Skip to content

Model Evaluation

Choosing the right metric matters as much as choosing the right algorithm. A model that scores 85% accuracy can still miss most of the positive cases. This page covers the key metrics for classification and regression, when to use each, and how to read them.

Every code block runs in a container in the companion repository, so the numbers and figures are real.

from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
out = Path("outputs")
out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=1000,
n_features=20,
n_informative=5,
weights=[0.85, 0.15],
random_state=42)
x_train, x_test, y_train, y_test = train_test_split(features,
y,
test_size=0.2,
stratify=y,
random_state=42)
pipeline = Pipeline([("scaler", StandardScaler()),
("classifier",
LogisticRegression(max_iter=1000, random_state=42))])
pipeline.fit(x_train, y_train)
from sklearn.metrics import (accuracy_score, precision_score, recall_score,
f1_score, roc_auc_score, average_precision_score)
y_pred = pipeline.predict(x_test)
y_prob = pipeline.predict_proba(x_test)[:, 1]
print(f"Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print(f"Precision: {precision_score(y_test, y_pred):.4f}")
print(f"Recall: {recall_score(y_test, y_pred):.4f}")
print(f"F1: {f1_score(y_test, y_pred):.4f}")
print(f"ROC-AUC: {roc_auc_score(y_test, y_prob):.4f}")
print(f"Average precision: {average_precision_score(y_test, y_prob):.4f}")
all_negative = accuracy_score(y_test, np.zeros_like(y_test))
print(f"Accuracy when every sample is called negative: {all_negative:.4f}")
Accuracy: 0.8450
Precision: 0.5000
Recall: 0.1935
F1: 0.2791
ROC-AUC: 0.8066
Average precision: 0.4368
Accuracy when every sample is called negative: 0.8450

The model looks fine at 84.5% accuracy. But recall is only 0.19: it finds fewer than one in five positive cases.

  • Accuracy is the fraction of correct predictions. It is misleading with imbalanced data. A model that always predicts “negative” scores 0.845 here, the same accuracy as the fitted model.
  • Precision: of all samples predicted positive, how many are? High precision means few false positives.
  • Recall (sensitivity): of all truly positive samples, how many did the model find? Recall of 0.19 means it misses 81% of the positives.
  • F1 is the harmonic mean of precision and recall. Use it when both false positives and false negatives matter.
  • ROC-AUC measures the ability to rank positives above negatives across all thresholds. It is threshold-independent.
  • Average precision summarizes precision across recall increments. Its baseline depends on class prevalence, so compare models on the same evaluation population. It differs from a trapezoidal area under the precision-recall curve. The metric documentation defines this calculation.
Metric Use when
Accuracy Classes are balanced
Precision False positives are costly (unnecessary treatments)
Recall False negatives are costly (missed diagnoses)
F1 You need one number balancing precision and recall
ROC-AUC Comparing models, threshold-independent
Average precision Imbalanced data, the positive class is rare
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)
fig, ax = plt.subplots(figsize=(5, 4))
display = ConfusionMatrixDisplay(cm, display_labels=["Negative", "Positive"])
display.plot(ax=ax, cmap="Blues")
ax.set_title("Confusion matrix")
fig.tight_layout()
fig.savefig(out / "confusion-matrix.png", dpi=150)
plt.close(fig)
[[163 6]
[ 25 6]]

Confusion matrix: 163 true negatives, 6 false positives, 25 false negatives, 6 true positives

163 true negatives, 6 false positives, 25 false negatives, 6 true positives. The model is conservative: it predicts positive only when confident, so few false positives but many false negatives.

from sklearn.metrics import classification_report
print(
classification_report(y_test, y_pred, target_names=["Negative",
"Positive"]))
precision recall f1-score support
Negative 0.87 0.96 0.91 169
Positive 0.50 0.19 0.28 31
accuracy 0.84 200
macro avg 0.68 0.58 0.60 200
weighted avg 0.81 0.84 0.81 200

