Lesson 32 of 40

Chapter 32 — Designing a Fair Model Comparison

Common folds  • Common metrics  •  Comparable budgets  • Decision-ready evidence

Comparing algorithms as controlled experiments rather than as isolated scores

BRIDGE FROM CHAPTER 31  After handling imbalance and choosing metrics that reflect the real decision, the next task is to compare candidate algorithms fairly. A useful comparison controls data, folds, preprocessing, metrics, tuning effort, and test conditions so that differences can be attributed to the models rather than to the experiment.

Chapter map

Table 32.1. Chapter roadmap

Section

Main question

Key idea

32.1 Candidate model selectionWhich algorithms should enter the comparison?Choose representatives from different model families rather than many near-duplicates.
32.2 Fair comparison rulesWhat must stay controlled?Use the same data, folds, metrics, preprocessing discipline, test conditions, and comparable search effort.
32.3 Beyond the main scoreWhat else matters?Compare variability, fit/prediction time, memory, interpretability, robustness, and deployment effort.
32.4 Practical vs statistical significanceIs a small score gain meaningful?Consider uncertainty, operational value, and the cost of added complexity.
32.5 Selecting the final modelHow is the final choice made?Balance predictive evidence with operational, maintenance, legal, and ethical requirements.
Practical labWhich model should be recommended?Build a common comparison table and write a defensible final recommendation.

 

Chapter overview

Model comparison is an experimental-design problem. If one model receives more data, a different validation split, better preprocessing, a larger search budget, or a more favorable metric, its higher score does not provide clean evidence that the algorithm itself is better. A fair comparison controls these sources of variation before drawing conclusions.

The goal is not to produce a leaderboard with one number. A deployment decision usually depends on predictive performance, stability, computational cost, interpretability, robustness, maintenance, and constraints imposed by the application. The strongest recommendation is therefore the model that provides the best overall evidence for the intended operating environment—not automatically the model with the largest validation mean.

Learning objectives

  • Select candidate algorithms from meaningfully different model families.
  • Design a comparison in which data, validation folds, primary metric, preprocessing discipline, and test conditions are controlled.
  • Use comparable tuning or search budgets when hyperparameter optimization is part of the experiment.
  • Report validation mean, variability, fit time, prediction cost, model size, interpretability, robustness, and deployment considerations.
  • Distinguish a numerically higher score from a practically valuable improvement.
  • Use a protected test set only after the model-selection procedure is complete.
  • Build a model-comparison table and write a reasoned final-model recommendation.

32.1 Candidate model selection

A useful comparison should cover different inductive biases. Testing five nearly identical tree ensembles may tell us less than comparing one linear model, one distance-based model, one tree, one ensemble, and one kernel method. Diversity helps students learn which types of structure each family can represent and which operational trade-offs accompany that flexibility.

Table 32.2. Representative candidate families

Family

Example

Strengths to investigate

Typical trade-offs

LinearLogistic RegressionFast, interpretable coefficients, strong baselineLinear decision boundary unless features are engineered
Distance-basedK-Nearest NeighborsFlexible local decisions, simple trainingNeeds scaling; prediction can be slow; memory depends on stored training data
TreeDecision TreeNonlinear splits, interactions, visual explanationCan be unstable and overfit without constraints
EnsembleRandom ForestRobust nonlinear performance, interactions, averagingLarger model; less transparent than one tree
KernelRBF Support Vector MachineFlexible nonlinear boundary in transformed spaceScaling required; fit cost can grow on large datasets; lower direct interpretability

 

DESIGN PRINCIPLE  Candidate diversity should be purposeful. Include models because they provide different assumptions, operational profiles, or explanatory value—not merely because they are available in a library.

 

A controlled candidate set

PYTHON  •  Define five model families with leakage-safe pipelines

from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

models = {
    "Logistic Regression": make_pipeline(
        StandardScaler(), LogisticRegression(max_iter=2000)
    ),
    "KNN": make_pipeline(
        StandardScaler(), KNeighborsClassifier(n_neighbors=7)
    ),
    "Decision Tree": DecisionTreeClassifier(max_depth=5, random_state=42),
    "Random Forest": RandomForestClassifier(
        n_estimators=300, random_state=42, n_jobs=-1
    ),
    "RBF SVM": make_pipeline(
        StandardScaler(), SVC(kernel="rbf", C=1.0, gamma="scale")
    ),
}

 

 

