Machine Learning • Machine Learning Fundamentals • 20 min read

Evaluating Machine Learning Models

A high score is not the whole story

Imagine a factory where only one product in 100 is defective. A classifier that always predicts “not defective” would achieve 99% accuracy while finding zero defective products. The score sounds impressive; the actual system is useless for detecting defects.

Model evaluation means asking whether predictions are good for the particular decision you need to make, using observations that did not guide model development. A classification task may require precision, recall, or F1 rather than accuracy alone. A numerical prediction task needs different measures, such as mean absolute error.

Start by asking what each mistake costs. In defect detection, missing a dangerous defect may matter more than inspecting a healthy product. In another setting, false alarms may be extremely expensive. Choosing a metric is therefore a problem-design decision, not just a mathematical formality.

Then ask whether the evaluation is trustworthy. Did the model see related examples during training? Is the test set representative of deployment? Did you tune repeatedly using the test results? These questions determine whether a reported score is useful evidence or just another attractive number on a dashboard.

A machine learning model must do more than produce predictions. It must produce useful predictions on data that did not determine its design, and its errors must be acceptable for the problem it is intended to solve. Model evaluation is the systematic process of measuring a model’s performance, comparing it with alternatives, and investigating where and why it fails.

No single score describes every aspect of model quality. The appropriate evaluation depends on the task, data collection process, relative costs of errors, and intended use. For example, a medical screening classifier may place particular importance on detecting positive cases, while a house-price predictor is usually assessed by the size of its numerical errors.

1. What does model evaluation measure?

In supervised learning, the model receives input features xx and predicts a target yy:

y^=fθ(x).\hat y = f_\theta(x).

An evaluation metric maps observed targets and model outputs to a number that describes one aspect of performance. Some metrics are better when higher (such as accuracy); others are better when lower (such as mean absolute error).

Evaluation should distinguish four questions:

  1. Predictive performance: How closely do predictions match the target?
  2. Generalization: Does that performance carry over to genuinely unseen examples?
  3. Operational suitability: Are errors, latency, resource use, and other constraints acceptable?
  4. Reliability: Does performance remain acceptable across relevant populations, time periods, and conditions?

A high metric score is evidence about the data and evaluation procedure used. It is not a guarantee of performance in every setting.

Loss functions versus evaluation metrics

A loss function guides the fitting of a model; an evaluation metric expresses how well its outputs meet an evaluation objective. They can be identical, but need not be.

Example taskTraining loss (possible choice)Evaluation metrics (possible choices)
Binary classificationBinary cross-entropyPrecision, recall, F1, ROC-AUC
Multiclass classificationMulticlass cross-entropyAccuracy, macro-F1, log loss
Numerical predictionMean squared errorMAE, RMSE, R2R^2
Imbalanced event detectionWeighted cross-entropyPrecision-recall measures, recall at a chosen precision

The training algorithm can optimize a smooth loss even when the final operational objective is thresholded and non-differentiable.

2. Evaluation begins with a trustworthy data split

A familiar supervised learning arrangement uses three distinct datasets:

DatasetMain roleMay it guide model selection?
Training setFit model parameters and learned preprocessingYes
Validation setCompare choices, tune hyperparameters and select thresholdsYes
Test setEstimate final performance after choices are fixedNo

The test set should remain independent of model-development decisions. Repeatedly checking it and changing the model in response turns it into another validation set.

Training data fits a model, validation data guides model selection, and a held-out test set supports final evaluation.
Training and validation support development; the held-out test set provides a final estimate after decisions are fixed.

For small datasets, cross-validation can offer more stable estimates during development. For time-series data, use a chronological split rather than randomly mixing future observations into training. When records from the same person, patient, customer, or device are strongly related, use group-aware splitting so related records do not appear on both sides of the evaluation boundary.

See Data Splitting, Labeling, and Leakage for the underlying principles.

3. Classification evaluation: the confusion matrix

A classifier predicts a category. For a binary task, assume the positive class is the event we want to detect. Four counts describe the outcome:

  • True positive (TP): Predict positive when the actual class is positive.
  • False positive (FP): Predict positive when the actual class is negative.
  • False negative (FN): Predict negative when the actual class is positive.
  • True negative (TN): Predict negative when the actual class is negative.
Actual classPredicted positivePredicted negative
PositiveTPFN
NegativeFPTN