support is the number of samples per class. macro avg treats both classes equally; weighted avg accounts for class size.

The ROC curve plots the true positive rate against the false positive rate at every threshold. For imbalanced data the precision-recall curve is more informative, because its baseline is the positive-class prevalence (about 0.15 here), not 0.5.

from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay
fig, ax = plt.subplots(figsize=(5, 4))
RocCurveDisplay.from_estimator(pipeline, x_test, y_test, ax=ax)
ax.plot([0, 1], [0, 1], "k--", alpha=0.5, label="Random")
ax.set_title("ROC curve")
ax.legend()
fig.tight_layout()
fig.savefig(out / "roc-curve.png", dpi=150)
plt.close(fig)
fig, ax = plt.subplots(figsize=(5, 4))
PrecisionRecallDisplay.from_estimator(pipeline, x_test, y_test, ax=ax)
ax.set_title("Precision-recall curve")
fig.tight_layout()
fig.savefig(out / "precision-recall-curve.png", dpi=150)
plt.close(fig)

ROC curve Precision-recall curve

For this binary classifier, predict uses a probability threshold of 0.5. A different threshold changes the sensitivity and precision of the resulting labels. Choose a decision objective before inspecting test performance. This example fixes F1 as its teaching objective; an assay workflow needs an objective justified by its error costs.

The next block produces out-of-fold probabilities from the training partition. Each preprocessing fit uses only the training rows of its fold. It chooses the threshold with the highest F1 on those development predictions, then applies the fixed threshold to the test probabilities from the model already fitted above.

from sklearn.metrics import precision_recall_curve
from sklearn.model_selection import StratifiedKFold, cross_val_predict
development_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
development_probability = cross_val_predict(
pipeline, x_train, y_train, cv=development_cv, method="predict_proba"
)[:, 1]
development_precision, development_recall, thresholds = precision_recall_curve(
y_train, development_probability
)
denominator = development_precision[:-1] + development_recall[:-1]
development_f1 = np.divide(
2 * development_precision[:-1] * development_recall[:-1],
denominator,
out=np.zeros_like(denominator),
where=denominator > 0,
)
selected_threshold = thresholds[np.argmax(development_f1)]
print(f"Threshold selected from development predictions: "
f"{selected_threshold:.4f}")
for label, threshold in (("Default", 0.5),
("Development choice", selected_threshold)):
prediction = (y_prob >= threshold).astype(int)
print(f"{label}: test precision = "
f"{precision_score(y_test, prediction):.4f}, "
f"recall = {recall_score(y_test, prediction):.4f}, "
f"F1 = {f1_score(y_test, prediction):.4f}")
Threshold selected from development predictions: 0.2058
Default: test precision = 0.5000, recall = 0.1935, F1 = 0.2791
Development choice: test precision = 0.4048, recall = 0.5484, F1 = 0.4658

The test results describe the two prespecified procedures: the default rule and the development-selected rule. Do not choose between them after inspecting those test results, and do not adjust the threshold again to improve the test score. The selected development F1 is optimistic because the threshold search maximized it. Repeated patients or time-dependent observations also require an appropriate development split.

ROC AUC concerns ranking, while a calibration plot compares predicted probabilities with observed event frequencies. A model can rank samples well and still assign probabilities that are too extreme. The plot below groups the test predictions into five quantile bins. It evaluates the fixed model; it does not fit a calibration transformation on the test labels.

from sklearn.calibration import CalibrationDisplay
from sklearn.metrics import brier_score_loss, log_loss
print(f"Test Brier score: {brier_score_loss(y_test, y_prob):.4f}")
print(f"Test log loss: {log_loss(y_test, y_prob):.4f}")
figure, axis = plt.subplots(figsize=(5, 4))
CalibrationDisplay.from_predictions(
y_test, y_prob, n_bins=5, strategy="quantile", ax=axis,
name="Fixed logistic model"
)
axis.set_title("Test probability calibration")
figure.tight_layout()
figure.savefig(out / "probability_calibration.png", dpi=150)
plt.close(figure)
Test Brier score: 0.1169
Test log loss: 0.3725