The pipelines are not identical because the algorithms do not have identical preprocessing needs. Logistic Regression, KNN, and RBF SVM are scale-sensitive, so scaling is fitted inside each training fold. Tree-based models are normally unaffected by monotonic feature scaling and can use the original numerical values directly.

32.2 Fair comparison rules

Fairness in model comparison means controlling the experimental conditions that can influence the result. The comparison does not need to make every algorithm identical; it needs to ensure that each receives an appropriate, leakage-safe treatment under equivalent evaluation conditions.

Table 32.3. Core fairness rules

Rule

Why it matters

Good practice

Same training dataDifferent observations change the learning problemUse identical train/validation/test partitions for every candidate.
Same validation foldsFold difficulty can change scores materiallyCreate one CV splitter and reuse it for all models.
Same primary metricDifferent metrics reward different behaviorChoose the primary metric before comparing results.
Same preprocessing disciplinePreprocessing leakage can inflate scoresFit transformations inside a pipeline within each training fold.
Same test conditionsDifferent test sets destroy comparabilityEvaluate the selected procedure once on one protected test set.
Comparable search budgetsMore tuning trials increase the chance of finding a stronger configurationUse similar numbers of candidates/fits or explicitly report unequal budgets.

 

Reuse exactly the same validation folds

PYTHON  •  Create one shared cross-validation strategy

from sklearn.model_selection import StratifiedKFold

cv = StratifiedKFold(
    n_splits=5,
    shuffle=True,
    random_state=42,
)

# Reuse this same object for every candidate model.

 

 

Using the same folds creates a paired comparison: model A and model B are challenged by the same validation observations in each fold. This makes fold-by-fold differences more informative and avoids confusing model quality with an easier or harder random split.

Preprocessing discipline

  • Scaling, imputation, encoding, feature selection, and resampling should be learned only from training data.
  • A pipeline is the preferred way to repeat preprocessing correctly inside cross-validation.
  • A model should not be penalized for receiving preprocessing that it genuinely needs, but it should not receive information from validation or test data.
  • Feature engineering that uses historical/group statistics must follow the same leakage-safe timing rules described in Chapters 28 and 29.
COMMON MISTAKE  Scaling the complete dataset before cross-validation leaks validation-fold information into the training transformation. Put StandardScaler inside the pipeline so each fold learns its own mean and standard deviation.

 

Comparable search budgets

If candidates are tuned, the comparison should control tuning effort. A model evaluated with 100 hyperparameter configurations should not be presented as directly comparable to a model evaluated with two arbitrary settings unless that difference is acknowledged. Search budget can be measured by candidate configurations, total CV fits, compute time, or an explicitly fixed resource budget.

Total CV fits = number of candidates × number of folds

For a simple grid or randomized search; refitting and nested loops add additional work.

 

Table 32.4. Example search-budget accounting

Model

Candidates

CV folds

Approx. validation fits

Logistic Regression12560
Random Forest12560
RBF SVM12560

 

32.3 Comparing more than the main score

A validation score answers only one question: how well did the candidate optimize a particular predictive criterion under the chosen folds? Production decisions usually need a richer evidence table.

Table 32.5. Dimensions of a deployment-oriented comparison

Dimension

What to report

Why it matters

Mean validation performanceMean primary metric across foldsExpected predictive performance under the validation design
Score variabilityStandard deviation, min, max, fold scoresStability and sensitivity to data composition
Training timeMean/total fit timeRetraining cost and iteration speed
Prediction timePer-batch or per-observation latencyReal-time and throughput feasibility
Memory use / model sizeSerialized estimator size; runtime memory if measuredDeployment footprint and infrastructure cost
InterpretabilityCoefficients, tree rules, feature effects, explanation toolingAuditability and stakeholder understanding
RobustnessPerformance under shifts, noise, subgroups, or perturbationsReliability outside the average case
Ease of deploymentDependencies, preprocessing, latency, monitoring burdenEngineering and maintenance effort

 

Collect predictive scores and timing together

PYTHON  •  Use cross_validate for multiple metrics and timing

from sklearn.model_selection import cross_validate

scoring = {
    "roc_auc""roc_auc",
    "f1""f1",
    "balanced_accuracy""balanced_accuracy",
}

result = cross_validate(
    models["Logistic Regression"],
    X_train,
    y_train,
    cv=cv,
    scoring=scoring,
    return_train_score=False,
    n_jobs=-1,
)