Suppose a detector is evaluated on 200 messages and produces:

  • TP = 40
  • FP = 10
  • FN = 20
  • TN = 130

These counts support several different metrics. Each answers a different question.

Accuracy

Accuracy is the fraction of predictions that are correct:

Accuracy=TP+TNTP+TN+FP+FN.\mathrm{Accuracy} = \frac{TP+TN}{TP+TN+FP+FN}.

For the example:

40+130200=0.85.\frac{40+130}{200} = 0.85.

Accuracy is 85%. However, it can mislead when classes are imbalanced. If 99% of examples belong to the negative class, a model that always predicts negative achieves 99% accuracy while detecting no positive cases.

Precision

Precision measures the proportion of predicted positives that are truly positive:

Precision=TPTP+FP.\mathrm{Precision} = \frac{TP}{TP+FP}.

Here:

4040+10=0.80.\frac{40}{40+10} = 0.80.

Precision is 80%. It matters when acting on a false alarm is costly. For example, automatically blocking legitimate messages could create a serious problem for users.

Recall (sensitivity)

Recall measures the proportion of actual positive examples that are detected:

Recall=TPTP+FN.\mathrm{Recall} = \frac{TP}{TP+FN}.

Here:

4040+20≈0.667.\frac{40}{40+20} \approx 0.667.

Recall is approximately 66.7%. It matters when missing a positive case is costly. Recall is also called sensitivity or the true positive rate.

Specificity

Specificity measures the proportion of actual negatives identified correctly:

Specificity=TNTN+FP=130140≈0.929.\mathrm{Specificity} = \frac{TN}{TN+FP} = \frac{130}{140} \approx 0.929.

Specificity is approximately 92.9%. Its complement is the false positive rate:

FPR=FPFP+TN=1−Specificity.\mathrm{FPR} = \frac{FP}{FP+TN} = 1-\mathrm{Specificity}.

F1-score

The F1-score combines precision and recall using their harmonic mean:

F1=2Precision⋅RecallPrecision+Recall=2TP2TP+FP+FN.F_1 = 2\frac{\mathrm{Precision}\cdot\mathrm{Recall}}{\mathrm{Precision}+\mathrm{Recall}} = \frac{2TP}{2TP+FP+FN}.

For the example:

F1=8080+10+20≈0.727.F_1 = \frac{80}{80+10+20} \approx 0.727.

The F1-score is approximately 72.7%. It is helpful when both false positives and false negatives deserve attention, but it does not include true negatives and does not encode a specific business cost model.

Note: When a metric’s denominator is zero, its value may be undefined. Software libraries provide explicit policies for reporting such cases. Never assume that an undefined value always means zero.

4. Classification thresholds and the precision-recall trade-off

Some classifiers produce a score or estimated probability rather than only a class label. A threshold converts that score into a decision:

