- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Model Evaluation and Validation
Model Evaluation and Validation
IntermediateLesson 4 of 9 in Machine Learning Course
What you will learn
- Summarize the errors of a regression model with MAE, MSE, RMSE and , compare them with a simple baseline, and choose the measure that fits the cost of mistakes.
- Compute MAE, MSE and RMSE from residualsTurn 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 baselineCompute the coefficient of determination, read what values from 1 down to below 0 mean, and judge every regression score against a simple baseline model.
- Compute MAE, MSE and RMSE from residuals
- 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 matrixSort predictions into true and false positives and negatives, compute accuracy, and recognize when a high accuracy hides a useless model.
- Calculate precision, recall and F1Compute precision, recall, specificity and F1 from a confusion matrix, decide which matters for a task, and average them over several classes.
- Build and read a confusion matrix
- 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 recallSee 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 curvePlot 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 summariesRead AUC as a ranking probability, know what it does and does not measure, and switch to precision–recall summaries when positives are rare.
- Move the decision threshold to trade precision for recall
- 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 setsGive each data split its role, size the splits sensibly, and keep information from the evaluation data out of training.
- Run k-fold cross-validationCarry 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 foldsPick stratified, grouped or time-ordered cross-validation to fit the data, and run every data-dependent preprocessing step inside the folds with a pipeline.
- Split data into training, validation and test sets
- 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 tradeoffDescribe 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 errorCompare training and validation error with a baseline level of performance, name the problem, and choose the changes most likely to help.
- Read learning curvesPlot training and validation error against the number of training examples and read the shapes that signal high bias, high variance or a good fit.
- Explain the bias–variance tradeoff
- 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-validationTell 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 checkExplain 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 oneCompare models fairly on the same folds, prefer the simpler model when scores are close, and report the result with its baseline and uncertainty.
- Search hyperparameters with cross-validation
Model Evaluation and Validation study guide
1Measure 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: . 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:
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.
| Quantity | Values | Total |
|---|---|---|
| Residual | −2, 0, 3, 6, −2 | 5 |
| Absolute residual | 2, 0, 3, 6, 2 | 13 |
| Squared residual | 4, 0, 9, 36, 4 | 53 |
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.
| Need | Useful metric | Reason |
|---|---|---|
| Each minute of error has similar cost | MAE | Absolute errors grow linearly |
| A large miss is especially costly | RMSE | Squaring gives large errors extra weight |
| Smooth squared-error training objective | MSE | Convenient 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,
Here 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 : about 72% of the mean reference's squared error has been removed.
| Value | Interpretation |
|---|---|
| 1 | Perfect predictions |
| 0 | Same squared error as the evaluation-mean reference |
| Below 0 | More squared error than that reference |
Predicting 25 minutes for each delivery gives squared error 368 and . 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.
2Evaluate 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 class | Predicted negative | Predicted positive |
|---|---|---|
| Negative | True negative: TN | False positive: FP |
| Positive | False negative: FN | True 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.
- The 80 correctly flagged messages are TP.
- The other flagged messages give .
- The remaining actual spam gives .
- There are 900 legitimate emails, so .
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:
Here accuracy is . 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 . 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
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 and recall is .
The negative class has its own recall, 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 concern | Main quantity to inspect |
|---|---|
| Flagged legitimate messages are costly | Precision |
| Missing actual spam is costly | Recall |
| Correctly leaving negatives alone matters | Specificity |
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:
For the spam filter, . 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 and recall is . 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.
| Average | Method | Ticket F1 |
|---|---|---|
| Macro | Mean of class F1 scores | 0.724 |
| Weighted | Weight by actual class counts | 0.749 |
| Micro | Pool TP, FP and FN before calculating | 0.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.
3Compare 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.
| Threshold | TP | FP | FN | Precision | Recall |
|---|---|---|---|---|---|
| 0.75 | 2 | 1 | 2 | 0.667 | 0.50 |
| 0.50 | 3 | 2 | 1 | 0.600 | 0.75 |
| 0.40 | 4 | 3 | 0 | 0.571 | 1.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:
Here recall increases by 0.25 at each of the four positives. Their precisions when admitted are 1, 1, 0.75 and . 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 :
- 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 and predicting negative has cost . Choose positive when ; 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
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 . Passing a negative moves horizontally by . The first six moves are:
- Up to (0, 0.25), then (0, 0.50).
- Right to (0.167, 0.50).
- Up to (0.167, 0.75).
- Right to (0.333, 0.75).
- 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:
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 pairs. The first two positives each beat all six negatives. The third beats five and the fourth beats four. Thus . 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 . A small negative-class error rate still produces a large workload because there are so many negatives.
| Question | Useful 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.
4Estimate 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
| Set | What it does | Decisions it can guide |
|---|---|---|
| Training | Fits parameters | The learned coefficients or other fitted values |
| Validation | Compares development choices | Features, model family, hyperparameters and threshold |
| Test | Checks the final procedure | Final reporting after choices are locked |
A split of 10000 labeled rows gives 6000 training, 2000 validation and 2000 test rows. If cross-validation replaces a fixed validation set, an 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 . 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 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
| Method | Work | Main consideration |
|---|---|---|
| Five- or ten-fold | Five or ten fits per setting | Common compromise between cost and estimate quality |
| Leave-one-out | One fit per row | Trains on almost all rows, but expensive and often high-variance |
| Repeated k-fold | Several shuffled k-fold runs | Reduces 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 , 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 situation | Splitter | What stays separated |
|---|---|---|
| Independent rows, rare classes | StratifiedKFold | Class proportions remain similar |
| Repeated rows per source | GroupKFold | A source never crosses train and validation in a split |
| Groups and class imbalance | StratifiedGroupKFold | Groups stay intact while class balance is approximated |
| Future prediction | TimeSeriesSplit | Validation 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.
5Diagnose 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:
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 degree | Training RMSE | Validation RMSE | Signal |
|---|---|---|---|
| 1 | 6.0 | 6.3 | Model misses the pattern |
| 3 | 3.1 | 3.4 | Best validation result here |
| 12 | 0.9 | 7.8 | Model 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:
| Case | Training error | Validation error | Diagnosis |
|---|---|---|---|
| A | 4.5% | 12% | Small bias gap, large variance gap |
| B | 11% | 12% | Large bias gap, small variance gap |
| C | 10% | 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 problem | Changes to investigate | Why they help |
|---|---|---|
| High bias | More informative inputs, greater flexibility, fewer constraints, completed optimization | Improve the fit to patterns already present |
| High variance | More representative training cases, simpler model, fewer inputs, stronger constraints | Reduce dependence on particular training cases |
| Both | Address inadequate fit and unstable generalization | One 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 rows | High-bias train / validation | High-variance train / validation |
|---|---|---|
| 100 | 18% / 25% | 1% / 30% |
| 1000 | 21% / 22.5% | 3% / 18% |
| 5000 | 21.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.
6Tune 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.
| Attribute | Meaning |
|---|---|
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 . If score errors were independent, the average highest score would be about . 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:
- Hold out an outer fold.
- On the outer training portion, run an inner CV search.
- Refit the inner winner on that entire outer training portion.
- Score once on the untouched outer fold.
- 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-NN | Mean accuracy | Eligible at cutoff 0.831? |
|---|---|---|
| 5 | 0.842 | Yes |
| 15 | 0.836 | Yes |
| 31 | 0.825 | No |
The best model's standard error is 0.011, giving . 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
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 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
1Measure a delivery model’s errors
12 steps
- 1IntroductionAsk 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.
- 2ExampleSubtract 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.
- 3ExampleAverage 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.
- 4ExampleSquare 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.
- 5ChallengeCheck 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.
- 6Key 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.
- 7ExampleConstruct 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 of the evaluation-mean reference error and removes the rest.
- 8ExampleCalculate and interpret R²
Calculate . 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.
- 9TipFit 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. - 10ChallengeExplain 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 , 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.
- 11ChallengeCombine 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.
- 12RecapRead 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.
2Turn classification counts into useful scores
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart with the kinds of mistakes
- 2ExplanationFix the positive class and axes
- 3ExampleRecover the flagged column
- 4ChallengeRebuild a new matrix
- 5Key InsightAccuracy needs a reference
- 6ExampleUse the denominator that answers the question
- 7ConnectionCount negatives in their own population
- 8ExampleBalance precision and recall with F1
- 9ChallengeCompute the positive-class result
- 10ExplanationChoose how classes receive weight
- 11ChallengeAudit a multiclass headline
- 12RecapAttach the question to the metric
3Follow a ranking through different thresholds
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate a ranking from its cutoff
- 2ExampleChoose a cutoff on the ranked list
- 3ExampleLower the cutoff one step
- 4ChallengeMake a decision from error costs
- 5ExplanationSummarize the PR path
- 6ExplanationChange the axes for ROC
- 7ExampleTrace the first six moves
- 8ChallengeFind the operating point
- 9TipRead the part of the curve you can use
- 10ExampleCalculate AUC through pairs
- 11ChallengeCheck what a score transformation changes
- 12ExampleTranslate rare-class rates into alerts
- 13ChallengeConnect a threshold with its workload
- 14RecapReport the ranking and the action
4Build validation that matches new cases
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDefine what new means
- 2ExampleAssign three distinct roles
- 3TipCount the rare outcomes too
- 4ChallengeKeep the final check independent
- 5ExampleRotate the held-out fold
- 6ExampleLabel the mean and spread
- 7ChallengeCount the fits and their training rows
- 8ConnectionChoose how often to resample
- 9ExampleKeep repeated sources together
- 10ExplanationLearn preprocessing inside each fold
- 11ChallengeRepair a misleading feature search
- 12ChallengeCombine time and transformation boundaries
- 13RecapProtect every learned step
5Use error patterns to choose the next experiment
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk why the model is failing
- 2ExplanationSeparate bias, variance and noise
- 3ExampleCompare model flexibility
- 4ChallengeChange flexibility in k-NN
- 5ExampleGive the error level a baseline
- 6ExampleDiagnose a different pair of gaps
- 7ChallengeChoose a remedy for the main gap
- 8TipInspect actual validation mistakes
- 9ExampleRead a high-bias learning curve
- 10ExampleRead a narrowing high-variance gap
- 11ChallengeLook beyond a small gap
- 12ChallengeUse a curve and a diagnosis together
- 13RecapTurn a diagnosis into an experiment
6Select and report a model honestly
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionEvaluate the choices as well as the fit
- 2ExplanationName what fitting learns
- 3ExampleCount every grid combination
- 4TipSearch the whole pipeline
- 5ChallengeUse a fixed random-search budget
- 6Key InsightThe winning score selected favorable noise
- 7ChallengeNotice a consumed test set
- 8ExplanationPut tuning inside an outer evaluation
- 9ExampleCount nested search work
- 10ConnectionPair the candidate comparisons
- 11ExampleApply a simplicity cutoff
- 12ChallengeSelect within an error band
- 13TipLabel uncertainty with its metric
- 14ChallengeChoose what belongs in the final report
- 15RecapKeep selection and measurement distinct
Model Evaluation and Validation practice questions
Set 1: Measure errors and read classification results10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
"scale" and "neighbors". How should its k-NN neighbor count be named in a search grid?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accuracy
Accuracy paradox
Achievable baseline
Average precision (AP)
Avoidable bias
B
Baseline model
Bootstrap
C
Class imbalance
Coefficient of determination (R²)
Confidence interval
Confusion matrix
D
Data leakage
Decision score
Decision threshold
E
Error analysis
F
F-beta score
F1 score
False negative
False positive
False positive rate (FPR)
Fold
Fold-score standard deviation
G
Generalization error
Grid search
Grouped cross-validation
H
Hyperparameter
I
Irreducible error
K
k-fold cross-validation
L
Learning curve
Learning-curve plateau
Leave-one-out cross-validation
Logarithmic search range
M
Macro average
Mean absolute error (MAE)
Mean absolute percentage error (MAPE)
Mean squared error (MSE)
Micro average
Model bias
Model variance
N
Negated error scorer
Nested cross-validation
O
One-standard-error rule
One-vs-rest evaluation
Operating point
Outer fold
Overfitting
Oversampling
P
Paired fold difference
Parameter
Pipeline
Positive class
Precision
Precision–recall curve
Probability calibration
R
Random search
Ranking quality
Recall
Refit
Repeated k-fold cross-validation
Resampling
Residual
Residual plot
Residual sum of squares
ROC AUC
ROC curve
ROC dominance
Root mean squared error (RMSE)
S
Selection optimism
Specificity
Standard error
Stratified k-fold
T
Test set
Test-set discipline
Time-series cross-validation
Total sum of squares
Training set
True negative
True positive
U
Underfitting
V
Validation curve
Validation set
W
Weighted average
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.