Model Evaluation and Validation

Learn how to tell whether a machine learning model will work on data it has never seen. Measure regression models with MAE, RMSE and R², and classifiers with the confusion matrix, precision, recall, F1, ROC curves and AUC. Estimate performance honestly with held-out data and cross-validation, diagnose underfitting and overfitting with the bias–variance tradeoff and learning curves, and tune hyperparameters and choose a final model while keeping the test set for one last, unbiased check. Examples use Python and scikit-learn.

IntermediateLesson 4 of 9 in Machine Learning Course

What you will learn

  1. Summarize the errors of a regression model with MAE, MSE, RMSE and R2, compare them with a simple baseline, and choose the measure that fits the cost of mistakes.
    • Compute MAE, MSE and RMSE from residuals
      Turn a model's prediction errors into MAE, MSE and RMSE, read them in the target's units, and see how each one treats large errors.
    • Interpret R² and compare against a baseline
      Compute the coefficient of determination, read what values from 1 down to below 0 mean, and judge every regression score against a simple baseline model.
  2. Count a classifier's correct and wrong predictions in a confusion matrix, see why accuracy can mislead, and compute precision, recall and F1 for binary and multiclass problems.
    • Build and read a confusion matrix
      Sort predictions into true and false positives and negatives, compute accuracy, and recognize when a high accuracy hides a useless model.
    • Calculate precision, recall and F1
      Compute precision, recall, specificity and F1 from a confusion matrix, decide which matters for a task, and average them over several classes.
  3. Choose a decision threshold for a task, draw and read ROC and precision–recall curves, and interpret AUC and average precision as threshold-free summaries.
    • Move the decision threshold to trade precision for recall
      See how the threshold on a classifier's scores changes precision and recall, read a precision–recall curve, and pick a threshold from the costs of errors.
    • Draw and read an ROC curve
      Plot the true positive rate against the false positive rate across thresholds, and read the curve's shape, corners and diagonal.
    • Interpret AUC and choose between ROC and precision–recall summaries
      Read AUC as a ranking probability, know what it does and does not measure, and switch to precision–recall summaries when positives are rare.
  4. Split data so that the evaluation reflects new data, run k-fold cross-validation, and choose a splitting scheme that prevents leakage for grouped, time-ordered or imbalanced data.
    • Split data into training, validation and test sets
      Give each data split its role, size the splits sensibly, and keep information from the evaluation data out of training.
    • Run k-fold cross-validation
      Carry out k-fold cross-validation step by step, report the mean and spread of the fold scores, and choose k with its costs in mind.
    • Match the splitting scheme to the data and keep preprocessing inside the folds
      Pick stratified, grouped or time-ordered cross-validation to fit the data, and run every data-dependent preprocessing step inside the folds with a pipeline.
  5. Explain the bias–variance tradeoff, tell high bias from high variance using training error, validation error and a baseline, and read learning curves to decide what will improve a model.
    • Explain the bias–variance tradeoff
      Describe bias, variance and irreducible error, see how model flexibility moves them, and connect them to underfitting and overfitting.
    • Diagnose high bias or high variance from training and validation error
      Compare training and validation error with a baseline level of performance, name the problem, and choose the changes most likely to help.
    • Read learning curves
      Plot training and validation error against the number of training examples and read the shapes that signal high bias, high variance or a good fit.
  6. Search hyperparameters with cross-validation, keep the test set for one final check, and choose and report a model with honest estimates of its performance.
    • Search hyperparameters with cross-validation
      Tell parameters from hyperparameters, run grid and random searches with cross-validation, and score the search with a metric that fits the task.
    • Keep the test set untouched until the final check
      Explain why repeated use of evaluation data inflates scores, use the test set once, and apply nested cross-validation when data are scarce.
    • Compare candidate models and report the chosen one
      Compare models fairly on the same folds, prefer the simpler model when scores are close, and report the result with its baseline and uncertainty.

Model Evaluation and Validation study guide

6 chapters

1

Measure how well a regression model predicts

Good regression predictions need errors that are small enough for the task, not just a high score. Start with individual residuals, then see how absolute values and squares turn them into useful summaries. Compare those summaries with simple constant predictions and read R² as a relative improvement. Unit-based errors, a fitted baseline and residual patterns together show what a single headline number can hide.

1.1 Compute MAE, MSE and RMSE from residuals

A residual is the actual value minus the prediction: ei=yi−y^i. Positive means the prediction was too low; negative means it was too high. To estimate performance on new cases, calculate errors on held-out rows that did not train the model.

Turn residuals into error sizes

Signed errors can cancel. Absolute values and squares prevent that cancellation:

MAE=1n∑i∣ei∣,MSE=1n∑iei2,RMSE=MSE.

All three are zero for perfect predictions, and lower is better. MAE and RMSE use the target's unit. MSE uses its square: minutes² for a duration measured in minutes.

Consider delivery times of 12, 15, 20, 30 and 18 minutes, predicted as 14, 15, 17, 24 and 20 minutes.

QuantityValuesTotal
Residual−2, 0, 3, 6, −25
Absolute residual2, 0, 3, 6, 213
Squared residual4, 0, 9, 36, 453

Divide the absolute total by five: MAE is 2.6 minutes. Divide the squared total by five: MSE is 10.6 minutes². Then take the square root: RMSE is about 3.26 minutes. Taking the square root before averaging would give MAE instead.

The mean signed residual is just 1 minute. It describes a tendency to predict too low, but conceals the size of the individual errors.

Choose the penalty that fits the task

MAE gives each extra unit of error the same weight. RMSE responds more strongly to large mistakes because squaring happens before averaging. On the same rows, RMSE is at least MAE; they are equal only when all absolute residuals are equal.

If the last actual delivery time changes from 18 to 48 minutes, its residual changes from −2 to 28. MAE rises to 7.8 minutes, while RMSE rises to about 12.91 minutes. That large gap points to uneven errors, including a particularly large one. Inspect those cases instead of treating the gap as a complete diagnosis.

NeedUseful metricReason
Each minute of error has similar costMAEAbsolute errors grow linearly
A large miss is especially costlyRMSESquaring gives large errors extra weight
Smooth squared-error training objectiveMSEConvenient to minimize during fitting

A constant mean prediction minimizes squared error; a constant median prediction minimizes absolute error. For these actual times, the mean is 19 and the median is 18. Predicting 19 throughout gives MAE 4.8 minutes, versus 4.6 minutes for 18.

Compute and report the metric
from sklearn.metrics import (
    mean_absolute_error, mean_squared_error,
    root_mean_squared_error,
)
mae = mean_absolute_error(y_true, y_pred)
mse = mean_squared_error(y_true, y_pred)
rmse = root_mean_squared_error(y_true, y_pred)

Cross-validation scorers use greater-is-better values. Negate results from "neg_mean_absolute_error" or "neg_root_mean_squared_error" to report positive errors. A score of −3 is better than −5.

Compare models on the same rows and target. An RMSE of 3 minutes has a different meaning from 3 °C. Percentage error, MAPE, divides by the actual value; the usual formula is undefined at zero and unstable near zero. Scikit-learn substitutes a tiny denominator at zero, which can produce a huge finite value, not a useful percentage.

Key Takeaways

  • MAE averages absolute residuals; RMSE takes the square root of the mean squared residual.
  • MAE and RMSE use target units; MSE uses squared units.
  • RMSE gives large errors extra weight. Choose the metric from the cost of errors.
  • A mean constant minimizes squared error; a median constant minimizes absolute error.
  • Negate error scorers before reporting cross-validation errors.
  • MAPE is unsuitable when actual values are zero or close to zero.

1.2 Interpret R² and compare against a baseline

An error in minutes tells you how far predictions miss. R², the coefficient of determination, asks how much squared error the model removes compared with a constant mean reference.

Work from two sums of squares

For nonconstant evaluation targets,

R2=1−SSresSStot=1−∑i(yi−y^i)2∑i(yi−yˉ)2.

Here yˉ is the mean of the evaluation targets. The numerator measures the model's squared errors; the denominator measures the squared errors of always predicting that evaluation mean.

For delivery times 12, 15, 20, 30 and 18 minutes, the mean is 19. The deviations from it are −7, −4, 1, 11 and −1, giving a total squared deviation of 188. Predictions of 14, 15, 17, 24 and 20 give a residual sum of squares of 53. Thus R2=1−53/188≈0.718: about 72% of the mean reference's squared error has been removed.

ValueInterpretation
1Perfect predictions
0Same squared error as the evaluation-mean reference
Below 0More squared error than that reference

Predicting 25 minutes for each delivery gives squared error 368 and R2=1−368/188≈−0.957. A negative value is a valid result; there is no lower bound. The square in the name does not force the score to be positive.

Fit a usable baseline

The reference inside R² knows the evaluation mean. A deployed constant cannot know future targets. Fit a baseline on training data, then evaluate it on exactly the same held-out rows as the model:

from sklearn.dummy import DummyRegressor
from sklearn.metrics import r2_score
baseline = DummyRegressor(strategy="mean")
baseline.fit(X_train, y_train)
baseline_pred = baseline.predict(X_val)
r2 = r2_score(y_val, model.predict(X_val))

A training-mean baseline usually has held-out R² slightly below zero because its mean differs from the evaluation mean. Use a median baseline when MAE is the main criterion. Do not refit either baseline on validation targets before comparing predictive performance.

Read R² beside other evidence

R² has no unit, but it depends on the evaluation targets' spread. The same RMSE can produce a higher R² when the targets vary more. Scores from different data sets therefore do not give a fair model ranking.

Training R² is also optimistic. In least-squares regression with an intercept, adding predictors cannot lower training R², even if they add noise. Adjusted R² makes a classical predictor-count correction; held-out scoring directly checks generalization.

Look at a residual plot, with residuals against predictions. A curve suggests a missed relationship; a funnel suggests that error size changes across predictions. R² alone cannot show these patterns or establish causation. Report a unit-based error as well: "Test RMSE is 3.3 minutes, versus 6.1 for the mean baseline; R² is 0.72."

If all evaluation targets are equal, the denominator of R² is zero. The mathematical ratio is undefined; r2_score normally substitutes 1 for perfect predictions and 0 for imperfect ones. Inspect such folds instead of applying the usual interpretation. A regressor's .score(X, y) returns R²; r2_score takes actual values first.

Key Takeaways

  • R² compares the model with the mean of the evaluation targets.
  • Negative R² means more squared error than that mean reference.
  • Fit predictive baselines on training data and score them on the same held-out rows.
  • Report a unit-based error and inspect residual patterns alongside R².
  • Training R² and scores from different data sets cannot establish generalization.
2

Evaluate classifiers with the confusion matrix

A classifier can make false alarms and misses with very different consequences. Count those outcomes before choosing a score. The confusion matrix shows where errors occur; precision, recall and F1 summarize selected parts of it. Accuracy needs a baseline when classes are imbalanced. With multiple classes, the averaging method decides whether each class or each example receives equal influence.

2.1 Build and read a confusion matrix

A classifier makes two different kinds of mistake: it can flag a negative case or miss a positive one. A confusion matrix keeps those errors separate. First name the positive class, such as spam, and keep that meaning fixed.

Read actual and predicted labels

Scikit-learn puts actual classes in rows and predicted classes in columns. With class order 0, 1, the layout is [[TN, FP], [FN, TP]].

Actual classPredicted negativePredicted positive
NegativeTrue negative: TNFalse positive: FP
PositiveFalse negative: FNTrue positive: TP

"True" means the prediction is correct. "Positive" in TP or FP describes the prediction. A false positive is a false alarm, also called a Type I error; a false negative is a miss, also called a Type II error. Read axis labels before using a matrix from another tool because layouts vary.

Recover the four counts