y^={1if s(x)≥t,0otherwise.\hat y = \begin{cases} 1 & \text{if } s(x) \geq t,\\ 0 & \text{otherwise.} \end{cases}

Here s(x)s(x) is a model score and tt is a chosen threshold.

Raising the threshold usually reduces positive predictions. That often increases precision but decreases recall; lowering it often does the reverse. The exact behavior depends on the score distribution and the dataset.

A threshold of 0.5 is not universally optimal. It should be chosen using validation data and the real consequences of different errors. For instance:

  • For fraud screening, missing costly fraudulent transactions may justify a lower detection threshold, followed by human review.
  • For automatically deleting user content, false positives can be especially harmful, motivating a stricter threshold.

Use the final test set to evaluate the selected threshold, not to select it.

ROC curve and ROC-AUC

The receiver operating characteristic (ROC) curve plots the true positive rate against the false positive rate as the decision threshold changes.

ROC-AUC is the area under that curve. For binary classification with appropriately oriented continuous scores, it can be interpreted as the probability that a randomly selected positive example receives a higher score than a randomly selected negative example, with half credit for ties.

A score near 1 indicates strong ranking separation; a score near 0.5 is consistent with random ranking under the usual assumptions. ROC-AUC measures ranking ability across thresholds. It does not, by itself, identify a threshold or guarantee that reported probabilities are calibrated.

Precision-recall curve and average precision

A precision-recall (PR) curve shows precision against recall across score thresholds. It is especially informative when the positive class is rare and positive-class retrieval is the focus.

Average precision (AP) summarizes the PR curve using a weighted average of precision at successive recall changes. It is not generally identical to the geometric area computed by trapezoidal interpolation.

Because PR metrics are influenced by class prevalence, compare them using the relevant population and dataset distribution.

5. Evaluating multiclass classification

A multiclass classifier chooses among more than two mutually exclusive labels, such as cat, dog, and bird.

A multiclass confusion matrix records predicted versus actual classes. For each class, we can calculate precision, recall, and F1 after treating that class as positive and all other classes as negative.

Common aggregation methods include:

Averaging methodInterpretationMain consideration
Macro averageUnweighted mean across classesTreats small and large classes equally
Weighted averageClass-wise mean weighted by true supportMay be dominated by frequent classes
Micro averagePools TP, FP, and FN counts before calculatingEmphasizes overall example-level outcomes

For standard single-label multiclass classification, micro-averaged precision, recall, and F1 equal accuracy when all classes are included. Macro-F1 can reveal poor performance on rare classes that overall accuracy may conceal.

For multilabel classification, where each example may have several simultaneously applicable labels, evaluation choices differ; document whether metrics are computed per label, per sample, or globally.

6. Evaluating numerical predictions: regression metrics

A regression model predicts a numerical value. For nn observations with actual values yiy_i and predicted values y^i\hat y_i, define the error:

ei=yi−y^i.e_i = y_i - \hat y_i.

Mean absolute error (MAE)

MAE=1n∑i=1n∣yi−y^i∣.\mathrm{MAE} = \frac{1}{n}\sum_{i=1}^{n}|y_i-\hat y_i|.

MAE is the average absolute error, in the same units as the target. If a delivery-time model has an MAE of 4 minutes, its predictions differ from actual times by 4 minutes on average in absolute terms for that evaluation dataset.

Mean squared error (MSE) and root mean squared error (RMSE)

MSE=1n∑i=1n(yi−y^i)2,\mathrm{MSE} = \frac{1}{n}\sum_{i=1}^{n}(y_i-\hat y_i)^2, RMSE=MSE.\mathrm{RMSE} = \sqrt{\mathrm{MSE}}.

Squaring errors gives large errors more influence. MSE is expressed in squared target units; RMSE returns to the original units.

Consider actual values [3,5,7][3,5,7] and predictions [2,5,10][2,5,10]. The absolute errors are [1,0,3][1,0,3]:

MAE=1+0+33≈1.33,\mathrm{MAE} = \frac{1+0+3}{3} \approx 1.33, RMSE=1+0+93≈1.83.\mathrm{RMSE} = \sqrt{\frac{1+0+9}{3}} \approx 1.83.

RMSE is higher because it penalizes the large error more strongly.

Coefficient of determination: R2R^2

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2.R^2 = 1-\frac{\sum_i (y_i-\hat y_i)^2}{\sum_i (y_i-\bar y)^2}.

R2R^2 compares the model’s squared prediction errors with a baseline that always predicts the mean of the observed targets. On a nonconstant evaluation target:

  • R2=1R^2=1 indicates perfect predictions.
  • R2=0R^2=0 matches that mean-prediction reference in squared-error terms.
  • R2<0R^2<0 means the predictions perform worse than that reference.

An R2R^2 score is not a percentage of predictions that are correct, and it does not establish a causal relationship. It may be undefined or handled specially for constant targets, depending on the reporting convention or library configuration.

Which regression metric should you choose?

MetricUseful whenImportant limitation
MAETypical magnitude of error is the main concernLess sensitive to rare large errors
RMSELarge prediction errors deserve extra weightCan be strongly influenced by outliers
MSESquared error is the optimization or evaluation objectiveHarder to interpret because units are squared
R2R^2Comparing to a mean-prediction referenceContext-dependent and potentially negative

Avoid treating percentage-error metrics as universally appropriate: many become unstable or undefined when true targets are zero or near zero.

7. Baselines: performance needs a reference point

A baseline is a simple, clearly defined method used to judge whether a more complex model adds value. Without a baseline, a metric value can be hard to interpret.

Suitable baselines might include:

  • Always predicting the majority class for classification.
  • Predicting the training-set mean or median for regression.
  • Using a simple linear model before a complex nonlinear model.
  • Using a previously established production model.
  • Using a reasonable non-ML rule or heuristic.

If an advanced classifier achieves 92% accuracy but the majority-class baseline achieves 96%, the advanced model has not demonstrated an improvement in that metric.

Compare models using the same valid data splits, target definition, metric definition, and evaluation procedure. Otherwise, apparent improvements may be artifacts of different testing conditions.

8. Cross-validation and hyperparameter tuning

kk-fold cross-validation partitions the available development data into kk folds. Each round fits on k−1k-1 folds and evaluates on the remaining fold. The process repeats until each fold has served as validation data.

For example, five-fold cross-validation produces five validation scores:

s1,s2,s3,s4,s5.s_1,s_2,s_3,s_4,s_5.

A commonly reported aggregate is their arithmetic mean:

sˉ=15∑j=15sj.\bar s = \frac{1}{5}\sum_{j=1}^{5}s_j.

The variation between fold scores offers some indication of sensitivity to the particular split, though folds are not independent random trials and their standard deviation is not automatically a valid confidence interval.

Use stratified folds when maintaining class proportions is important. Use group-aware splitting when related samples must remain together. Use time-aware validation for forecasting and other temporally ordered problems.

How cross-validation can go wrong

Suppose you standardize the entire dataset and then run cross-validation. Every held-out fold has already influenced the mean and standard deviation used by that transformation. This creates data leakage.

Fit learned transformations within the training portion of each fold. In scikit-learn, a Pipeline helps enforce that separation.

When cross-validation is used to choose hyperparameters, the best reported cross-validation score is a selection score, often optimistic for the chosen configuration. Evaluate the finalized choice on an untouched test set. For an especially rigorous estimate when model selection is extensive, consider nested cross-validation.

9. Practical Python example: classification evaluation

The following example trains a logistic regression classifier on a built-in dataset, evaluates a dummy baseline with the same split, and displays several complementary metrics. The pipeline fits scaling on the training data only.

from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score,
    confusion_matrix,
    f1_score,
    precision_score,
    recall_score,
    roc_auc_score,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)

model = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=2000, random_state=42),
)
model.fit(X_train, y_train)

baseline_predictions = baseline.predict(X_test)
predictions = model.predict(X_test)
positive_scores = model.predict_proba(X_test)[:, 1]

print("Baseline accuracy:", accuracy_score(y_test, baseline_predictions))
print("Model accuracy:", accuracy_score(y_test, predictions))
print("Precision:", precision_score(y_test, predictions))
print("Recall:", recall_score(y_test, predictions))
print("F1:", f1_score(y_test, predictions))
print("ROC-AUC:", roc_auc_score(y_test, positive_scores))
print("Confusion matrix:\n", confusion_matrix(y_test, predictions))

Interpretation: The confusion matrix identifies which errors occur. Precision and recall describe different aspects of positive-class detection. ROC-AUC measures score ranking across thresholds, while the dummy classifier establishes a minimum reference. The dataset uses a specific binary label encoding; always verify which label is the positive class before interpreting these metrics.

This is a teaching example, not a validated clinical system. Real deployment would require representative external data, careful validation, calibration analysis, risk assessment, and appropriate oversight.

Optional cross-validation during development

Use the following code on the training split only to estimate model performance while developing it:

from sklearn.model_selection import StratifiedKFold, cross_val_score

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(
    model, X_train, y_train, cv=cv, scoring="f1"
)
print("F1 scores by fold:", scores)
print("Mean validation F1:", scores.mean())

If those results inform your choice of model or settings, reserve the held-out test split for the final evaluation.

10. Practical Python example: regression evaluation

The following example compares a linear regression model with a simple mean-prediction baseline. It reports several metrics rather than relying on one number.

from sklearn.datasets import make_regression
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import (
    mean_absolute_error,
    mean_squared_error,
    r2_score,
)
from sklearn.model_selection import train_test_split
import numpy as np

