How to Evaluate Machine Learning Models (Easy Guide)
A model that scores 99% on your laptop and fails in production is worse than useless. Knowing how to evaluate machine learning models properly means choosing the right metric, testing on data the model has never seen, and avoiding data leakage. This guide covers classification and regression metrics, cross-validation, regularisation and the pitfalls that quietly inflate results.
Classification metrics
Everything starts with the confusion matrix, which counts correct and incorrect predictions for each class.

- Accuracy: share of all predictions that are correct. Misleading when one class is rare.
- Precision: of the items predicted positive, how many really are. Matters when false alarms are costly, such as flagging genuine payments as fraud.
- Recall: of the real positives, how many the model found. Matters when misses are costly, such as missing a disease.
- F1 score: the harmonic mean of precision and recall, useful when you need a balance.
- ROC-AUC: how well the model ranks positives above negatives across all thresholds.
Regression metrics
| Metric | What it tells you |
|---|---|
| MAE (mean absolute error) | Average size of the error, in the target’s units. Easy to explain. |
| MSE (mean squared error) | Average squared error. Punishes large errors more. |
| RMSE | Square root of MSE, back in the target’s units. |
| R² (coefficient of determination) | Share of the variance in the target that the model explains. 1 is perfect; 0 is no better than predicting the mean. |
Always plot predicted vs actual values and the residuals. A good R² can hide systematic errors on specific ranges of the target.
Train, validation and test sets
Split your data into three parts with three different jobs:
- Training set: the model learns from it.
- Validation set: you use it to compare models and tune hyperparameters.
- Test set: you use it once, at the end, to estimate real-world performance.
Looking at test results while you are still tuning is called data snooping. Every peek leaks a little information about the test set into your decisions, and the final score becomes optimistic.
Cross-validation
K-fold cross-validation makes better use of limited data. The training data is split into k folds; the model is trained k times, each time validated on a different fold, and the scores are averaged.

- Stratified k-fold keeps the class proportions the same in every fold, which is important for imbalanced classification.
- Time-series split always validates on data that comes after the training data, never before.
- Grid search and randomised search combine cross-validation with hyperparameter tuning.
Regularisation: fighting overfitting
Regularisation adds a penalty for large model weights, pushing the model towards simpler solutions that generalise better.
- Ridge (L2) shrinks all coefficients smoothly. Good when many features each matter a little, and when features are correlated.
- Lasso (L1) can shrink some coefficients to exactly zero, which doubles as feature selection.
- Elastic Net mixes both.
The strength of the penalty (alpha in scikit-learn’s Ridge and Lasso, C in LogisticRegression, where smaller means stronger) is a hyperparameter to tune with cross-validation.
Data leakage and other pitfalls
Data leakage happens when training data contains information the model will not have in real use. Results look excellent in testing and collapse after deployment. Common causes:
- Fitting a scaler, imputer or feature selector on the whole dataset before splitting.
- Features calculated from the target or from future data, such as an average price computed over the entire dataset.
- Random splits on time-series data, so the model “sees the future”.
- Duplicate or near-duplicate records appearing in both training and test sets.
Other traps: reading feature importance as cause and effect, ignoring class imbalance, and trusting a single lucky split.
The leak-proof way to do it in scikit-learn
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold
from sklearn.metrics import classification_report
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
pipe = Pipeline([("scale", StandardScaler()), ("model", LogisticRegression(max_iter=1000))])
search = GridSearchCV(pipe, {"model__C": [0.01, 0.1, 1, 10]},
cv=StratifiedKFold(5, shuffle=True, random_state=42), scoring="f1")
search.fit(X_train, y_train) # scaling is re-fitted inside each fold: no leakage
print(search.best_params_)
print(classification_report(y_test, search.predict(X_test))) # test set used once
The scikit-learn model evaluation guide lists every metric and scorer you can use.
Checklist: how to evaluate machine learning models step by step
- Write down the business goal and the cost of each type of error before you pick a metric.
- Split off a test set first, stratified for classification or time-ordered for time series, and leave it untouched.
- Build a simple baseline, such as predicting the most common class or the mean, so every score has a reference point.
- Put all preprocessing inside a
Pipelineso it is re-fitted within each cross-validation fold. - Compare models with k-fold cross-validation and report both the mean and the spread of the scores.
- Tune hyperparameters, including regularisation strength, with grid or randomised search.
- Check the confusion matrix or residual plots, not just one headline number.
- Evaluate once on the test set and record the result.
- After deployment, keep monitoring, because data drift slowly degrades every model.
Follow this checklist and you will know how to evaluate machine learning models in a way that holds up in production, not just in a notebook.
Master model evaluation with real projects
Module 5 of IBM’s Machine Learning with Python covers metrics, cross-validation, regularisation, pipelines with GridSearchCV and data leakage. Read our review or view the course on Coursera.
FAQ
Which metric should I use for an imbalanced dataset?
Avoid accuracy alone. Use precision, recall, F1 or the precision–recall curve, and decide which error type is more costly for your problem.
How many folds should I use in cross-validation?
Five or ten folds are common defaults. Use fewer for very large datasets or slow models, and stratified folds for classification.
What is the difference between overfitting and data leakage?
Overfitting means the model memorises training noise and does worse on new data, which honest validation reveals. Leakage makes the validation itself dishonest, so you do not notice the problem until production.
Back to the start of the series: Machine Learning with Python: The Complete Guide.