print(result["test_roc_auc"].mean())
print(result["test_roc_auc"].std())
print(result["fit_time"].mean())
print(result["score_time"].mean())

 

 

The score_time value includes prediction and metric computation for the requested scoring functions, so it is useful for relative screening but is not the same as a carefully isolated production latency benchmark. When latency matters, benchmark prediction directly on a representative batch after fitting the final candidate.

Measure prediction time and serialized model size

PYTHON  •  A simple operational benchmark

from pathlib import Path
from time import perf_counter
import joblib

model = models["Random Forest"].fit(X_train, y_train)

start = perf_counter()
= model.predict(X_test)
predict_seconds = perf_counter() - start

path = Path("candidate_model.joblib")
joblib.dump(model, path)
size_mb = path.stat().st_size / (1024 ** 2)

print(f"Prediction time: {predict_seconds:.6f} s")
print(f"Serialized size: {size_mb:.3f} MB")

 

 

MEASUREMENT NOTE  Serialized file size is a practical deployment proxy, not a complete measurement of runtime memory. A rigorous memory benchmark requires environment-specific profiling and should be performed under the intended deployment stack.

 

Interpretability, robustness, and deployment

Not every comparison dimension is naturally a single number. Qualitative ratings can be useful when their criteria are defined before model selection. For example, a team might rate interpretability as High/Medium/Low based on whether the model provides globally understandable coefficients or rules, and deployment complexity based on preprocessing, dependency, memory, and latency requirements.

Table 32.6. Example qualitative rubric

Criterion

High / easy

Medium

Low / difficult

InterpretabilityCompact linear coefficients or small treePost-hoc explanations neededComplex nonlinear ensemble/kernel behavior
Deployment easeSmall artifact, simple preprocessing, low latencyModerate pipeline or artifact sizeLarge footprint, expensive inference, special dependencies
MaintenanceFew stable hyperparameters and simple monitoringModerate tuning/monitoring burdenFrequent retuning or complex monitoring dependencies

 

32.4 Practical versus statistical significance

A higher validation mean is not automatically an important improvement. Suppose model A has ROC AUC 0.941 and model B has 0.943. The difference of 0.002 may be smaller than ordinary fold-to-fold variation, may not change any operational decision, and may require substantially greater compute or complexity.

Measurement uncertainty

Cross-validation produces a distribution of scores rather than a perfectly known population performance. Mean and standard deviation summarize this evidence, but the folds are not independent replications of completely new datasets. Treat simple confidence intervals or hypothesis tests cautiously and avoid presenting them as stronger evidence than the experimental design supports.

PYTHON  •  Inspect paired fold differences

import numpy as np

score_a = np.array([0.9380.9470.936,  0.9440.940])
score_b = np.array([0.9410.9460.939,  0.9450.942])

delta = score_b - score_a
print("Mean improvement:", delta.mean())
print("Fold differences:", delta)
print("Improved folds:", (delta > 0).sum(), "of"len(delta))

 

 

Paired fold differences are useful because both candidates face the same fold. They show whether an improvement is consistent or driven by one favorable split. They do not, by themselves, prove that a tiny difference will generalize to every future dataset.

Practical significance

Table 32.7. Questions for practical significance

Question

Interpretation

Does the score gain change decisions?A small metric increase matters more if it catches materially more costly events at the chosen threshold.
Is the gain consistent?A gain that appears across folds/subgroups is more persuasive than one driven by a single split.
What does complexity cost?More memory, latency, retraining time, or explanation burden can outweigh a tiny score gain.
Is the gain robust?Check subgroup, temporal, noise, and distribution-shift behavior where relevant.
Can the gain be measured reliably?If uncertainty is larger than the improvement, describe the candidates as effectively similar rather than over-ranking them.

 

DECISION RULE   When two models are effectively tied on predictive evidence, prefer the one with the stronger operational profile: simpler explanation, lower latency, smaller footprint, easier maintenance, or lower risk.

 

32.5 Selecting the final model

Final-model selection should be a documented decision, not an automatic maximum-score lookup on one metric column. The selection criteria should reflect the use case and should ideally be defined before examining the final comparison table.

  • Predictive performance: primary metric and important secondary metrics.
  • Stability: fold-to-fold and subgroup variability.
  • Explainability: ability to justify predictions and model behavior to stakeholders.
  • Computational cost: training, prediction, infrastructure, and energy considerations.
  • Maintenance requirements: retraining frequency, monitoring complexity, tuning sensitivity, and dependencies.
  • Legal and ethical requirements: fairness, auditability, privacy, accessibility, human oversight, and domain-specific obligations.