A spam filter is evaluated on 1000 emails. There are 100 actual spam messages. It flags 110 emails, and 80 of them are spam.

  1. The 80 correctly flagged messages are TP.
  2. The other flagged messages give FP=110−80=30.
  3. The remaining actual spam gives FN=100−80=20.
  4. There are 900 legitimate emails, so TN=900−30=870.

Check row totals: the positive row contains 100 messages and the negative row 900. The predicted-positive column contains 110. These checks catch a swapped FP and FN.

Accuracy is the fraction of all predictions that are correct:

accuracy=TP+TNTP+FP+FN+TN.

Here accuracy is 950/1000=0.95. The error rate is 0.05. This single fraction counts false alarms and misses equally even when their practical costs differ.

Check what accuracy hides

If only 100 of 10000 transactions are fraudulent, predicting "legitimate" every time achieves 99% accuracy and finds no fraud. This is the accuracy paradox: a large majority class dominates the score. Compare against DummyClassifier(strategy="most_frequent"), fitted on training data, and inspect both error types.

The cost can change with the application. Blocking a legitimate transaction creates a false alarm; accepting a fraudulent one creates a miss. The matrix shows the counts you need to evaluate those consequences.

Extend the table to several classes

With three ticket classes, a matrix may have actual rows billing [50, 5, 5], technical [10, 25, 5], and account [2, 3, 15]. Its diagonal contains the correct counts: 50, 25 and 15. Accuracy is 90/120=0.75. The off-diagonal count 10 shows technical tickets predicted as billing, the largest single confusion.

from sklearn.metrics import confusion_matrix, accuracy_score
matrix = confusion_matrix(y_val, predictions, labels=[0, 1])
accuracy = accuracy_score(y_val, predictions)

The matrix describes predictions at one threshold. If a threshold change moves an actual positive across the boundary, it moves between TP and FN. An actual negative moves between FP and TN. A change that crosses no scores leaves the matrix unchanged.

Key Takeaways

  • Name the positive class and read the matrix axes before interpreting counts.
  • Scikit-learn uses actual rows and predicted columns: [[TN, FP], [FN, TP]].
  • Accuracy counts correct predictions across all classes and can hide missed rare cases.
  • Compare with a majority-class baseline and inspect off-diagonal errors.

2.2 Calculate precision, recall and F1

Precision and recall answer different questions about the positive class. Precision asks how trustworthy positive predictions are. Recall, also called sensitivity or true positive rate, asks how many actual positives were found.

Choose the right denominator
P=TPTP+FP,R=TPTP+FN.

Precision divides by predicted positives; recall divides by actual positives. For a spam filter with TP 80, FP 30, FN 20 and TN 870, precision is 80/110≈0.727 and recall is 80/100=0.80.

The negative class has its own recall, specificity:

specificity=TNTN+FP,FPR=FPFP+TN=1−specificity.

Specificity here is about 0.967, so the false positive rate is about 0.033. FPR divides false alarms by actual negatives, not by alerts. The fraction of alerts that are false is one minus precision.

Practical concernMain quantity to inspect
Flagged legitimate messages are costlyPrecision
Missing actual spam is costlyRecall
Correctly leaving negatives alone mattersSpecificity

A model can achieve recall 1 by flagging everything, but its precision then equals the positive share. Flagging just one obvious positive can achieve precision 1 with very low recall. Always inspect both. If there are no predicted positives, precision has a zero denominator; scikit-learn's default returns 0 with a warning, and zero_division controls the convention.

Combine precision and recall carefully

F1 is their harmonic mean:

F1=2PRP+R=2TP2TP+FP+FN.

For the spam filter, F1=160/210≈0.762. With precision 1 and recall 0.10, F1 is only about 0.182, not their ordinary mean of 0.55. A weak component holds F1 down.

F1 gives precision and recall equal emphasis and ignores true negatives. F-beta changes that emphasis: beta above 1 favors recall, below 1 favors precision. When explicit false-alarm and miss costs are available, calculate expected cost directly instead of asking F1 to represent those costs.

Average over classes

Treat each class as positive in turn. For ticket rows billing [50, 5, 5], technical [10, 25, 5], account [2, 3, 15], billing precision is 50/62≈0.806 and recall is 50/60≈0.833. Technical precision is about 0.758 and recall 0.625; account precision is 0.600 and recall 0.750. Their F1 scores are about 0.820, 0.685 and 0.667.

AverageMethodTicket F1
MacroMean of class F1 scores0.724
WeightedWeight by actual class counts0.749
MicroPool TP, FP and FN before calculating0.750

Macro gives every class equal importance. Weighted scores give larger classes more influence; compare class-level scores when they hide weak small classes. For single-label multiclass predictions across all classes, micro F1 equals accuracy.

classification_report(y_true, y_pred) shows class scores and their averages. Select f1_score(y_true, y_pred, average="macro") when each class should count equally. State the averaging method with every multiclass result.

Key Takeaways

  • Precision uses predicted positives; recall uses actual positives.
  • Specificity is negative-class recall; FPR is one minus specificity.
  • F1 is a harmonic mean and ignores true negatives.
  • F-beta above beta 1 emphasizes recall; below 1 emphasizes precision.
  • Macro averages classes equally; weighted uses class sizes; micro pools counts.
  • State the class and averaging method when reporting a score.
3

Compare classifiers across thresholds with ROC and precision–recall curves

One classifier can produce many different decisions from the same scores. Moving a threshold changes which cases are flagged and the resulting balance of detections and false alarms. ROC and precision–recall curves show those choices across cutoffs; AUC and average precision summarize their rankings. The practical choice still depends on costs, class balance and performance at the threshold you will actually use.

3.1 Move the decision threshold to trade precision for recall

A classifier's score ranks how likely a case is to be positive. A decision threshold converts that score into a label. In the examples here, a case is positive when its score is at least the threshold. Choosing that cutoff is part of model selection.

Follow the cases that cross

Ten validation scores are 0.95, 0.85, 0.80, 0.70, 0.55, 0.45, 0.40, 0.30, 0.20 and 0.10. The positives have scores 0.95, 0.85, 0.70 and 0.45.

ThresholdTPFPFNPrecisionRecall
0.752120.6670.50
0.503210.6000.75
0.404300.5711.00

At 0.50, five scores pass, three of them positive. Lowering the cutoff to 0.40 admits the remaining positive and another negative. Recall rises because a miss becomes a detection, but the added false alarm reduces precision.

Raising the threshold can only keep or reduce the number of detected positives, so recall cannot increase. Precision has no such guarantee: removing a true positive can lower it. In this table, threshold 0.70 gives precision 0.75, higher than the 0.667 at the stricter threshold 0.80.

Read a precision–recall curve

A precision–recall curve plots recall horizontally and precision vertically as the threshold changes. Average precision, AP, weights each precision by the increase in recall:

AP=∑j(Rj−Rj−1)Pj.

Here recall increases by 0.25 at each of the four positives. Their precisions when admitted are 1, 1, 0.75 and 4/6. AP is about 0.854. This is a step-weighted summary, not a trapezoidal area using straight lines between PR points. The positive share is the usual large-sample random-ranking reference. On this tiny ten-case sample it is 0.4, but expected AP over random rankings is about 0.529; the reference is not exact for every sample size.

Pick a useful operating point

Suppose a miss costs 10 units and a false alarm costs 1. Compare validation costs with C=10FN+FP:

  • At 0.85, two misses and no false alarms cost 20.
  • At 0.70, one miss and one false alarm cost 11.
  • At 0.45, no misses and two false alarms cost 2.
  • At 0.40, no misses and three false alarms cost 3.

Threshold 0.45 is cheapest among these candidates. A constraint can also set the operating point, such as the highest recall while precision remains at least 0.9.

For calibrated probabilities, cases scored about 0.2 are positive about 20% of the time. With zero cost for correct decisions, predicting positive has expected cost (1−p)CFP and predicting negative has cost pCFN. Choose positive when p≥CFP/(CFP+CFN); costs 1 and 10 give about 0.09. Arbitrary ranking scores do not support that probability calculation.

Apply the chosen rule
scores = model.predict_proba(X_val)[:, 1]
labels = (scores >= threshold).astype(int)

Column 1 is the positive score when model.classes_ is [0, 1]. Scikit-learn's default binary predict uses a strict probability cutoff above 0.5; the code makes the at-least convention explicit at ties. Choose the threshold on validation data or with TunedThresholdClassifierCV, never from test results. Report it beside precision and recall.

Key Takeaways

  • Raising the threshold cannot increase recall; precision can move either way.
  • A precision–recall curve follows both measures across cutoffs.
  • Average precision weights precision by each increase in recall.
  • Choose thresholds on validation data from costs or a practical constraint.
  • The cost-derived probability threshold requires calibrated probabilities.

3.2 Draw and read an ROC curve

An ROC curve, or receiver operating characteristic curve, follows detections and false alarms across decision thresholds. Its vertical axis is true positive rate, which equals recall; its horizontal axis is false positive rate.

Build the axes from actual classes
TPR=TPTP+FN,FPR=FPFP+TN.

Each rate uses an actual-class total. This is why an ROC curve differs from a precision–recall curve: precision divides by predicted positives and responds directly to the balance of true and false alerts.

Start above the largest score, so nothing is flagged. The curve begins at (0, 0). Lower the threshold through all scores until everything is flagged, reaching (1, 1). The top-left corner, (0, 1), means every positive found and no negative flagged.

Walk through a ranked list

Use ten descending scores: 0.95 positive, 0.85 positive, 0.80 negative, 0.70 positive, 0.55 negative, 0.45 positive, then 0.40, 0.30, 0.20 and 0.10 all negative. There are four positives and six negatives.

Passing a positive moves vertically by 1/4=0.25. Passing a negative moves horizontally by 1/6≈0.167. The first six moves are:

  1. Up to (0, 0.25), then (0, 0.50).
  2. Right to (0.167, 0.50).
  3. Up to (0.167, 0.75).
  4. Right to (0.333, 0.75).
  5. Up to (0.333, 1).

The remaining negatives move the curve right along the top to (1, 1). At threshold 0.50, the point is (0.333, 0.75). About one third of negatives are flagged while three quarters of positives are found.

Compare the relevant region

The diagonal represents random scores on average. Scores with reversed ranking tend to produce a curve below it; reversing their order reverses that ranking. Finite samples can wander above and below the diagonal.

If one model reaches at least as high a TPR at every FPR, its curve dominates the other. Equal numerical thresholds are unnecessary: models can express scores on different scales. If curves cross, choose using the region that matters. An alert system that allows at most 1% false alarms needs strong performance near the left edge, even if another model performs better elsewhere.

Changing only the class proportions leaves the ROC curve unchanged when the score distribution within each class stays the same. Both axes divide within a class. This is useful for ranking comparisons, but it hides the number of false alerts relative to true alerts when positives are rare.

Supply scores to the software
from sklearn.metrics import roc_curve, RocCurveDisplay
scores = model.predict_proba(X_val)[:, 1]
fpr, tpr, thresholds = roc_curve(y_val, scores)
RocCurveDisplay(fpr=fpr, tpr=tpr).plot()

Use probabilities for class 1 or a decision_function oriented toward that class. Hard labels give only one nontrivial operating point and discard the detailed ranking. For multiple classes, use one-vs-rest curves: select a class as positive and combine the others as negative.

Key Takeaways

  • ROC plots TPR vertically against FPR horizontally.
  • Each positive crossed moves up by 1/P; each negative crossed moves right by 1/N.
  • The top-left corner is perfect; the diagonal is the average random-ranking reference.
  • When curves cross, compare the false-alarm range that matters for the task.
  • Use scores, not hard predictions, to preserve the full ranking.
  • ROC is unchanged by class proportions alone if within-class score distributions stay fixed.

3.3 Interpret AUC and choose between ROC and precision–recall summaries

ROC AUC summarizes an ROC curve by its area. It measures how well scores rank positives above negatives, across thresholds. It does not tell you the accuracy at a particular cutoff.

Count positive–negative pairs

