Choosing a machine learning metric is a measurement decision, not a final formatting step. This practical guide explains which classification, regression, and ranking metrics to track, how to calculate them with scikit-learn, how to handle imbalanced data, and how to report results so that a score reflects the real objective of your model.
Overview
The right evaluation metric depends on what errors matter, what information your model produces, and how predictions will be used. There is no universally best metric. Accuracy may be useful when classes are reasonably balanced and errors have similar consequences, but it can be misleading when one class is rare. Similarly, RMSE may be appropriate when large regression errors deserve extra weight, while MAE is easier to interpret when every error should contribute more evenly.
Start by defining the decision your model supports. For example:
- Screening: missing a positive case may be more costly than reviewing a false alarm, so recall deserves close attention.
- Limited follow-up capacity: precision may matter because only the highest-confidence predictions can be acted on.
- Probability-based decisions: log loss or a calibration measure may be more useful than a thresholded classification score.
- Continuous prediction: MAE, RMSE, or a relative error measure can describe how far predictions are from observed values.
- Search or recommendation: ranking metrics evaluate whether relevant items appear near the top, rather than merely whether an item receives a positive label.
Metrics should be calculated on validation or test data that was not used to fit the model. For a broader workflow, see Machine Learning Model Evaluation: Metrics, Validation Methods, and Error Analysis.
What to track
Classification metrics
Classification begins with the confusion matrix: true positives, true negatives, false positives, and false negatives. These counts support several common measures.
| Metric | Formula or meaning | Best used when | Important caution |
|---|---|---|---|
| Accuracy | (TP + TN) / all predictions | Classes and error costs are reasonably balanced. | Can look strong when the majority class dominates. |
| Precision | TP / (TP + FP) | False positives are costly or review capacity is limited. | Higher precision can come with lower recall. |
| Recall | TP / (TP + FN) | Missing positive cases is especially costly. | Increasing recall may create more false positives. |
| F1 score | Harmonic mean of precision and recall | You need one thresholded score balancing both measures. | It does not include true negatives or express business costs directly. |
| ROC-AUC | Ranking quality across classification thresholds | You want a threshold-independent view of score ordering. | May appear optimistic when the positive class is very rare. |
| PR-AUC | Area under the precision-recall curve | The positive class is rare and positive retrieval matters. | Interpret it alongside the positive-class prevalence and operating threshold. |
| Log loss | Penalty for incorrect and poorly calibrated probabilities | Predicted probabilities will drive decisions or prioritization. | A confident wrong prediction is penalized heavily. |
Do not report only a single classification score. At minimum, include the confusion matrix, precision, recall, F1 score, and the chosen decision threshold. If your model outputs probabilities, also inspect calibration and log loss. A model can rank cases well while producing probabilities that are not reliable enough for downstream decisions.
Regression metrics
| Metric | Formula or meaning | Best used when | Important caution |
|---|---|---|---|
| MAE | Mean of absolute errors | You want an error measure in the target's original units. | Large errors are not emphasized as strongly as they are by RMSE. |
| RMSE | Square root of mean squared errors | Large errors should receive extra weight. | Outliers can dominate the result. |
| R² | Relative improvement over a baseline mean predictor | You want a broad measure of explained variation. | It is not an average error in business units and can be negative. |
Use MAE when you need an accessible statement such as “the typical absolute error is about five units.” Use RMSE when a few large mistakes create disproportionate operational or financial risk. Always compare with a simple baseline and review residuals by meaningful groups, time periods, or value ranges.
Ranking metrics
For search, recommendation, and retrieval systems, the order of results matters. Precision@k measures the proportion of the first k results that are relevant. Recall@k measures how much of the relevant set appears in those first k results. Mean reciprocal rank emphasizes the position of the first relevant result, while normalized discounted cumulative gain can account for graded relevance and the decreasing value of lower-ranked positions.
Choose k to match the interface or workflow. A metric at 10 is not interchangeable with one at 100. If you are evaluating a generative or retrieval-augmented system, define a repeatable test set and inspect individual failures; the approach described in LLM Evaluation Test Cases can help structure that process.
A practical metric-selection decision tree
- Is the target continuous? Start with MAE and RMSE, then add R² or a domain-specific measure if useful.
- Is the target a class label? Identify whether false positives, false negatives, or both are costly.
- Are classes imbalanced? Look beyond accuracy; use precision, recall, F1, PR-AUC, and the confusion matrix.
- Will predicted probabilities be consumed? Add log loss and assess calibration.
- Does result order matter? Use ranking metrics at the actual display or action cutoff.
- Can a single metric hide a failure? Report a small metric set, subgroup results, and representative errors.
Scikit-learn examples
For binary classification, calculate thresholded and probability-based measures separately:
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
roc_auc_score, average_precision_score, log_loss,
confusion_matrix
)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, zero_division=0)
recall = recall_score(y_test, y_pred, zero_division=0)
f1 = f1_score(y_test, y_pred, zero_division=0)
roc_auc = roc_auc_score(y_test, y_proba)
pr_auc = average_precision_score(y_test, y_proba)
loss = log_loss(y_test, y_proba)
cm = confusion_matrix(y_test, y_pred)
Here, y_pred contains labels after applying a threshold, while y_proba contains the model's probability for the positive class. Do not pass hard labels to a probability metric. For regression:
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import numpy as np
mae = mean_absolute_error(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
Check the installed scikit-learn version before copying examples into a production workflow, because function options and supported behavior can change. Keep preprocessing inside a pipeline and evaluate it within the same cross-validation process to reduce leakage risk.
Cadence and checkpoints
Evaluation is not finished when a notebook produces its first score. Track results at several checkpoints:
- During development: use cross-validation or a validation split to compare candidate models and features.
- Before selection: freeze the evaluation protocol, threshold policy, baseline, and primary metric.
- At final testing: run the chosen workflow once on a held-out test set, then preserve the configuration and results.
- Before release: review subgroup, temporal, and edge-case performance, not only the aggregate score.
- After deployment: monitor available outcomes, prediction distributions, threshold performance, and data quality on a monthly or quarterly cadence appropriate to the use case.
Maintain a simple evaluation log with the dataset version, feature pipeline, model version, threshold, sample size, class distribution, primary metric, secondary metrics, and notes about known limitations. This makes experiment comparisons more reliable and gives you a baseline for later monitoring. The article on Machine Learning Model Monitoring provides a useful companion workflow for post-release checks.
How to interpret changes
A metric change is a signal to investigate, not an explanation by itself. If accuracy rises while recall falls, the decision threshold or class distribution may have changed. If RMSE rises while MAE stays fairly stable, a small number of large errors may be driving the difference. If PR-AUC falls but ROC-AUC is stable, performance may have weakened specifically for the rare positive class.
Use this diagnostic sequence:
- Confirm that the same data definition, split strategy, and metric implementation were used.
- Compare the class or target distribution with the previous evaluation period.
- Inspect the confusion matrix, residual distribution, or top-ranked examples.
- Break results down by time, geography, category, customer segment, or another relevant group.
- Check whether a threshold, feature pipeline, label process, or upstream data source changed.
- Decide whether the change is sampling noise, a meaningful behavior shift, or an implementation problem.
Imbalanced data deserves particular care. A majority-class baseline can achieve high accuracy without finding useful positive cases. Prefer a metric aligned with the positive-class objective, report prevalence, and state the threshold used. Resampling or class weighting may change the precision-recall trade-off, so evaluate the final decision process rather than assuming that a training adjustment improved the real outcome.
When to revisit
Revisit metric selection whenever the model's purpose, data, or operating conditions change. A quarterly review is a reasonable starting point for a stable educational or internal project, while a faster cadence may be appropriate when labels arrive quickly, the environment changes often, or errors have significant consequences. Recheck sooner after a feature change, retraining run, threshold adjustment, data-source migration, product redesign, or unexpected monitoring alert.
Use this practical review checklist:
- Write down the current business or learning objective in one sentence.
- Confirm the primary metric still represents that objective.
- Record secondary metrics that expose trade-offs, including confusion-matrix counts or residual summaries.
- Compare against the last approved model and a simple baseline.
- Review subgroup and edge-case errors before accepting an aggregate improvement.
- Update the evaluation log, code comments, and model documentation.
- Set the next review date and define the change that would trigger an earlier investigation.
For a hands-on learning project, keep the workflow reproducible: save the test split or split rule, pin or record library versions, preserve prediction outputs, and include a short error-analysis note in the project repository. If you are building the surrounding pipeline, connect this work with a broader production machine learning workflow. Metrics are most useful when they remain tied to the decision, documented across experiments, and checked again as the model and its data evolve.