A decision matrix

A weighted decision matrix can make trade-offs explicit, but the weights must reflect real requirements rather than being chosen to justify a preferred model after seeing the results. Hard constraints should usually be applied before weighted scoring—for example, a latency ceiling or a mandatory explainability requirement.

Decision score = Σ (criterion weight × normalized criterion score)

Use only when the criteria and weights have a defensible operational basis.

 

Table 32.8. Example decision criteria

Criterion

Example weight

Direction / requirement

ROC AUC35%Higher is better
F115%Higher is better
Validation stability15%Lower variability is better
Prediction latency10%Lower is better; may have a hard ceiling
Model size5%Lower is better when deployment footprint matters
Interpretability10%Higher is better
Maintenance / deployment ease10%Higher is better

 

GOVERNANCE NOTE  Legal and ethical requirements should not be reduced to a cosmetic score. Some requirements are constraints that a model must satisfy before it is eligible for deployment, even if another model has a slightly higher predictive metric.

 

Practical lab — Build a fair model-comparison table

Goal: compare five classifier families under one controlled experimental design, summarize predictive and operational evidence, and recommend one final model. The Breast Cancer Wisconsin dataset is used because it is small enough for classroom execution while supporting linear, distance-based, tree, ensemble, and kernel classifiers.

LAB DISCIPLINE  The test set is protected until the candidate-selection rule has been applied to cross-validation results. All models use the same training data, the same five stratified folds, and ROC AUC as the primary validation metric.

 

Step 1 — Load data and create one protected test set

PYTHON  •  Prepare the dataset

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True, as_frame=True)

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.20,
    stratify=y,
    random_state=42,
)

print(X_train.shape, X_test.shape)
print(y_train.value_counts(normalize=True).sort_index())

 

 

Step 2 — Define one CV strategy and the candidate models

PYTHON  •  Shared folds and candidate models

from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

models = {
    "Logistic Regression": make_pipeline(
        StandardScaler(), LogisticRegression(max_iter=2000)
    ),
    "KNN": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=7)),
    "Decision Tree": DecisionTreeClassifier(max_depth=5, random_state=42),
    "Random Forest": RandomForestClassifier(
        n_estimators=300, random_state=42, n_jobs=-1
    ),
    "RBF SVM": make_pipeline(
        StandardScaler(), SVC(kernel="rbf", C=1.0, gamma="scale")
    ),
}

 

 

Step 3 — Evaluate every model on exactly the same folds

PYTHON  •  Collect validation means, variability, and timing

import numpy as np
import pandas as pd
from sklearn.model_selection import cross_validate

scoring = {
    "roc_auc""roc_auc",
    "f1""f1",
    "balanced_accuracy""balanced_accuracy",
}

rows = []
fold_scores = {}

for name, model in models.items():
    cv_result = cross_validate(
        model,
        X_train,
        y_train,
        cv=cv,
        scoring=scoring,
        n_jobs=-1,
    )
    auc = cv_result["test_roc_auc"]
    fold_scores[name] = auc
    rows.append({
        "model": name,
        "auc_mean": auc.mean(),
        "auc_std": auc.std(),
        "auc_min": auc.min(),
        "auc_max": auc.max(),
        "f1_mean": cv_result["test_f1"].mean(),
        "balanced_acc_mean": cv_result["test_balanced_accuracy"].mean(),
        "fit_time_s": cv_result["fit_time"].mean(),
        "score_time_s": cv_result["score_time"].mean(),
    })

comparison = pd.DataFrame(rows).sort_values("auc_mean", ascending=False)
print(comparison.round(4))

 

 

Step 4 — Visualize mean performance and variability

PYTHON  •  Plot a validation comparison

import matplotlib.pyplot as plt

plot_df = comparison.sort_values("auc_mean")
plt.figure(figsize=(84.5))
plt.errorbar(
    plot_df["auc_mean"],
    plot_df["model"],
    xerr=plot_df["auc_std"],
    fmt="o",
    capsize=4,
)
plt.xlabel("Mean ROC AUC ± fold standard deviation")
plt.ylabel("Model")
plt.title("Fair cross-validated model comparison")
plt.tight_layout()
plt.show()

 

 

Do not rank models from the plot by mean alone. Look for overlap in fold variability, then inspect secondary metrics and operational evidence before recommending a final candidate.