Choose one positive and one negative at random. AUC is the chance that the positive scores higher, counting a tie as half a success:

AUC=correctly ordered pairs+0.5 tied pairsall positive–negative pairs.

For positives scored 0.95, 0.85, 0.70 and 0.45, and negatives scored 0.80, 0.55, 0.40, 0.30, 0.20 and 0.10, there are 4×6=24 pairs. The first two positives each beat all six negatives. The third beats five and the fourth beats four. Thus AUC=(6+6+5+4)/24=0.875. The staircase ROC area gives the same result.

An AUC of 1 means all positives rank above all negatives. Random ranking has expected AUC 0.5. A result below 0.5 indicates more reversed than correctly ordered pairs. A single measured 0.5 can also arise from a ranking pattern that is not random; it is the pair score that matches the random reference.

Separate ranking from decisions

AUC depends on order. Squaring probabilities preserves their order and therefore preserves AUC, even though the numbers change and may become poorly calibrated. AUC cannot establish that scores of 0.8 correspond to an 80% positive rate.

Two models can also have different curve shapes with the same area. A model with a strong overall AUC can perform poorly in the small false-alarm region you need. Report useful operating-point metrics as well as the area.

Count alerts when positives are rare

Suppose an evaluation set contains 100 positives and 10000 negatives. A point with TPR 0.90 and FPR 0.05 gives 90 true alerts but 500 false alerts. Precision is 90/(90+500)≈0.153. A small negative-class error rate still produces a large workload because there are so many negatives.

QuestionUseful evidence
How well are classes ranked?ROC curve and ROC AUC
How reliable are alerts for rare positives?Precision–recall curve and AP
What happens at the deployed cutoff?Precision, recall and confusion matrix there

Average precision responds directly to the positive share, so compare AP on evaluation data with comparable prevalence. ROC AUC is insensitive to prevalence changes alone, provided the score distributions within classes stay fixed. Neither summary replaces the actual counts needed for staffing or error-cost decisions.

Calculate from the score column
from sklearn.metrics import roc_auc_score, average_precision_score
scores = model.predict_proba(X_val)[:, 1]
auc = roc_auc_score(y_val, scores)
ap = average_precision_score(y_val, scores)

Check that column 1 corresponds to class 1. The scorer names are "roc_auc" and "average_precision". For multiclass probabilities, roc_auc_score(y_true, probabilities, multi_class="ovr") averages one-vs-rest AUCs.

Key Takeaways

  • AUC measures positive–negative pair ordering, with ties worth one half.
  • AUC is not accuracy, calibration or a guarantee about one operating threshold.
  • Rare positives can leave many false alerts even at a low FPR.
  • Use PR curves and AP for alert quality, and report threshold-specific counts.
4

Estimate performance on new data with held-out sets and cross-validation

A model must be evaluated on cases that stand apart from its training process. The separation includes fitted preprocessing, repeated sources and time, as well as labels. Use held-out sets to assign training, selection and final testing distinct roles. Cross-validation reuses development rows in a controlled rotation, while grouped, stratified and time-ordered folds make that rotation fit the prediction problem.

4.1 Split data into training, validation and test sets

Generalization error is expected error on new data from the same source. Training error cannot estimate it honestly: the fitted model has already used the training examples to choose its parameters.

Give each set one role
SetWhat it doesDecisions it can guide
TrainingFits parametersThe learned coefficients or other fitted values
ValidationCompares development choicesFeatures, model family, hyperparameters and threshold
TestChecks the final procedureFinal reporting after choices are locked

A 60/20/20 split of 10000 labeled rows gives 6000 training, 2000 validation and 2000 test rows. If cross-validation replaces a fixed validation set, an 80/20 split can reserve 8000 rows for development and 2000 for the final test. The validation folds then come only from the development portion.

from sklearn.model_selection import train_test_split
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42,
)
X_train, X_val, y_train, y_val = train_test_split(
    X_dev, y_dev, test_size=0.25, stratify=y_dev,
    random_state=42,
)

The second split holds out a quarter of 80%, giving 20% of the original rows for validation. A fixed random_state reproduces the split. These proportions are practical choices, not requirements for every data set.

Preserve the prediction situation

For independent classification cases, stratification keeps class proportions approximately alike in each set. At a 1% positive rate, 2000 test rows contain about 20 positives. Recall then depends on only about 20 cases, even though the test set sounds large.

If the model will predict the future, train on past rows and evaluate on later rows. Randomly mixing dates can let future information shape past predictions. If deployment is to new people or devices, keep all rows from one person or device together. Otherwise the model may recognize an already-seen source.

Keep evaluation information out

Leakage occurs when training receives information unavailable at prediction time or learns from evaluation data. A feature such as "refund issued" is too late for a fraud prediction made before the transaction is approved. Copies of one case in training and test also undermine the separation.

Split before fitting a scaler, imputer or feature selector. Learn their values from training rows, then apply those fixed transformations to validation and test rows. Merely excluding evaluation labels is insufficient: data-dependent preprocessing can still leak information.

Balance training size and score precision

For independent test cases, an accuracy near 0.80 on 500 rows has approximate standard error 0.8×0.2/500≈0.018. A larger test set improves precision but leaves fewer training rows. The number of rare positives may be the stronger constraint.

One model's uncertainty does not settle a comparison of two models on the same rows. Their errors are paired: inspect where their predictions differ. A single validation split also depends on the random allocation; cross-validation reduces reliance on one allocation without using the test set for development.

Key Takeaways

  • Training fits parameters; validation chooses settings; testing checks locked decisions.
  • The split should match prediction on future times or unseen groups.
  • Stratification preserves class proportions approximately but cannot create more rare cases.
  • Split before fitting preprocessing and exclude features unavailable at prediction time.
  • Test size controls estimate precision as well as the number of rare outcomes.

4.2 Run k-fold cross-validation

A model's validation score can change because a different set of rows was held out. k-fold cross-validation checks a procedure on several held-out folds and averages the results.

Rotate the held-out fold

Split development data into roughly equal folds. For each fold, fit a fresh model on all the other folds, then evaluate on that fold. In ordinary k-fold, each row is validated once and used for training in the other runs.

With 1000 rows and five folds, each fit trains on 800 and validates on 200. Five RMSE values of 4.1, 3.8, 4.4, 3.9 and 4.3 minutes have mean 4.1 and sample standard deviation about 0.26 minutes. Report "RMSE 4.1±0.26 minutes, mean ± SD over five folds." This spread describes variation across splits.

Dividing that SD by the square root of five gives a rough standard error, about 0.11 minutes. It is rough because training portions overlap. Fold scores are not independent repeated experiments, so that calculation is not a rigorous confidence interval.

Use the scorer's direction correctly
from sklearn.model_selection import KFold, cross_val_score
cv = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(
    model, X_dev, y_dev, cv=cv,
    scoring="neg_root_mean_squared_error",
)
errors = -scores
mean_rmse = errors.mean()
fold_sd = errors.std(ddof=1)

Use a pipeline as model when preprocessing learns from data. cross_validate can return several metrics and training scores with return_train_score=True. For classifiers with binary or multiclass targets, an integer cv=5 selects stratified folds; otherwise it selects plain KFold. Neither default shuffles. Choose the split deliberately when rows have an order.

Choose the resampling method
MethodWorkMain consideration
Five- or ten-foldFive or ten fits per settingCommon compromise between cost and estimate quality
Leave-one-outOne fit per rowTrains on almost all rows, but expensive and often high-variance
Repeated k-foldSeveral shuffled k-fold runsReduces dependence on one allocation

Leave-one-out's nearly identical training sets produce strongly related fits. Holding out only one row per fit does not guarantee a stable estimate. For classification, use a corresponding stratified repeated splitter when class balance matters.

Cross-validation evaluates the fitting procedure, not a single fitted object. Each fold model has less training data than the final model, which can make the estimate somewhat pessimistic. After choosing the procedure, refit it on all development data. If its CV score helped win a search, that score is a selection result; use an untouched test or outer CV for final evaluation.

Distinguish the bootstrap

The bootstrap samples rows with replacement and uses the distribution of a statistic across many resamples to estimate uncertainty. A size-n resample leaves a given original row out with probability (1−1/n)n, approaching 0.368. Some original rows repeat and others are absent. This differs from dividing data into disjoint folds.

For model comparison on common folds, inspect paired score differences. Two models' individual fold SDs do not show whether their difference is consistent.

Key Takeaways

  • Ordinary k-fold validates every row once using fresh fits on the other folds.
  • Report mean fold performance and label its spread as SD.
  • Five or ten folds balance fit cost and estimate quality.
  • Negate error scorers and refit the chosen procedure on all development data.
  • The bootstrap samples with replacement; it does not form disjoint folds.
  • A search winner needs a separate final estimate.

4.3 Match the splitting scheme to the data and keep preprocessing inside the folds

A splitting method should recreate the kind of new case the model will encounter. Keeping validation labels out of model fitting is only part of that separation: sources, dates and learned transformations matter too.

Match folds to the data
Data situationSplitterWhat stays separated
Independent rows, rare classesStratifiedKFoldClass proportions remain similar
Repeated rows per sourceGroupKFoldA source never crosses train and validation in a split
Groups and class imbalanceStratifiedGroupKFoldGroups stay intact while class balance is approximated
Future predictionTimeSeriesSplitValidation follows training in time

Fifty positives among 1000 rows can give ten positives per validation fold in five-fold stratification. Group constraints may prevent exact class balance. Keep the group boundary even when it makes the proportions less tidy.

For monthly data, train on months 1–6 and validate on month 7; next, train on months 1–7 and validate on month 8. These expanding windows test prediction forward in time. Shuffling would answer a different question by mixing earlier and later rows.

Fit transformations within each training portion

A scaler learns means and standard deviations; an imputer learns fill values; a feature selector learns which inputs to keep. Each must learn again inside each training fold. Fitting any of them on the full development set first gives validation rows influence over the training procedure.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier())
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(pipe, X_dev, y_dev, cv=cv, scoring="f1")

Cross-validation clones and fits the whole pipeline per training fold. Its scaler then transforms validation rows using that fold's training statistics. For grouped data, pass groups=source_ids with GroupKFold(n_splits=5) instead of this stratified splitter.

See how selection can leak

Imagine 50 rows with 5000 random-noise features and independent coin-flip labels. There is no predictive relationship: expected new-case error is 50%. Selecting the 100 features most correlated with all 50 labels before cross-validation uses validation labels to find chance patterns. The resulting CV error can look far below 50%.

Repeating feature selection inside the training folds removes that shortcut; evaluation returns toward the chance level. Chance can still produce a good finite-sample score, but the procedure no longer deliberately uses held-out labels.

Oversampling before splitting creates another shortcut: copies or related synthetic cases can appear on both sides. Resample only training portions, for example with an imbalanced-learn pipeline. Keep validation data at their original distribution.

A pipeline prevents leakage from its own correctly implemented steps. It cannot fix an outcome-derived input or a source split chosen incorrectly. Check every feature by asking, "Would this information be available, in this form, when the prediction is made?"

Key Takeaways

  • Use stratification for class balance, groups for repeated sources and time order for future predictions.
  • Refit every learned transformation inside each training fold.
  • Put preprocessing and the model in the pipeline evaluated by CV.
  • Selecting features or oversampling before splitting can leak validation information.
  • A pipeline does not fix unavailable features or incorrect group and time boundaries.
5

Diagnose underfitting and overfitting with bias, variance and learning curves

The next useful experiment depends on why a model is failing. Bias describes a persistent inability to fit the pattern; variance describes sensitivity to the training sample. Compare training and validation error with a credible achievable baseline, then inspect how those errors change with more training data. These signals help choose between improving the fit, reducing flexibility and collecting more examples.

5.1 Explain the bias–variance tradeoff

A model can fail because its assumptions miss the pattern or because its fitted predictions depend too strongly on the particular training sample. These are bias and variance, two different sources of prediction error.