X, y = make_regression(
    n_samples=500, n_features=6, noise=20, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

baseline = DummyRegressor(strategy="mean")
model = LinearRegression()

for name, estimator in [("Mean baseline", baseline), ("Linear model", model)]:
    estimator.fit(X_train, y_train)
    predictions = estimator.predict(X_test)
    mae = mean_absolute_error(y_test, predictions)
    rmse = np.sqrt(mean_squared_error(y_test, predictions))
    r2 = r2_score(y_test, predictions)
    print(f"{name}: MAE={mae:.2f}, RMSE={rmse:.2f}, R2={r2:.3f}")

The synthetic data is designed around a linear relationship, so linear regression is a reasonable candidate. That result should not be generalized to arbitrary real-world data.

11. Beyond one average score: error analysis

Two models may have similar overall metrics yet make errors in very different ways. Error analysis examines individual failures and systematic patterns.

Useful questions include:

  1. Which examples are misclassified or have the largest regression residuals?
  2. Does the model struggle with underrepresented categories or unusual feature values?
  3. Is performance different across important groups or environments?
  4. Does the model fail on observations collected later in time?
  5. Could labeling mistakes or target ambiguity explain certain errors?
  6. Does model confidence correspond to actual correctness?

For a probability-producing classifier, calibration asks whether predicted probabilities match observed event frequencies. For instance, among appropriately comparable cases assigned an event probability near 0.8, roughly 80% should experience the event if the scores are well calibrated. A model may rank cases well but still be poorly calibrated.

Also consider uncertainty. An evaluation score from a small test set can change substantially with a different sample. Report the test-set size, class support, and, where appropriate, confidence intervals or resampling-based uncertainty estimates using methods suited to the sampling structure.

12. Evaluation under changing conditions

A held-out test result estimates performance under the conditions represented by that test set. Production systems may encounter new data distributions, unusual inputs, changing user behavior, or modified target definitions.

After deployment, consider monitoring:

  • Input-data distributions and missing-value rates.
  • Predictive performance once trustworthy labels become available.
  • Differences in error rates across relevant populations or contexts.
  • Model confidence and calibration where applicable.
  • Latency, failure rates, and infrastructure cost.
  • Data drift, changes in input distributions, and concept drift, changes in the relationship between inputs and targets.

Retraining is not automatically the correct response to a performance drop. First investigate data quality, labeling changes, measurement shifts, and the suitability of the original problem formulation.

13. Common evaluation mistakes

MistakeWhy it is misleadingBetter practice
Reporting only training accuracyFitting quality is not held-out performanceEvaluate on unseen examples
Reporting only overall accuracyCan hide minority-class failuresInclude confusion matrix and class-aware metrics
Selecting the threshold on the test setTest outcomes influence developmentChoose threshold on validation data
Scaling before cross-validationHeld-out folds affect learned preprocessingFit preprocessing inside each fold with a pipeline
Random splitting of time-series dataFuture information may leak backwardUse chronological evaluation
Ignoring a simple baselineA complex model may add no valueCompare against a defensible reference
Reporting ROC-AUC as if it were accuracyROC-AUC assesses ranking, not threshold accuracyExplain what each metric measures
Treating R2R^2 as a correctness percentageR2R^2 compares squared error to a referenceReport error magnitude and units too
Comparing scores from different datasetsDifferent data may have different difficultyUse a consistent, representative evaluation protocol
Reusing a test set repeatedlyModel selection overfits the test setPreserve a genuinely final evaluation

14. Check your understanding

  1. Why is a test set different from a validation set?
  2. When can accuracy be deceptive?
  3. What is the difference between precision and recall?
  4. Why might a classifier have high ROC-AUC but poor probability calibration?
  5. Which metric penalizes large regression errors more heavily: MAE or RMSE?
  6. Can R2R^2 be negative? What does that imply?
  7. Why does preprocessing belong inside cross-validation folds?
  8. Why are baselines necessary?
  9. When should you consider a time-based or group-aware split?
  10. Why does a production model require ongoing evaluation?
Show suggested answers
  1. Validation data influences development choices; the test set is reserved for a final estimate after those choices are fixed.
  2. Class imbalance can make a majority-class predictor appear successful without detecting the important class.
  3. Precision asks how many predicted positives are correct; recall asks how many actual positives were detected.
  4. ROC-AUC evaluates ranking across thresholds, whereas calibration evaluates whether numerical probabilities match frequencies.
  5. RMSE, because errors are squared before averaging.
  6. Yes. It means prediction squared error exceeds the specified mean-prediction reference on that evaluation data.
  7. Otherwise the held-out fold influences the transformation and can contaminate its evaluation.
  8. A score has limited meaning without a simple comparison showing the model’s added value.
  9. When chronology matters or related examples share information that must not cross the evaluation boundary.
  10. Real-world data and task conditions can change, reducing performance after the initial test.

References and further reading

Related articles in

  • Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
  • Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
  • Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.

Image preview

Fit