Step 5 — Fit candidates and benchmark prediction time and size

PYTHON  •  Operational benchmark on the same test batch

from pathlib import Path
from time import perf_counter
import joblib

operational = []

for name, model in models.items():
    fitted = model.fit(X_train, y_train)

    start = perf_counter()
    _ = fitted.predict(X_test)
    predict_ms = (perf_counter() - start) *1000

    safe_name = name.lower().replace(" ""_")
    path = Path(f"{safe_name}.joblib")
    joblib.dump(fitted, path)
    size_mb = path.stat().st_size  / (1024** 2)

    operational.append({
        "model": name,
        "predict_ms": predict_ms,
        "size_mb": size_mb,
    })

operational = pd.DataFrame(operational)
comparison = comparison.merge(operational, on="model")
print(comparison.round(4))

 

 

BENCHMARK CAUTION  One timing run is suitable for a classroom demonstration, not a production latency guarantee. Real benchmarking should include warm-up, repeated runs, representative batch sizes, fixed hardware, and percentile latency such as p50/p95/p99.

 

Step 6 — Add qualitative deployment criteria

PYTHON  •  Attach a transparent qualitative rubric

qualitative = pd.DataFrame([
    ["Logistic Regression""High""High"],
    ["KNN""Medium""Medium"],
    ["Decision Tree""High""High"],
    ["Random Forest""Medium""Medium"],
    ["RBF SVM""Low""Medium"],
], columns=["model""interpretability""deployment_ease"])

comparison = comparison.merge(qualitative, on="model")
print(comparison.to_string(index=False))

 

 

These ratings are illustrative and should be replaced by criteria appropriate to the actual deployment environment. For example, an edge device may weight memory and latency more heavily, while a regulated decision-support application may place greater weight on explanation and auditability.

Step 7 — Inspect paired fold differences between the leaders

PYTHON  •  Check whether the apparent gain is consistent

leaders = comparison.head(2)["model"].tolist()
= fold_scores[leaders[0]]
= fold_scores[leaders[1]]

delta =- b
print("Leaders:", leaders)
print("Fold differences:", np.round(delta, 4))
print("Mean paired difference:", delta.mean().round(4))
print("Winner by fold:", (delta > 0).sum(), "of"len(delta))

 

 

If the leading mean differs by only a few thousandths and the paired fold differences change sign, describe the models as close on predictive evidence. The final recommendation can then legitimately depend on latency, model size, interpretability, robustness, or maintenance needs.

Step 8 — Apply a documented selection rule

Before touching the test labels, students should write a selection rule. One example is: choose any model whose mean ROC AUC is within 0.005 of the best candidate, then prefer lower variability; if candidates remain close, prefer the simpler model with better interpretability and deployment ease.

PYTHON  •  Example rule: identify near-best candidates