Separate persistent error from sample sensitivity

High bias means that, averaged across possible training sets, the model still misses the underlying relationship. It leads to underfitting. High variance means that the fitted model changes greatly when the training sample changes. It leads to overfitting, where a model follows sample-specific noise.

For squared error at a fixed input, expected prediction error decomposes into variance, squared bias and noise variance:

E[(y0−f^(x0))2]=Var(f^(x0))+[Bias(f^(x0))]2+Var(ε).

The expectation averages over training samples and new outcome noise. Squared bias 4, variance 1 and noise variance 9 give expected squared error 14 and its square root about 3.74. The noise term is irreducible error: unpredictable variation left even if the relationship is known. It bounds expected error, not every individual observed test score.

Find a useful degree of flexibility
Polynomial degreeTraining RMSEValidation RMSESignal
16.06.3Model misses the pattern
33.13.4Best validation result here
120.97.8Model fits sample noise

Increasing flexibility tends to lower bias and increase variance. In this example, the degree-12 model fits training rows extremely well but generalizes poorly. Choosing it from training error would reward the wrong behavior. Degree 3 has the lowest validation error among the candidates.

For k-nearest neighbors, smaller k gives a more local, flexible prediction. With k equal to 1, training error is zero when identical inputs do not have conflicting labels. The prediction is sensitive to which cases happen to be nearby. With k equal to the full training count and uniform weighting, every classification prediction is the training majority class: a very inflexible rule.

Read a validation curve

A validation curve varies one hyperparameter on its horizontal axis and plots training and validation performance. A typical error curve falls as flexibility captures the pattern, then rises as sample noise dominates. Select using validation performance, keeping the test set untouched.

from sklearn.model_selection import validation_curve
train_scores, val_scores = validation_curve(
    pipe, X_dev, y_dev,
    param_name="knn__n_neighbors",
    param_range=[1, 3, 7, 15, 31],
    cv=5, scoring="f1",
)

Here pipe has a step named knn; higher F1 is better. Large k is the smoother end of this axis, so flexibility increases toward the smaller values. Read both the parameter direction and whether the vertical axis is a score or an error.

The tradeoff is a guide, not a requirement that every improvement sacrifices one component. More representative training data can reduce variance, and an informative input can reduce bias. The exact additive formula is for squared error; classification uses the same diagnostic ideas without that decomposition of its error rate. Here "bias" describes a prediction property, separate from an intercept, sampling bias or unfair treatment of a group.

Key Takeaways

  • Bias is persistent model error across samples; variance is sensitivity to the training sample.
  • Expected squared error equals squared bias plus variance plus irreducible noise.
  • Greater flexibility often lowers training error but can raise validation error.
  • In k-NN, smaller k is more flexible; larger k is smoother.
  • A validation curve varies a hyperparameter and supports selection using validation performance.

5.2 Diagnose high bias or high variance from training and validation error

Training and validation errors become useful diagnoses when compared with a credible performance baseline. Ask both how well the model fits and how much worse it gets on held-out cases.

Read two gaps

An expert error rate or a justified noise level can approximate the best performance realistically achievable. This is different from a dummy-model baseline: a majority-class model tells you what a trivial rule achieves, not the noise floor.

Compare training error with the achievable baseline for avoidable bias. Compare validation error with training error for the variance gap. These are practical diagnostic signals, not numerical estimates of the bias and variance terms in the squared-error decomposition.

With expert error of 4%, consider:

CaseTraining errorValidation errorDiagnosis
A4.5%12%Small bias gap, large variance gap
B11%12%Large bias gap, small variance gap
C10%18%Both gaps are large

Case A has training error only 0.5 percentage points above the baseline, but validation adds 7.5 points. Case B has a 7-point training gap and only a 1-point validation gap. Case C leaves 6 points to improve on training data and a further 8 points lost on validation.

Without the baseline, "10% training error" is hard to judge. It can be poor for clean printed digits but close to the practical limit for noisy speech. Check the task and the data quality before calling training error high.

Match the change to the diagnosis
Main problemChanges to investigateWhy they help
High biasMore informative inputs, greater flexibility, fewer constraints, completed optimizationImprove the fit to patterns already present
High varianceMore representative training cases, simpler model, fewer inputs, stronger constraintsReduce dependence on particular training cases
BothAddress inadequate fit and unstable generalizationOne change may not solve both gaps

For k-NN, a smaller k can address excessive smoothness, while a larger k can reduce sample sensitivity. For polynomial regression, increasing degree can reduce underfitting and decreasing it can reduce overfitting. Regularization strength is another constraint to tune.

Collecting more of the same kind of data is usually a weak first move when both errors have already settled far above the achievable baseline. Increasing model flexibility is usually a poor first move when training error is already low and the validation gap is wide.

Inspect the actual mistakes

Error analysis adds detail that averages cannot show. Sample misclassified validation cases, sort them into useful categories such as blurred inputs, a product type or label errors, and count the categories. If a large share of errors comes from unreadable inputs, investigate that issue before spending time on a small category.

Keep the diagnosis within training and validation data, including CV results. Looking at test errors to decide what to change makes those rows part of development.

Key Takeaways

  • Compare training error with an achievable baseline and validation error with training error.
  • These gaps guide diagnosis; they are not the exact decomposition terms.
  • Increase useful capacity for high bias; reduce sample sensitivity for high variance.
  • Inspect and count validation error categories to choose the next experiment.

5.3 Read learning curves

A learning curve shows what changes as the model receives more training examples. Its horizontal axis is training-set size. Its two vertical series show training and validation error, or scores with a clearly labeled direction.

Build each point with a fresh fit

Choose growing subsets of training data, fit a fresh model at each size, then evaluate on that subset and held-out cases. Use the same validation set or a defined cross-validation procedure so changes reflect training size.

Training error often rises as the model must fit more cases. Validation error often falls because more cases reveal a more stable pattern. These are typical trends; small samples make individual points noisy. A rising training-error curve can therefore accompany better generalization.

Read the level and the gap

With an achievable baseline error of 5%, compare two patterns:

Training rowsHigh-bias train / validationHigh-variance train / validation
10018% / 25%1% / 30%
100021% / 22.5%3% / 18%
500021.5% / 22%4% / 12%

In the high-bias pattern, both curves have almost met around 22%, far above the baseline. More rows of the same kind are unlikely to help much. Improve the model's ability to represent useful patterns or improve the inputs.

In the high-variance pattern, training error stays near the baseline and validation error is still falling. The gap narrows as data grow. More representative examples are a promising next experiment; simplifying the model is an alternative.

A good fit has a small gap near the achievable baseline. A small gap alone is insufficient: the high-bias example also has one. Judge both the height and separation of the curves, then inspect the trend at the largest available size.

Compute curves with the full procedure
import numpy as np
from sklearn.model_selection import learning_curve
sizes, train_scores, val_scores = learning_curve(
    pipe, X_dev, y_dev,
    train_sizes=np.linspace(0.1, 1.0, 5),
    cv=cv, scoring="neg_root_mean_squared_error",
)
train_errors = -train_scores
val_errors = -val_scores
train_mean = train_errors.mean(axis=1)
val_mean = val_errors.mean(axis=1)
val_sd = val_errors.std(axis=1, ddof=1)

Here cv is a splitter suitable for the data. Plot both means against sizes and, if useful, a band of one fold SD. The sign reversal makes the vertical axis an error, so down is better. The band shows fold variation, not a guaranteed interval for future performance. Keep preprocessing inside pipe at every size.

Name the horizontal axis

A learning curve varies the number of examples. A validation curve varies a hyperparameter. A training-loss plot varies iterations or epochs and answers whether optimization is progressing. The same word "curve" does not make their diagnoses interchangeable.

Building the learning curve needs many fits. For time-ordered data, use past-to-future training and validation windows, such as TimeSeriesSplit, and ensure the subsets preserve that order. Never shuffle future rows into a training subset to make the plot smoother.

Key Takeaways

  • Learning curves vary training-set size and compare training with validation performance.
  • Close curves far above the baseline suggest bias; a wide narrowing gap suggests variance.
  • Training error can rise while validation error improves.
  • Read the largest-size trend before deciding whether more data will help.
  • Label the axis: data size, hyperparameter and epoch plots answer different questions.
6

Tune hyperparameters and select a model without touching the test set

Choosing settings is itself a learning process: repeated comparisons can fit the noise in validation scores. Search within development data, keep preprocessing inside every fit and lock decisions before the test. When a separate test is impractical, nested cross-validation evaluates the search procedure. Compare candidates on common folds, weigh practical costs and report the final evidence with clearly labeled uncertainty.

6.1 Search hyperparameters with cross-validation

Parameters are learned during fitting, such as regression coefficients. Hyperparameters control the procedure before fitting: k in k-NN, polynomial degree, optimization settings and preprocessing choices. Their values need validation evidence.

Search inside development data

Choose the metric, define candidate settings, evaluate each with the same cross-validation splits, select a setting and refit it on all development data. Keep the reserved test set out of every search decision.

Grid search tries every listed combination. Four k values and two weighting rules create eight candidates. Five-fold CV requires 40 fits, followed by one final refit: 41 fits. Adding another hyperparameter multiplies the work. A grid of 5 by 4 by 3 values gives 60 candidates and 300 fold fits with five folds, before refitting.

Random search samples a fixed number of combinations. It can explore more distinct values under a limited budget, especially when only a few dimensions matter strongly. Use logarithmic ranges for positive scale settings such as learning rates: orders of magnitude are more informative than equally spaced values from 0.0001 to 1.