Predicted probabilities and observed positive fractions in five test-set bins, with the ideal calibration diagonal.

Each bin contains a limited sample, so deviations from the diagonal also reflect sampling variation. Brier score and log loss assess probability predictions, but neither isolates calibration alone. If calibration adjustment is required, fit it within development data and preserve the final test data for evaluation.

The scikit-learn threshold guide separates probabilities from decisions. Its calibration guide explains the probability diagnostics and development-data requirements.

The regression metrics use a second synthetic dataset: 500 samples, 10 features, and Gaussian noise with a standard deviation of 10, fit with a scaled linear regression.

from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
features_r, y_r = make_regression(n_samples=500,
n_features=10,
noise=10.0,
random_state=42)
x_train_r, x_test_r, y_train_r, y_test_r = train_test_split(features_r,
y_r,
test_size=0.2,
random_state=42)
regressor = Pipeline([("scaler", StandardScaler()),
("regressor", LinearRegression())])
regressor.fit(x_train_r, y_train_r)
y_pred_r = regressor.predict(x_test_r)
rmse = np.sqrt(mean_squared_error(y_test_r, y_pred_r))
print(f"RMSE: {rmse:.4f}")
print(f"MAE: {mean_absolute_error(y_test_r, y_pred_r):.4f}")
print(f"R2: {r2_score(y_test_r, y_pred_r):.4f}")
RMSE: 9.8539
MAE: 7.7979
R2: 0.9951
  • RMSE is in target units and penalizes large errors most.
  • MAE is in target units and treats all errors equally; it is more robust to outliers than RMSE.
  • R-squared compares squared prediction error with a constant prediction equal to the test-set mean. It can be negative when predictions are worse than that reference. It does not establish performance on another cohort.
r2 = r2_score(y_test_r, y_pred_r)
fig, ax = plt.subplots(figsize=(5, 4))
ax.scatter(y_test_r, y_pred_r, alpha=0.5, s=20)
lims = [min(y_test_r.min(), y_pred_r.min()),
max(y_test_r.max(), y_pred_r.max())]
ax.plot(lims, lims, "k--", alpha=0.5, label="Perfect")
ax.set_xlabel("Actual")
ax.set_ylabel("Predicted")
ax.set_title(f"Predicted vs actual (R2 = {r2:.3f})")
ax.legend()
fig.tight_layout()
fig.savefig(out / "predicted-vs-actual.png", dpi=150)
plt.close(fig)

Predicted vs actual values, R-squared 0.995

Points on the diagonal are perfect predictions. Systematic deviations mean the model is biased in some ranges.

Task Primary metric Secondary
Balanced classification Accuracy, F1 ROC-AUC
Imbalanced classification Average precision, F1 ROC-AUC, recall
Regression RMSE MAE, R-squared
Ranking ROC-AUC Average precision

You change the threshold until recall looks acceptable on the test set. Can you still report that test result as an independent evaluation of the chosen procedure?

You cannot. The threshold choice used the test outcomes. Define the objective and choose the threshold within development data, then evaluate the fixed procedure on separate data.

Now that you can evaluate models, the next page is an Algorithms Overview of the main tabular algorithms, with StatQuest videos explaining how each one works.

  • scikit-learn model evaluation

    The metric reference distinguishes class decisions, ranking, and probability accuracy. It defines the denominators and averaging choices behind the displayed scores.

  • Decision-threshold tuning

    The guide explains threshold selection and the need for data separate from classifier fitting. It helps assess the development-prediction threshold search in this lesson.

  • Probability calibration

    The guide explains reliability curves and why a Brier score measures more than calibration alone. Use it when interpreting the quantile-bin plot and probability scores together.