best_auc = comparison["auc_mean"].max()
near_best = comparison[
    comparison["auc_mean">= best_auc -0.005
].copy()

near_best = near_best.sort_values(
    ["auc_std""predict_ms""size_mb"],
    ascending=[TrueTrueTrue],
)

print(near_best[
    ["model""auc_mean""auc_std""predict_ms""size_mb",
     "interpretability""deployment_ease"]
].round(4))

 

 

IMPORTANT   The code above does not automatically encode interpretability or legal requirements. The final recommendation must apply those criteria explicitly rather than pretending every decision can be reduced to one numeric sort order.

 

Step 9 — Evaluate the selected model once on the protected test set

PYTHON  •  Final test evaluation

from sklearn.metrics import (
    accuracy_score,
    f1_score,
    roc_auc_score,
)

# Replace with the model selected by your documented rule.
selected_name = near_best.iloc[0]["model"]
selected_model = models[selected_name].fit(X_train, y_train)

pred = selected_model.predict(X_test)

if hasattr(selected_model,  "predict_proba"):
    score = selected_model.predict_proba(X_test)[:, 1]
else:
    score = selected_model.decision_function(X_test)

print("Selected model:", selected_name)
print("Test accuracy:", accuracy_score(y_test, pred))
print("Test F1:", f1_score(y_test, pred))
print("Test ROC AUC:", roc_auc_score(y_test, score))

 

 

The test set verifies the selected procedure. If another candidate happens to score higher on the test set, do not restart selection by cycling through candidates on the same test set; doing so converts the test set into another validation set.

Step 10 — Build the final model-comparison table

Table 32.9. Recommended student comparison table

Model

CV AUC mean ± SD

F1

Fit time

Pred. time

Size

Interpret.

Deploy.

Logistic RegressionHighHigh
KNNMediumMedium
Decision TreeHighHigh
Random ForestMediumMedium
RBF SVMLowMedium

 

Student deliverable — Final recommendation

Write a short recommendation of approximately 250–400 words containing:

  1. The primary validation metric and why it was chosen.
  2. The leading models and their mean score, variability, and important secondary metrics.
  3. Whether the observed score differences are large enough to matter operationally.
  4. The main trade-offs in training time, prediction time, model size, interpretability, robustness, and deployment.
  5. The selected final model and the specific reasons it best satisfies the application requirements.
  6. Any legal, ethical, monitoring, or maintenance constraints that must be addressed before deployment.
RECOMMENDED WRITING PATTERN  Evidence → trade-off → decision. Avoid statements such as “Random Forest is best because it has the highest score.” Explain why the score difference is meaningful—or why another model is preferable despite a slightly lower score.

 

Lab reflection questions

1.  Why is reusing exactly the same CV folds more informative than giving every model a different random split?

2.  Why is scaling KNN and SVM but not necessarily Random Forest still a fair comparison?

3.  If two candidates differ in ROC AUC by 0.002 but one is ten times faster, what additional evidence would you examine before choosing?

4.  Why can unequal hyperparameter search budgets bias a comparison?

5.  What is the difference between cross-validation variability and production robustness?

6.  When should interpretability or a legal requirement override a small predictive advantage?

7.  Why should the protected test set not be used repeatedly to choose among candidate models?

Chapter summary

Table 32.10. Key takeaways

Topic

Takeaway

Candidate modelsChoose meaningfully different families to explore distinct assumptions and trade-offs.
Fairness controlsUse the same data, folds, metric, leakage-safe preprocessing discipline, test conditions, and comparable tuning effort.
Beyond one scoreReport variability, speed, footprint, interpretability, robustness, deployment, and maintenance evidence.
SignificanceA numerically higher score may be too small or uncertain to justify extra complexity.
Final selectionThe best model is the one that best satisfies predictive and operational requirements under documented constraints.
Train a Supervised Machine Learning Model
1 Chapter 1 — Introduction to Machine Learning 2 Chapter 2 — Understanding Supervised Learning 3 Chapter 3 — The Complete Supervised Learning Workflow 4 Chapter 4 — Defining the Machine Learning Problem 5 Chapter 5 — Loading and Inspecting Data 6 Chapter 6 — Exploratory Data Analysis 7 Chapter 7 — Cleaning the Dataset 8 Chapter 8 — Feature and Target Preparation 9 Chapter 9 — Splitting the Dataset Correctly 10 Chapter 10 — Numerical Feature Preprocessing 11 Chapter 11 — Encoding Categorical Features 12 Chapter 12 — Preprocessing Pipelines 13 Chapter 13 — Baseline Models 14 Chapter 14 — Logistic Regression 15 Chapter 15 — K-Nearest Neighbors Classification 16 Chapter 16 — Decision Tree Classification 17 Chapter 17 — Ensemble Classification Models 18 Chapter 18 — Support Vector Machines 19 Chapter 19 — Linear Regression 20 Chapter 20 — Regularized Regression 21 Chapter 21 — Tree-Based Regression 22 Chapter 22 — Confusion Matrix and Basic Metrics 23 Chapter 23 — Probability-Based Classification Evaluation 24 Chapter 24 — Regression Metrics 25 Chapter 25 — Residual Analysis 26 Chapter 26 — Underfitting and Overfitting 27 Chapter 27 — Cross-Validation 28 Chapter 28 — Feature Engineering 29 Chapter 29 — Feature Selection 30 Chapter 30 — Hyperparameter Tuning 31 Chapter 31 — Handling Imbalanced Classification 32 Chapter 32 — Designing a Fair Model Comparison 33 Chapter 33 — Final Test Evaluation 34 Chapter 34 — Global Model Interpretation 35 Chapter 35 — Local Prediction Explanation 36 Chapter 36 — Error Analysis and Robustness 37 Chapter 37 — Fairness and Ethical Considerations 38 Chapter 38 — Model Persistence 39 Chapter 39 — Building a Basic Prediction Application 40 Chapter 40 — Monitoring a Supervised Model