Search the pipeline
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold
pipe = Pipeline([
    ("scale", StandardScaler()),
    ("knn", KNeighborsClassifier()),
])
grid = {
    "knn__n_neighbors": [3, 5, 11, 21],
    "knn__weights": ["uniform", "distance"],
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = GridSearchCV(pipe, grid, cv=cv, scoring="f1")
search.fit(X_dev, y_dev)

The double underscore connects a pipeline step name with its setting. Searching the full pipeline ensures scaling learns only from each training fold. Keep k values no larger than the smallest fold's training count.

AttributeMeaning
best_params_Selected hyperparameter values
best_score_Winning mean CV score, used for selection
best_estimator_Selected pipeline refitted on all development data
cv_results_Candidate settings, scores and timing information

The refit happens by default. The winning CV value is not an independent final performance estimate: it helped choose the winner.

Make the search match the task

Accuracy can favor ignoring rare positives. Choose F1, AP, ROC AUC or a negated regression error according to the application. Error scorers still maximize: −3 is better than −5. For multiple metrics, supply a scoring dictionary and name the selection metric in refit, such as refit="f1".

With RandomizedSearchCV, n_iter controls the candidate budget. A learning-rate distribution can be supplied by scipy.stats.loguniform(1e-4, 1). These sampled settings are still evaluated by CV; random search does not mean a random train/test split for each candidate.

If the winner lies at the edge of a range, extend the development search in that direction. A coarse search followed by a narrower grid can be efficient. Choosing from training scores rewards flexible fits; choosing from test scores spends the independent final check.

Key Takeaways

  • Hyperparameters configure fitting; parameters are learned during fitting.
  • Grid size multiplies across settings, then by folds; include final refits in the budget.
  • Random search fixes the candidate budget and can explore wide ranges efficiently.
  • Search the complete pipeline with a task-appropriate metric.
  • The best CV score selects a model; it is not its independent final estimate.
  • Extend a search range when its best setting is on the boundary.

6.2 Keep the test set untouched until the final check

A held-out score is useful only while it stays outside the decisions it evaluates. Trying many models and reporting their highest development score selects both a model and a favorable piece of noise.

Understand selection optimism

Imagine 20 models whose true accuracy is 0.80, each measured on 500 cases. Each observed accuracy has approximate standard error 0.8×0.2/500≈0.018. If score errors were independent, the average highest score would be about 0.80+1.87×0.018≈0.833. No model became better; the winning estimate was lucky.

Actual models' errors can be correlated, so this numerical illustration is not a correction to subtract from every search. It explains why best_score_ is a selection score. Reusing validation data for many choices can overfit those data even if each individual model fit excludes them.

Lock decisions before testing

Finish the feature choices, model family, preprocessing, settings and threshold before computing test performance. Use the test set for one final check and report the result, including an inconvenient one.

A slightly lower test than CV score can reflect ordinary sampling variation. A large drop calls for investigation of leakage, changes in the data source or excessive development comparisons. If that investigation guides a new model, the old test set has joined development. A new independent check needs fresh data; disclose the reuse if fresh data are unavailable.

Evaluate tuning with nested CV

Nested cross-validation separates selection from evaluation using two loops:

  1. Hold out an outer fold.
  2. On the outer training portion, run an inner CV search.
  3. Refit the inner winner on that entire outer training portion.
  4. Score once on the untouched outer fold.
  5. Repeat for every outer fold and summarize the outer scores.

With eight candidates, five inner folds and five outer folds, there are 200 inner fits plus five winner refits, or 205. Different outer portions can select different settings. The outer scores estimate the whole tuning procedure, not the performance of one fixed hyperparameter value.

from sklearn.model_selection import GridSearchCV, cross_val_score
inner_search = GridSearchCV(pipe, grid, cv=inner_cv, scoring="f1")
outer_scores = cross_val_score(
    inner_search, X_dev, y_dev, cv=outer_cv, scoring="f1",
)

Here pipe, grid, inner_cv and outer_cv define the candidates and suitable splitters. All learned preprocessing stays inside pipe. Fitting a scaler on all data before the outer loop would let outer evaluation rows influence development. Group and time boundaries must also be respected in both loops.

Nested CV is useful when data are scarce and a separate final test would leave too little training data. After estimating the procedure, run that search on all available development data to obtain the model to use.

After a final held-out test, a locked procedure may be refitted on training plus test rows for deployment. The earlier test score remains the estimate obtained before that refit; the enlarged fit has no separate held-out score on those same rows. Keep that distinction clear in reporting.

Key Takeaways

  • The best development score is optimistic because selection rewards favorable noise.
  • Lock every development decision before the final test.
  • Changing a model in response to test results converts that set into development data.
  • Nested CV tunes inside each outer training portion and evaluates on the outer holdout.
  • Outer scores estimate the tuning procedure, even when selected settings differ.
  • A deployment refit does not create a new independent score for the enlarged fit.

6.3 Compare candidate models and report the chosen one

A useful model comparison asks whether an improvement is consistent, meaningful for the task and worth the practical cost. The largest mean score is one piece of that decision.

Compare like with like

Score every candidate and a fitted dummy baseline on the same evaluation rows with the same metric. For CV, reuse a reproducible splitter, such as StratifiedKFold(n_splits=5, shuffle=True, random_state=0). Different random folds mix model differences with split differences.

Inspect the paired differences, one per fold. A candidate that wins on all five folds gives stronger evidence of a consistent advantage than a similar mean difference with changing signs. A difference of 0.002 can matter with very precise evaluation; it can also be indistinguishable from noise when folds swing by 0.01 or more. The individual models' SDs do not measure the variability of their difference.

Use a simplicity rule when scores are close

The one-standard-error rule selects the simplest candidate within one standard error of the best mean. For higher-is-better scores, subtract the best model's standard error from its mean to obtain a cutoff.

k in k-NNMean accuracyEligible at cutoff 0.831?
50.842Yes
150.836Yes
310.825No

The best model's standard error is 0.011, giving 0.842−0.011=0.831. Larger k is smoother, so k of 15 is the simplest eligible candidate here. Choosing k of 31 would exceed the permitted drop. For lower-is-better error, add one standard error to the lowest mean instead.

Treat CV standard errors as rough because training portions overlap. The rule is a practical selection preference, not a significance test or a claim that the candidates are identical.

Include operational needs

Consider prediction time, training time, memory, explainability, stability under changing data, performance across user groups and whether inputs exist at prediction time. A tiny score gain may not justify a large delay or an unavailable feature. These choices are still development choices, made before the test.

Report the decision and its uncertainty

For independent cases, test accuracy 0.86 on 500 rows has approximate 95% interval

0.86±1.960.86×0.14/500≈0.86±0.030.

That is roughly 0.83–0.89. This binomial approximation concerns accuracy on the sampled population, not a guarantee under future distribution changes or a confidence interval for F1.

An evaluation report states:

  • Data source, split sizes and any group or time separation.
  • Metric and its practical reason, alongside a baseline on the same rows.
  • Selected settings and CV mean ± SD, labeled as development results.
  • Final held-out score and an appropriate uncertainty summary.
  • For classification, the positive class, averaging method where needed, decision threshold and confusion matrix.

For example: "k-NN with k of 15 reached F1 0.71±0.03 in five-fold CV and 0.69 on 2000 test rows; the majority-class baseline had F1 0." Include the threshold and counts with that result. An accuracy beside an F1, or two scores from different test sets, cannot establish a fair ranking.

Key Takeaways

  • Compare candidates and baselines using common rows, folds and metrics.
  • Inspect paired fold differences, not just the highest mean.
  • The one-standard-error rule favors the simplest eligible candidate.
  • Include operational costs when choosing a model.
  • Report split design, baseline, settings, CV spread, final score and threshold-specific counts.

Model Evaluation and Validation examples

6 Walkthroughs

1

Measure a delivery model’s errors

12 steps
Work from residuals to unit-based errors, a mean baseline and R².
  1. 1
    IntroductionAsk how far predictions miss

    A regression model predicts a quantity, such as delivery time. Its errors need a size, a unit and a useful comparison. We will calculate absolute and squared errors for five deliveries, then ask how much the model improves on a constant mean. The error metric answers how far predictions miss; R² answers a different question about improvement relative to a reference.

  2. 2
    ExampleSubtract each prediction

    Actual delivery times are 12, 15, 20, 30 and 18 minutes. Predictions are 14, 15, 17, 24 and 20 minutes. Subtract predicted from actual to get residuals −2, 0, 3, 6 and −2. The third prediction is 3 minutes too low; the fourth is 6 minutes too low. Keep these signs while constructing the errors, even though the next calculations use their absolute values or squares.

  3. 3
    ExampleAverage the absolute errors

    The absolute residuals are 2, 0, 3, 6 and 2 minutes. Their total is 13 minutes across five cases, so MAE is 2.6 minutes. This average treats each additional minute of error equally. The mean signed residual would instead be 1 minute: negative and positive values cancel, so that number describes average direction without measuring the full size of the errors.

  4. 4
    ExampleSquare first, then average

    Square the same residuals to obtain 4, 0, 9, 36 and 4. Their sum is 53, so MSE is 10.6 minutes². Take the square root only after averaging: RMSE is about 3.26 minutes. The error of 6 minutes supplies 36 of the 53 squared units, showing why this calculation gives large misses much more influence than MAE does.

  5. 5
    ChallengeCheck a metric calculation

    A separate duration model has residuals −2, 2 and 4 minutes. What are its MAE and RMSE, and which is larger?

    ---reveal---

    The absolute total is 8, so MAE is about 2.667 minutes. The squared total is 24, giving MSE 8 minutes² and RMSE about 2.828 minutes. RMSE is larger because the error sizes vary. Averaging the signed residuals would give about 1.333 minutes and conceal their size.

  6. 6
    Key InsightChoose the cost you intend to measure

    MAE suits a roughly constant cost for each unit of error. RMSE emphasizes big misses. If the last actual delivery time changes from 18 to 48 minutes, its residual becomes 28: MAE rises to 7.8, but RMSE rises to about 12.91 minutes. This difference comes from the penalty, so a lower value under one metric need not identify the best model under the other.

  7. 7
    ExampleConstruct the mean reference

    The five actual times have mean 19 minutes. Their deviations from it are −7, −4, 1, 11 and −1. Squaring and adding gives 188. This is the total sum of squares, the denominator of R². Our model’s residual squared total was 53, so it leaves 53/188 of the evaluation-mean reference error and removes the rest.

  8. 8
    ExampleCalculate and interpret R²

    Calculate R2=1−53/188≈0.718. The model removes about 72% of that constant reference’s squared error. Its RMSE is about 3.26 minutes against about 6.13 minutes for always predicting 19. The two numbers have different jobs: R² expresses relative improvement, while RMSE tells you the remaining error in minutes. Neither alone describes every residual pattern.

  9. 9
    TipFit baselines before evaluation

    The mean inside R² belongs to the evaluation targets. A usable dummy model instead learns a constant from training targets, so its held-out R² can be slightly negative. Fit DummyRegressor(strategy="mean") on training rows and score it beside the model. Use a median baseline when MAE is the primary criterion. Do not learn a new baseline constant from held-out targets.

  10. 10
    ChallengeExplain a negative score

    Another model has residual squared total 240 on the same five actual times. What is its R², and does a negative value indicate a calculation error?

    ---reveal---

    R² is 1−240/188, about −0.277. It has more squared error than the evaluation-mean reference. That negative result is valid: the square in the name does not restrict R² to positive values. The reference target spread remains 188 because the evaluated targets did not change.

  11. 11
    ChallengeCombine relative and practical error

    Two models have identical held-out R² on the same target rows, but a report lists different RMSE values. Can both results be consistent?

    ---reveal---

    No, apart from rounding or a reporting difference. The same targets fix the R² denominator; equal R² then fixes the squared residual total. On the same number of rows, MSE and RMSE must also agree. Different evaluation rows would break that reasoning, which is why a comparison must name its data.

  12. 12
    RecapRead a regression result as evidence

    Keep the residual direction separate from error size. MAE and RMSE express different penalties in the target unit; R² compares squared error with an evaluation-mean reference. A useful report identifies held-out rows, includes a training-fitted baseline and states a unit-based error. Inspect the residual plot for patterns that those averages can conceal.

2

Turn classification counts into useful scores

12 steps
Build a confusion matrix and connect precision, recall, F1 and class averages to the task.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart with the kinds of mistakes
  2. 2
    ExplanationFix the positive class and axes
  3. 3
    ExampleRecover the flagged column
  4. 4
    ChallengeRebuild a new matrix
  5. 5
    Key InsightAccuracy needs a reference
  6. 6
    ExampleUse the denominator that answers the question
  7. 7
    ConnectionCount negatives in their own population
  8. 8
    ExampleBalance precision and recall with F1
  9. 9
    ChallengeCompute the positive-class result
  10. 10
    ExplanationChoose how classes receive weight
  11. 11
    ChallengeAudit a multiclass headline
  12. 12
    RecapAttach the question to the metric
3

Follow a ranking through different thresholds

14 steps
Use one ranked list to build threshold metrics, ROC points, AUC and average precision.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate a ranking from its cutoff
  2. 2
    ExampleChoose a cutoff on the ranked list
  3. 3
    ExampleLower the cutoff one step
  4. 4
    ChallengeMake a decision from error costs
  5. 5
    ExplanationSummarize the PR path
  6. 6
    ExplanationChange the axes for ROC
  7. 7
    ExampleTrace the first six moves
  8. 8
    ChallengeFind the operating point
  9. 9
    TipRead the part of the curve you can use
  10. 10
    ExampleCalculate AUC through pairs
  11. 11
    ChallengeCheck what a score transformation changes
  12. 12
    ExampleTranslate rare-class rates into alerts
  13. 13
    ChallengeConnect a threshold with its workload
  14. 14
    RecapReport the ranking and the action
4

Build validation that matches new cases

13 steps
Separate test data, rotate validation folds and keep sources, time and preprocessing inside the right boundaries.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDefine what new means
  2. 2
    ExampleAssign three distinct roles
  3. 3
    TipCount the rare outcomes too
  4. 4
    ChallengeKeep the final check independent
  5. 5
    ExampleRotate the held-out fold
  6. 6
    ExampleLabel the mean and spread
  7. 7
    ChallengeCount the fits and their training rows
  8. 8
    ConnectionChoose how often to resample
  9. 9
    ExampleKeep repeated sources together
  10. 10
    ExplanationLearn preprocessing inside each fold
  11. 11
    ChallengeRepair a misleading feature search
  12. 12
    ChallengeCombine time and transformation boundaries
  13. 13
    RecapProtect every learned step
5

Use error patterns to choose the next experiment

13 steps
Distinguish bias and variance, compare errors with a baseline and read training-size curves.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk why the model is failing
  2. 2
    ExplanationSeparate bias, variance and noise
  3. 3
    ExampleCompare model flexibility
  4. 4
    ChallengeChange flexibility in k-NN
  5. 5
    ExampleGive the error level a baseline
  6. 6
    ExampleDiagnose a different pair of gaps
  7. 7
    ChallengeChoose a remedy for the main gap
  8. 8
    TipInspect actual validation mistakes
  9. 9
    ExampleRead a high-bias learning curve
  10. 10
    ExampleRead a narrowing high-variance gap
  11. 11
    ChallengeLook beyond a small gap
  12. 12
    ChallengeUse a curve and a diagnosis together
  13. 13
    RecapTurn a diagnosis into an experiment
6

Select and report a model honestly

15 steps
Count a search budget, protect the test set, evaluate tuning and choose a model from comparable evidence.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionEvaluate the choices as well as the fit
  2. 2
    ExplanationName what fitting learns
  3. 3
    ExampleCount every grid combination
  4. 4
    TipSearch the whole pipeline
  5. 5
    ChallengeUse a fixed random-search budget
  6. 6
    Key InsightThe winning score selected favorable noise
  7. 7
    ChallengeNotice a consumed test set
  8. 8
    ExplanationPut tuning inside an outer evaluation
  9. 9
    ExampleCount nested search work
  10. 10
    ConnectionPair the candidate comparisons
  11. 11
    ExampleApply a simplicity cutoff
  12. 12
    ChallengeSelect within an error band
  13. 13
    TipLabel uncertainty with its metric
  14. 14
    ChallengeChoose what belongs in the final report
  15. 15
    RecapKeep selection and measurement distinct

Model Evaluation and Validation practice questions

50 Practice Questions in 5 sets

Set 1: Measure errors and read classification results10 Practice Questions

Question 1 of 10

A model has squared residual sum 36 on evaluation targets whose total squared deviation from their mean is 90. What is R²?
  1. 0.600
  2. 0.400
  3. 1.400
  4. −0.600
Show answerHide answer
Answer: A
R² is one minus the residual sum divided by the total sum, giving 1−36/90=0.600. The ratio 0.400 is the share of mean-reference squared error still left, not the share removed. The model removes 60% of that reference error.

Question 2 of 10

A container has actual mass 18 kg and predicted mass 21 kg. What is its residual, using actual minus predicted?
  1. 3 kg
  2. −3 kg
  3. 39 kg
  4. −39 kg
Show answerHide answer
Answer: B
The residual is actual minus predicted, so it is −3 kg. The negative sign means the prediction was too high. A residual of 3 kg reverses the subtraction and would describe a prediction that was too low.

Question 3 of 10

A model has residuals −1, 2 and −3 minutes. What are its MAE and RMSE, to three decimals?
  1. MAE 2.000; RMSE 2.000 minutes
  2. MAE 0.667; RMSE 2.160 minutes
  3. MAE 2.000; RMSE 4.667 minutes
  4. MAE 2.000; RMSE 2.160 minutes
Show answerHide answer
Answer: D
The absolute errors sum to 6, giving MAE 2 minutes. Squared errors sum to 14, so RMSE is the square root of 14/3, about 2.160 minutes. Reporting 4.667 minutes leaves the mean squared error unrooted and assigns it the wrong unit.

Question 4 of 10

On held-out data, a training-fitted mean baseline has R² −0.08 and a model has R² −0.03. How do their squared errors compare?
  1. The model is worse than both mean references.
  2. The model matches the evaluation-mean reference.
  3. The model beats the fitted baseline but loses to the evaluation mean.
  4. The model beats the evaluation mean but loses to the fitted baseline.
Show answerHide answer
Answer: C
A higher R² means lower squared error on the same evaluation rows. The model therefore beats the fitted baseline, but its negative R² means it loses to the evaluation-mean reference. A negative score does not mean the model must lose to every training-fitted baseline.

Question 5 of 10

Of 600 uploaded files, 90 contain a defect. A detector flags 120 files, including 72 defective ones. What is the matrix with actual rows and predicted columns ordered negative, positive?
  1. [[390, 120], [18, 72]]
  2. [[462, 48], [18, 72]]
  3. [[462, 18], [48, 72]]
  4. [[480, 30], [18, 72]]
Show answerHide answer
Answer: B
There are 72 true positives, 48 false positives and 18 false negatives. Of 510 actual negatives, 462 are correctly left unflagged, giving [[462, 48], [18, 72]]. Swapping 48 and 18 confuses false alarms with missed actual positives and breaks the actual-class row totals.

Question 6 of 10

Only 3% of documents need manual review. A classifier always predicts "no review." What are its accuracy and recall for the review class?
  1. Accuracy 0.970; recall 0
  2. Accuracy 0.970; recall 0.970
  3. Accuracy 0.030; recall 0
  4. Accuracy 0.030; recall 1
Show answerHide answer
Answer: A
Always predicting the majority class correctly labels the 97% that need no review. It catches none of the actual review cases, so recall is zero. Giving recall 0.970 mistakes overall accuracy for the fraction of positives detected.

Question 7 of 10

A fault detector has TP 24, FP 6, FN 16 and TN 154. What are its precision and recall?
  1. Precision 0.600; recall 0.800
  2. Precision 0.923; recall 0.600
  3. Precision 0.800; recall 0.923
  4. Precision 0.800; recall 0.600
Show answerHide answer
Answer: D
Precision divides 24 true alerts by 30 total alerts, giving 0.800. Recall divides 24 detections by 40 actual faults, giving 0.600. Interchanging those denominators swaps the two answers and changes which practical question each score answers.

Question 8 of 10

A classifier has precision 0.75 and recall 0.25. What is its F1 score?
  1. 0.500
  2. 0.250
  3. 0.375
  4. 0.750
Show answerHide answer
Answer: C
F1 is the harmonic mean, 2×0.75×0.25 divided by their sum of 1, giving 0.375. The ordinary average 0.500 overstates the balance between them. F1 is pulled toward the weaker recall, even though precision is fairly high.

Question 9 of 10

A three-class classifier has class F1 scores 0.90, 0.60 and 0.30, with actual class counts 70, 20 and 10. What are macro and weighted F1?
  1. Macro 0.600; weighted 0.780
  2. Macro 0.780; weighted 0.600
  3. Macro 0.600; weighted 0.600
  4. Macro 0.750; weighted 0.780
Show answerHide answer
Answer: A
Macro F1 averages the three scores equally, giving 0.600. Weighted F1 is (70×0.90+20×0.60+10×0.30)/100=0.780. Reversing them gives the large class equal influence in the wrong measure; actual class counts belong only in the weighted calculation.

Question 10 of 10

Two duration models are evaluated on the same five cases. Residuals are [0, 0, 0, 0, 8] minutes for A and [2, 2, 2, 2, 2] for B. Each minute of absolute error has equal cost. Which model fits that cost, and how does RMSE rank them?
  1. Choose B; RMSE also favors B.
  2. Choose B; RMSE instead favors A.
  3. Choose A; RMSE also favors A.
  4. Choose A; RMSE instead favors B.
Show answerHide answer
Answer: D
Equal cost per absolute minute favors MAE: A has 1.6 minutes and B has 2.0. RMSE instead favors B, because A has RMSE about 3.578 versus 2.0 for B. Choosing B from its lower RMSE would apply a squared-error emphasis that the stated cost does not use.
Set 2: Choose thresholds and protect evaluation data10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Validation cases have (score, actual label): (0.92, 1), (0.76, 0), (0.63, 1), (0.51, 0), (0.28, 1), (0.12, 0). At a threshold of at least 0.60, what are precision and recall?
  1. Precision 1.000; recall 0.667
  2. Precision 0.667; recall 1.000
  3. Precision 0.667; recall 0.667
  4. Precision 0.500; recall 0.667
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A threshold rises and some cases stop being predicted positive. Which metric is guaranteed not to increase: recall or precision?
  1. Precision only
  2. Recall only
  3. Both metrics
  4. Neither metric
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An evaluation set has 60 actual positives and 240 actual negatives. A threshold gives TP 45 and FP 12. What is its ROC point, written (FPR, TPR)?
  1. (0.200, 0.750)
  2. (0.050, 0.789)
  3. (0.750, 0.050)
  4. (0.050, 0.750)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Two positives have scores 0.9 and 0.4; two negatives have scores 0.7 and 0.4. What is ROC AUC?
  1. 0.625
  2. 0.500
  3. 0.750
  4. 0.875
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An alert system faces 200 actual positives and 19800 actual negatives. At its chosen threshold, TPR is 0.85 and FPR is 0.02. What fraction of its alerts are correct, and which additional curve best shows that alert burden?
  1. 0.850; precision–recall curve
  2. 0.980; precision–recall curve
  3. About 0.300; precision–recall curve
  4. About 0.300; ROC curve alone
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

You reserve 25% of 2400 independent cases for testing, then 20% of the remaining cases for validation. How many rows train the model?
  1. 1200 rows
  2. 1320 rows
  3. 1800 rows
  4. 1440 rows
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Ordinary four-fold CV runs on 360 rows. How many rows train each fold model?
  1. 270 rows
  2. 90 rows
  3. 360 rows
  4. 180 rows
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Cross-validation returns negative MAE scores [−2, −4, −3]. What mean MAE should be reported?
  1. −3 target units
  2. 3 target units
  3. 9 target units
  4. √3 target units
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A team predicts faults for devices it has never seen. Each device supplies many rows. The team stratifies individual rows and selects features using all development labels before CV. What evaluation repair addresses both problems?
  1. Keep row folds; move feature selection inside the pipeline.
  2. Use grouped folds; keep feature selection fitted beforehand.
  3. Use grouped folds; fit feature selection inside each fold.
  4. Use time folds; select features once from development labels.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A model predicts next-month demand from past observations. What CV scheme matches that use?
  1. Shuffle all months into stratified folds.
  2. Hold out every fifth month in shuffled folds.
  3. Train on later months and validate on earlier ones.
  4. Train on earlier months and validate on later ones.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Diagnose errors and tune a procedure10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A grid has three k values and four weight-setting combinations. With three-fold CV and one final refit, how many model fits are required?
  1. 36 fits
  2. 37 fits
  3. 12 fits
  4. 40 fits
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A regression model has squared bias 9, prediction variance 4 and noise variance 3 at an input. What is its expected squared prediction error?
  1. 10
  2. 16
  3. 22
  4. 4
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Polynomial models of degrees 2, 4 and 9 have training RMSE 7.2, 4.0 and 1.2, and validation RMSE 7.6, 4.5 and 8.1. Which degree should be selected from this evidence?
  1. Degree 2, from the smaller gap.
  2. Degree 9, from training error.
  3. Degree 4, from validation error.
  4. Degree 9, from greater flexibility.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Expert error is 2%. A model has training error 14% and validation error 15%. What is the main diagnosis and a suitable next experiment?
  1. High variance; reduce model flexibility.
  2. High variance; collect more similar data.
  3. High bias; collect more similar data.
  4. High bias; increase useful model flexibility.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

With an achievable error near 3%, training/validation errors are 1%/24% at 200 rows, 2%/15% at 2000 rows and 3%/10% at 8000 rows. What is the most supported next step?
  1. Increase flexibility because training error rose.
  2. Stop because the curves already meet.
  3. Collect more representative training cases.
  4. Remove validation data because its error is high.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A search optimizes negated RMSE. Settings produce mean scores −6.4, −5.8 and −6.1. Which is selected?
  1. The setting with RMSE 5.8.
  2. The setting with RMSE 6.4.
  3. The setting with RMSE 6.1.
  4. The setting with RMSE −5.8.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A team adjusts its alert threshold after seeing test false alarms, then reports the updated test F1 as an independent final estimate. What is wrong with that claim?
  1. Only model coefficients can overfit evaluation data.
  2. The test set is independent because labels stayed fixed.
  3. Threshold changes require retraining the classifier first.
  4. Test feedback influenced the selected prediction rule.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Nested CV uses six candidates, four inner folds and three outer folds, with one winner refit per outer fold. What is the fit count, and what do the outer scores evaluate?
  1. 73 fits; one fixed parameter setting.
  2. 75 fits; one fixed parameter setting.
  3. 75 fits; the tuning procedure.
  4. 72 fits; the tuning procedure.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

For k-NN, k values 3, 7, 13 and 25 score 0.912, 0.910, 0.907 and 0.899. The best mean has standard error 0.008. Which k does the one-standard-error rule choose?
  1. k = 3
  2. k = 13
  3. k = 25
  4. k = 7
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Expert error is 3%. At the largest two training sizes, training/validation errors are 13%/23% and 13.5%/20%. A proposal says, "More data will solve the problem because validation error is falling." What does the combined evidence support?
  1. Reduce variance and improve inadequate fit.
  2. Collect data; the model already fits well.
  3. Increase flexibility; variance is already small.
  4. Keep the model; both errors are near baseline.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Combine metrics with evaluation choices10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A residual plot has a clear U-shaped pattern against predicted values. What does that suggest?
  1. The target values are all constant.
  2. Every prediction is too high.
  3. The model misses a curved relationship.
  4. The errors have equal size everywhere.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Validation threshold L gives TP 36, FP 18 and FN 4; threshold H gives TP 28, FP 4 and FN 12. Each miss costs 3 units and each false alarm 2. Which threshold is cheaper, and what is its recall?
  1. L; recall 0.900
  2. H; recall 0.700
  3. H; recall 0.875
  4. L; recall 0.667
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A classifier outputs calibrated probabilities. Correct decisions have zero cost, a false alarm costs 4 units and a miss costs 12. What probability cutoff minimizes expected cost?
  1. 0.750
  2. 0.333
  3. 0.500
  4. 0.250
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

ROC curves cross: model A has higher TPR below FPR 0.01, while model B is better above FPR 0.10. Deployment allows at most FPR 0.005. Which region should guide the comparison?
  1. The region at FPR 0.005 or below.
  2. The region at FPR 0.10 or above.
  3. The region at equal numerical thresholds.
  4. The region nearest FPR 0.50.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Every probability score is replaced by its square before computing AUC. What happens to AUC?
  1. It falls because all positive scores fall.
  2. It rises because low scores become smaller.
  3. It stays the same because order is preserved.
  4. It becomes accuracy at a new threshold.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A multiclass classifier handles the largest class well but two small classes poorly. Which average gives every class equal influence?
  1. Weighted F1
  2. Micro F1
  3. Overall accuracy
  4. Macro F1
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A descending ranking has actual labels [positive, negative, positive, negative, positive]. What is average precision when recall increases at each positive?
  1. 0.600
  2. About 0.756
  3. About 0.667
  4. About 0.867
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A size-100 bootstrap resample is drawn from 100 original rows. Why can it contain fewer than 100 distinct rows?
  1. Rows are sampled with replacement.
  2. Each row is held out exactly once.
  3. Rows are split into disjoint folds.
  4. The positive class is removed first.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A forecasting team groups repeated device rows but fits its imputer on all dates, then randomly partitions device groups. It will predict future months for unseen devices. What boundaries does an honest evaluation need?
  1. Unseen devices; preprocessing may use future inputs.
  2. Later dates; the same devices may cross the boundary.
  3. Later dates and unseen devices; fit preprocessing on training rows.
  4. Random device groups; fit preprocessing on all unlabeled rows.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Models A and B have accuracies [0.80, 0.84, 0.82, 0.86] and [0.82, 0.83, 0.84, 0.87] on common folds. Prediction takes 2 ms for A and 12 ms for B; deployment permits at most 5 ms. Which candidate meets the timing requirement, and what does the paired accuracy evidence show?
  1. A meets timing; B gains 0.010 on every fold.
  2. B meets timing; its mean accuracy gain is 0.010.
  3. A meets timing; B gains 0.005 on average.
  4. A meets timing; B gains 0.010 on average, with one fold loss.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Audit a complete model evaluation10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A plot varies training epochs horizontally and shows loss vertically. Is this a sample-size learning curve or an optimization plot?
  1. A sample-size learning curve.
  2. An optimization plot.
  3. A hyperparameter validation curve.
  4. An ROC operating curve.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A pipeline has steps named "scale" and "neighbors". How should its k-NN neighbor count be named in a search grid?
  1. "neighbors__n_neighbors"
  2. "scale__n_neighbors"
  3. "n_neighbors__neighbors"
  4. "neighbors_n_neighbors"
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A final classifier is 90% accurate on 900 independent test cases. What is its approximate 95% accuracy interval using the normal approximation?
  1. 0.89 to 0.91
  2. 0.84 to 0.96
  3. 0.90 to 0.92
  4. 0.88 to 0.92
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Evaluation targets are 2, 4 and 6 minutes. A fitted mean baseline predicts 5 throughout, while a model predicts 3, 4 and 5. What are model R² and baseline R² on these rows?
  1. Model 0.750; baseline 0
  2. Model 0.818; baseline −0.375
  3. Model 0.750; baseline −0.375
  4. Model 0.250; baseline 0.375
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Four CV fold errors are 5, 7, 5 and 7 minutes. What are their mean and sample standard deviation, rounded to three decimals?
  1. Mean 6; SD 1.155 minutes
  2. Mean 6; SD 1.000 minutes
  3. Mean 6; SD 0.577 minutes
  4. Mean 24; SD 1.155 minutes
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An analyst runs a search inside outer CV, then tries three new feature sets after comparing outer means and reports the highest outer mean as independent final performance. What should change?
  1. Report the winning inner mean instead.
  2. Evaluate the selected workflow on untouched data.
  3. Average only the outer folds that improved.
  4. Refit on outer holdouts and report training error.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Three models, simplest to most flexible, have mean CV RMSE 4.45, 4.24 and 4.10 minutes. The lowest mean has standard error 0.20 minutes. Which does the one-standard-error rule select?
  1. The simplest, with RMSE 4.45.
  2. The most flexible, with RMSE 4.10.
  3. Any model, since all are within 0.40.
  4. The middle model, with RMSE 4.24.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two fault detectors are tested on the same cases. A has TP 32, FP 8, FN 8; B has TP 36, FP 24, FN 4. The team ranks them by F1. Which wins, and why can choosing by recall alone disagree?
  1. B wins F1; A has higher recall.
  2. B wins F1; B has fewer false alarms.
  3. A wins F1; B has higher recall.
  4. A wins F1; A has higher recall.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A review of 80 validation mistakes finds 44 unreadable inputs, 26 wrong labels and 10 rare product cases. Which category should be investigated first by the error-count approach?
  1. Rare product cases, because they are least common.
  2. Unreadable inputs, because they cause the most errors.
  3. All cases equally, without using their categories.
  4. Wrong labels, because they exceed half the errors.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A locked pipeline scores well on an untouched test set. The team then refits the same procedure on development plus test data for deployment. What may it honestly report?
  1. The earlier test score, identified as measured before refitting.
  2. A new independent test score from the combined training rows.
  3. The earlier score as a measurement of the exact enlarged fit.
  4. The enlarged fit training score as held-out performance.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

82 Key Terms, each with its definition

A

Accuracy
Accuracy is the fraction of all evaluated cases predicted correctly, counting correct results across every class in the denominator.
A majority-only classifier can have high accuracy when the class it ignores is very rare.
Accuracy paradox
The accuracy paradox is the misleadingly high accuracy a classifier can achieve on imbalanced data while missing the rare class.
Finding no faults can still produce 98% accuracy if only 2% of the evaluation cases are faulty.
Achievable baseline
An achievable baseline is a credible approximation to the best error realistically attainable, such as expert error or a justified noise level.
A majority-class dummy score is a trivial reference, not evidence of the lowest error the task permits.
Average precision (AP)
Average precision summarizes a precision–recall curve by weighting each precision by its associated increase in recall.
AP uses recall increments, so it differs from drawing straight lines and calculating trapezoidal PR area.
Avoidable bias
Avoidable bias is the gap between training error and a credible achievable error level, used as a practical signal of inadequate fit.
Training error 12% against expert error 3% suggests room to improve fitting before collecting similar data.

B

Baseline model
A baseline model is a simple fitted rule used as a reference when judging whether a more elaborate model improves useful predictions.
A mean dummy regressor learns its constant from training targets and is scored on the same held-out rows.
Bootstrap
The bootstrap draws repeated samples with replacement and uses variation in a statistic across those resamples to estimate uncertainty.
A size-200 bootstrap draw can repeat the same case and leave other original cases entirely absent.

C

Class imbalance
Class imbalance is an unequal frequency of class labels, often making a large majority class dominate overall accuracy.
A fault detector with thousands of negatives per positive needs alert precision as well as a low FPR.
Coefficient of determination (R²)
The coefficient of determination measures the share of evaluation-mean squared error removed by a model when targets vary.
R² of −0.2 means the model has 20% more squared error than the evaluation-mean reference.
Confidence interval
A confidence interval comes from a procedure intended to cover a population quantity at a stated rate across repeated samples.
A binomial accuracy interval on independent test cases does not directly provide an interval for F1.
Confusion matrix
A confusion matrix counts actual classes against predicted classes, showing correct predictions and specific kinds of classification error.
Scikit-learn places actual classes in rows, so the upper-right binary cell counts false positives.

D

Data leakage
Data leakage occurs when training uses evaluation information or information that would be unavailable when predicting a new case.
A status recorded after a fault is confirmed cannot honestly predict that fault before the inspection occurs.
Decision score
A decision score is a model output used to rank cases or assign labels through a cutoff; it need not be a calibrated probability.
A score of 0.8 can rank above 0.6 without establishing that 80% of similarly scored cases are positive.
Decision threshold
A decision threshold is the cutoff used to turn model scores into class labels, controlling which cases receive positive predictions.
Lowering an alert threshold can find more defects while also sending more sound items to inspection.

E

Error analysis
Error analysis examines validation mistakes, groups them into meaningful categories and counts them to identify useful development priorities.
If most mistakes involve unreadable inputs, that category deserves investigation before a rare error type.

F

F-beta score
An F-beta score combines precision and recall with a chosen emphasis: beta above 1 favors recall and below 1 favors precision.
F2 gives recall more influence than F1 when missed positives are the stronger practical concern.
F1 score
The F1 score is the harmonic mean of precision and recall, balancing them equally while leaving true negatives out of its calculation.
Strong precision cannot keep F1 high when recall is very low, because the harmonic mean penalizes imbalance.
False negative
A false negative is an actual positive predicted as negative, so the classifier misses a case it was intended to detect.
A defective component that passes the detector without being flagged is a false negative.
False positive
A false positive is an actual negative predicted as positive, creating a false alarm at the chosen decision threshold.
A valid file incorrectly flagged as corrupted adds a false positive to a file-corruption detector's confusion matrix.
False positive rate (FPR)
The false positive rate is the fraction of actual negatives flagged as positive, with actual negatives as its denominator.
FPR 0.01 means 1% of legitimate cases are flagged; it does not mean only 1% of alerts are false.
Fold
A fold is a subset used as a held-out validation portion during one rotation of an ordinary cross-validation run.
The model for the third rotation trains on all folds except the third, which supplies its validation score.
Fold-score standard deviation
A fold-score standard deviation measures score variation across held-out folds; it is not itself an uncertainty interval for future performance.
An RMSE report should identify whether its ± value is fold SD, a rough SE or a confidence interval.

G

Generalization error
Generalization error is expected prediction error on new cases from the source of interest, beyond the data used to fit the model.
Low training error alone cannot establish low error on new customers or later observations.
Grid search
Grid search evaluates every combination of listed hyperparameter values with a chosen validation procedure and selection metric.
Four neighbor counts and three weighting settings create 12 candidates before multiplying by the CV fold count.
Grouped cross-validation
Grouped cross-validation keeps each source entirely within one side of a split when testing generalization to previously unseen sources.
All rows from one device stay together so validation does not reward recognizing a device seen in training.

H

Hyperparameter
A hyperparameter configures the fitting or decision procedure, such as neighbor count, polynomial degree or a score cutoff.
The value of k is compared using development evidence before the selected k-NN procedure is refitted.

I

Irreducible error
Irreducible error is outcome noise remaining even when the predictive relationship is known, setting a floor for expected prediction error.
Random measurement noise can prevent expected prediction error from reaching zero for any fitted relationship.

K

k-fold cross-validation
k-fold cross-validation rotates a held-out fold while fitting fresh models on the remaining folds, then averages the held-out scores.
In a six-fold run, each row is evaluated once and participates in training for the other five fits.

L

Learning curve
A sample-size learning curve plots training and validation performance against the number of training examples, with a fresh fit at each size.
A widening data set that narrows a large validation gap supports trying more representative training cases.
Learning-curve plateau
A learning-curve plateau is a region where adding training examples changes error little, helping judge the likely value of further similar data.
Two close curves plateauing far above expert error suggest changing the model or inputs instead of sample size.
Leave-one-out cross-validation
Leave-one-out cross-validation holds out one row per fit and trains on all remaining rows, requiring one fitted model for each row.
A data set with 250 cases needs 250 fits for one leave-one-out evaluation of a fixed procedure.
Logarithmic search range
A logarithmic search range spaces or samples positive settings by multiplicative scale, allowing exploration across orders of magnitude.
Learning rates from 0.0001 to 1 can be explored by scale instead of placing most trials near the large end.

M

Macro average
A macro average is the unweighted mean of class-level metric values, giving each class equal influence regardless of its size.
Macro F1 can expose poor handling of small ticket classes that a large class would otherwise dominate.
Mean absolute error (MAE)
Mean absolute error is the average absolute residual, expressed in the target's unit, so positive and negative errors cannot cancel.
MAE of 4 minutes means the average absolute difference between actual and predicted times is 4 minutes.
Mean absolute percentage error (MAPE)
Mean absolute percentage error averages absolute errors relative to actual values; zero or near-zero actual values make it unsuitable.
Percentage errors can explode when actual demand is near zero even if the absolute prediction error is small.
Mean squared error (MSE)
Mean squared error is the average squared residual, in squared target units, giving large errors more weight than small ones.
A duration model's MSE is reported in minutes², so it is not directly an error measured in minutes.
Micro average
A micro average pools class-level TP, FP and FN counts before computing a metric; it equals accuracy in full single-label multiclass scoring.
Micro F1 matches overall accuracy when each ticket receives exactly one of the available class labels.
Model bias
Model bias is persistent error in the average prediction across possible training samples, often caused by assumptions too simple for the pattern.
A straight line fitted to a strongly curved relationship can retain high bias even with many training rows.
Model variance
Model variance is how much fitted predictions change across possible training samples, measuring sensitivity to sample-specific details.
A very small k can make k-NN predictions depend strongly on which nearby cases happened to be sampled.

N

Negated error scorer
A negated error scorer returns an error with its sign reversed so that larger values consistently mean better model performance.
In a CV search, negative RMSE −2 is better than −4; the corresponding positive errors are 2 and 4.
Nested cross-validation
Nested cross-validation tunes models inside outer training portions and evaluates each selected procedure on an untouched outer holdout.
Different outer folds can select different k values, so outer results describe the search procedure.

O

One-standard-error rule
The one-standard-error rule selects the simplest candidate whose mean is within one standard error of the best candidate's mean.
For error, add SE to the lowest mean; then choose the simplest candidate no higher than that limit.
One-vs-rest evaluation
One-vs-rest evaluation treats one class as positive and all other classes together as negative, then repeats for the other classes.
A three-class classifier can have a separate ROC curve for each class against the combined remainder.
Operating point
An operating point is the pair of performance rates or counts produced by one specific threshold on a classifier's scores.
An ROC operating point with FPR 0.02 and TPR 0.9 describes one cutoff, not the whole ranking.
Outer fold
An outer fold is the held-out evaluation portion in nested CV, excluded from the inner search and its winner refit.
The inner search selects settings without the outer fold, and only its finished winner is evaluated there.
Overfitting
Overfitting occurs when a model follows sample-specific noise, fitting training data much better than it predicts held-out cases.
A high-degree polynomial can have tiny training RMSE and a much larger validation RMSE.
Oversampling
Oversampling increases minority-class training representation by repeating or generating cases; it must stay within training portions.
Oversampling before splitting can put copies or related synthetic cases on both sides of validation.

P

Paired fold difference
A paired fold difference subtracts two candidate scores on the same held-out fold, isolating their observed advantage under common conditions.
A model that wins by 0.01 on each common fold has a more consistent advantage than changing-sign wins.
Parameter
A parameter is a value learned during model fitting, such as a regression coefficient, as distinct from a setting chosen for that procedure.
Fitting regression coefficients changes parameters; selecting polynomial degree changes a hyperparameter.
Pipeline
A pipeline bundles preprocessing and a model into one fitted procedure so CV can relearn the complete sequence inside each training fold.
Putting scaling before k-NN in a pipeline keeps validation rows out of the scaler's fitted statistics.
Positive class
The positive class is the outcome chosen for detection in a classification problem, usually coded 1 in binary examples.
For a document-review detector, "needs review" can be positive even though it is the less common class.
Precision
Precision is the fraction of predicted positives that are actually positive, measuring how trustworthy the classifier's alerts are.
Precision 0.8 means four fifths of alerts are correct, not that four fifths of all positives were found.
Precision–recall curve
A precision–recall curve plots precision against recall as the decision threshold changes, displaying alert reliability and detection together.
For rare faults, the PR curve shows how precision changes as the system aims to catch more actual faults.
Probability calibration
Probability calibration is agreement between predicted probabilities and observed positive rates among similarly scored cases.
If scores near 0.4 are calibrated, about 40% of those cases should be positive in the relevant population.

R

Random search
Random search evaluates a fixed number of sampled hyperparameter combinations from specified values or distributions.
A random search can sample learning rates across several orders of magnitude without filling a dense grid.
Ranking quality
Ranking quality describes how effectively model scores place positive cases above negative ones, independently of a selected cutoff.
Squaring probabilities preserves their order and AUC even though it changes their numerical interpretation.
Recall
Recall is the fraction of actual positives detected, also called sensitivity or true positive rate; it measures how many cases are found.
Recall 0.8 means the detector catches four fifths of the actual faults, regardless of false alarms.
Refit
A refit trains the selected procedure again on the full available development portion after its settings have been chosen.
GridSearchCV's default final refit produces best_estimator_ using all the rows passed to the search.
Repeated k-fold cross-validation
Repeated k-fold cross-validation reruns k-fold with different allocations to reduce dependence on one particular set of folds.
Repeating a shuffled five-fold split three times produces 15 validation scores for the procedure.
Resampling
Resampling repeatedly draws or partitions available cases to study model performance or a statistic's variability without collecting new cases.
Cross-validation rotates held-out portions, while the bootstrap draws replacement samples from existing rows.
Residual
A residual is an actual target value minus its prediction; its sign shows whether the prediction was too low or too high.
A mass predicted as 13 kg when it is actually 15 kg has a positive residual of 2 kg.
Residual plot
A residual plot displays prediction errors against a variable, often predictions, to reveal missed patterns or changing error spread.
A curved residual pattern suggests that a straight-line model has missed a curved relationship.
Residual sum of squares
The residual sum of squares is the total of the squared differences between actual targets and the model's predictions.
Adding squared residuals gives the numerator of the error ratio used to calculate R².
ROC AUC
ROC AUC is the area under an ROC curve, equal to positive–negative ranking success with half credit for tied scores.
AUC 0.9 means strong pair ordering; it does not establish 90% accuracy at the deployed threshold.
ROC curve
An ROC curve plots true positive rate vertically against false positive rate horizontally as the decision threshold varies.
A point near the top-left corner finds many positives while flagging relatively few actual negatives.
ROC dominance
ROC dominance means one model achieves at least as high a true positive rate at every false positive rate as the compared model.
Dominating curves may need different numerical thresholds because the models' score scales can differ.
Root mean squared error (RMSE)
Root mean squared error is the square root of MSE; it restores the target unit while retaining extra emphasis on large errors.
A model with a few very large misses can have RMSE much higher than MAE on the same evaluation rows.

S

Selection optimism
Selection optimism is the upward bias in the winning development score caused by selecting favorable sampling noise along with model quality.
Trying many candidates can raise the best observed CV score even when their true performance is the same.
Specificity
Specificity is the fraction of actual negatives correctly left negative; it is negative-class recall and equals one minus FPR.
High specificity means most legitimate messages remain unflagged, even if some spam is missed.
Standard error
A standard error describes sampling variability of an estimated quantity; a fold-based approximation is rough because training portions overlap.
Dividing fold SD by the square root of the fold count gives a rough SE, not an independence guarantee.
Stratified k-fold
Stratified k-fold keeps class proportions approximately alike in the validation folds, helping retain rare classes during evaluation.
With enough positives, stratification avoids folds whose recall estimate depends on just one accidental positive.

T

Test set
A test set is held apart from development decisions to measure performance after the model and its decision rule are fixed.
Changing a threshold in response to test errors means those rows no longer serve as an independent final check.
Test-set discipline
Test-set discipline keeps test results outside every development choice, using them only after the model and threshold have been fixed.
A disappointing final score should not trigger a new setting choice followed by another claimed independent test.
Time-series cross-validation
Time-series cross-validation evaluates later observations using models trained only on earlier observations, preserving prediction direction.
An expanding window trains through August before validating September, then advances to the next period.
Total sum of squares
The total sum of squares measures evaluation-target spread by adding squared deviations from those targets' own mean.
The denominator of R² is zero when every evaluation target has exactly the same value.
Training set
A training set supplies examples used to learn a model's parameters and the fitted values of its preprocessing steps.
A scaler learns its mean and spread from training rows before transforming held-out cases.
True negative
A true negative is an actual negative correctly predicted as negative, so it remains outside the positive alerts.
A legitimate message correctly left outside the spam folder counts as a true negative.
True positive
A true positive is an actual positive that a classifier correctly predicts as positive at the chosen decision threshold.
A genuinely defective component flagged for inspection contributes one true positive.

U

Underfitting
Underfitting occurs when a model fails to capture useful patterns and leaves substantial avoidable error even on its training data.
Training and validation errors that remain high and close together suggest a model with inadequate fit.

V

Validation curve
A validation curve plots training and validation performance against one hyperparameter to show how that setting affects generalization.
A curve over k values should be read knowing that larger k means a smoother, less flexible k-NN model.
Validation set
A validation set supplies held-out development examples used to choose model settings, features or a decision threshold.
Selecting the best k from validation F1 uses those rows for development, even without fitting coefficients on them.

W

Weighted average
A weighted class average combines per-class metric values using the number of actual cases in each class as the weights.
Weighted F1 is driven more by the largest class, so inspect small-class scores alongside it.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started