Model Evaluation & Generalisation
Learn how to test a model fairly, choose the right score for the task, spot underfitting and overfitting, and check whether a model is likely to work on data it has never seen before.
The big idea
A model is useful when it works beyond the examples used to train it.
Think of a student preparing for an exam. If they only memorise the practice questions, they may struggle when the exam asks something new. A machine learning model can make the same mistake.
What this page covers
Choose a section from the left menu.
- Train, validation and test data
- Regression and classification scores
- Clustering and dimensionality reduction checks
- Anomaly detection and reinforcement learning evaluation
- Underfitting, good fit and overfitting
- Cross-validation, learning curves and practical fixes
Underfitting
The model is too simple or has not learned enough. It performs poorly even on training examples.
Good generalisation
The model learns useful patterns and performs similarly on training and unseen data.
Overfitting
The model learns training examples too closely, including noise and accidental details.
Data leakage
Information from validation or test data accidentally enters training. This can make a model look better than it really is.
1. What does generalisation really mean?
Training performance is not the same as performance in the real world.
Memorising versus learning
A model can memorise examples, much like remembering the answers to a practice paper. Learning means finding a pattern that also helps with different examples.
Generalisation gap
The gap is the difference between how well a model does on training data and how well it does on unseen validation data.
For error measures, a large positive gap can be a warning sign. For scores where higher is better, compare the direction carefully: training score minus validation score.
Important terms
| Term | Simple meaning | What it is used for |
|---|---|---|
| Training error | How wrong the model is on data it learned from | Checks how well it learned the training examples |
| Validation error | How wrong it is on data used during model selection | Compare settings and choose a model |
| Test error | How wrong it is on a final held-aside set | Estimate final performance once |
| Generalisation | How well it handles new examples | Judge real-world usefulness |
| Data leakage | Test/validation information slips into training | Avoid unfairly high results |
2. Training, validation and test data
Use separate data for learning, choosing and final checking.
How a dataset is split
The slider below changes the size of each part. The percentages are teaching examples, not fixed rules.
What each set does
The model uses these examples to learn its parameters.
You use this to compare models, tune settings and decide when to stop training.
Keep this aside. Use it at the end to estimate how the chosen model performs on unseen data.
When a simple random split is useful
For many independent examples, shuffle and split the rows. Use a fixed random seed when you want repeatable results.
When random splitting can be wrong
For time series, do not train on future rows and test on earlier rows. Split by time. For people, patients, devices or repeated customers, consider group-based splitting so related records do not leak across sets.
3. Supervised learning: choose the right score
Regression predicts numbers. Classification predicts categories or class probabilities.
Regression metrics
- MAE: average size of the errors. Easy to explain in the target's units.
- MSE: average squared error. Large mistakes receive a much bigger penalty.
- RMSE: square root of MSE. Returns to the target's units.
- R²: compares the model with predicting the average. It can be negative on test data.
- MAPE: average percentage error; unsafe when actual values are zero or close to zero.
For MAE, MSE, RMSE and MAPE, lower values usually mean smaller prediction errors. For R², higher is generally better. An R² below zero means the model performed worse than simply predicting the average target value on that dataset.
Choose based on the mistakeUse MAE when you want an easy-to-explain average error. Use RMSE when large errors should count more. Be careful with percentage error when actual values can be zero or close to zero.
Classification metrics
- Accuracy: share of all predictions that are correct.
- Precision: of predicted positives, how many were truly positive?
- Recall: of actual positives, how many did we find?
- F1: balances precision and recall.
- ROC-AUC / PR-AUC: compare ranking quality across thresholds. PR-AUC is often useful when positives are rare.
Accuracy can hide poor results when one class is much more common than another. Precision matters when false alarms are costly. Recall matters when missing a real positive is costly. F1 balances precision and recall.
Remember the thresholdROC-AUC and PR-AUC look at ranking across different thresholds. The detailed classification lab below lets you move the threshold and see how the confusion matrix and scores change.
4. Interactive regression evaluation lab
Change the model's predictions and see how common regression scores respond.
Actual values and predictions
Move the prediction-bias and noise controls.
How to interpret these scores
| Metric | Better direction | What it tells you | Watch out for |
|---|---|---|---|
| MAE | Lower | Typical absolute miss | Does not heavily punish very large errors |
| MSE | Lower | Squared error size | Units are squared |
| RMSE | Lower | Penalises large errors, in original units | Can be pulled by outliers |
| R² | Usually higher | Improvement over predicting the mean | Not a percentage of predictions that are correct |
| MAPE | Lower | Average relative error | Problematic near zero; can over-weight small actual values |
5. Interactive classification evaluation lab
Explore thresholds, confusion matrices and the balance between false alarms and missed cases.
Choose a probability threshold
A model predicts a positive class when its probability is at least the selected threshold.
Confusion matrix
When accuracy can fool you
Imagine 990 normal transactions and 10 fraudulent ones. A model that always says “normal” gets 99% accuracy but catches zero fraud. Accuracy alone hides the failure. Check recall, precision, F1, PR-AUC and the confusion matrix for rare classes.
6. Unsupervised learning: evaluation without answer labels
There may be no correct answer column. Use measures that match the goal, and inspect the result.
Clustering evaluation
- Silhouette score: compares how close a point is to its own cluster versus other clusters. Range −1 to +1; higher is generally better.
- Davies–Bouldin index: compares within-cluster spread with distance between clusters. Lower is generally better.
- Calinski–Harabasz score: compares between-cluster separation with within-cluster spread. Higher is generally better.
- Inertia / within-cluster sum of squares: measures compactness in K-Means; it always tends to decrease as K grows, so use an elbow or other evidence.
Adjusted Rand Index (ARI), Normalised Mutual Information (NMI) and purity compare clusters with known labels. They are not available when true labels do not exist. A cluster score alone cannot tell you whether the groups are useful to the business.
These values are a teaching illustration showing that adding clusters does not automatically improve the result. They are not calculated from a fitted clustering model.
Dimensionality reduction evaluation
- Explained variance ratio: how much variation each principal component keeps.
- Cumulative explained variance: how much is kept by the first several components.
- Reconstruction error: how different the reconstructed data is from the original.
- Downstream task performance: does a model still work well after reducing dimensions?
Association rule evaluation
- Support: how often the item combination appears.
- Confidence: how often B appears when A appears.
- Lift: how much more often A and B occur together than expected if independent. Lift above 1 suggests a positive association.
- Leverage / conviction: other ways to compare co-occurrence and rule strength.
7. Anomaly detection: when rare events matter
There may be very few confirmed examples of an anomaly, or no labels at all.
Useful evaluation ideas
- Precision at a review budget: among the top 100 alerts, how many were real issues?
- Recall: how many known anomalies did the system find?
- PR-AUC: useful when anomalies are rare and labels are available.
- False alarms per day: important when people must investigate alerts.
- Detection delay: how long does it take to find an event?
- Operational cost: time, money and harm caused by missed or false alerts.
Why accuracy is usually weak here
If only 1 in 1,000 events is unusual, a system that always says “normal” can still be 99.9% accurate. Yet it detects none of the unusual events.
8. Reinforcement learning: evaluate behaviour over time
An agent learns by taking actions and receiving rewards from an environment.
What should we measure?
- Average episode return: total reward collected in one run, averaged over many runs.
- Success rate: how often the agent completes the task.
- Episode length: how many steps it needs.
- Constraint violations: unsafe or forbidden actions.
- Stability: does performance vary greatly across random seeds?
- Generalisation: can it handle new starting positions, maps, opponents or conditions?
Training environment versus new environment
A game-playing agent might learn a training level very well but fail when the layout changes. Test it on different seeds, scenarios and difficulty levels.
9. Model complexity: underfitting, good fit and overfitting
Explore how a model can become too simple or too flexible.
Model fit on training and test examples
Bias–variance trade-off
The model makes assumptions that are too simple. It misses important patterns. Often linked with underfitting.
The model changes too much when the training sample changes. It may learn noise. Often linked with overfitting.
The aim is not to make the model as complex as possible. It is to find a level of complexity that captures useful patterns and still works on unseen data.
10. Validation strategies: choose the right experiment
Not every dataset should be split in the same way.
Hold-out validation
Split once into training, validation and test sets. It is simple and fast, but the result can depend on the random split.
K-fold cross-validation
Split data into K parts. Train K times, each time validating on a different part. Average the results. Useful when data is limited.
Stratified K-fold
Keeps roughly similar class proportions in each fold. Often helpful for imbalanced classification.
Time-series split
Train on earlier time periods and validate on later periods. Never shuffle future information into the past.
Group K-fold
Keeps all records from the same group together. Helps prevent the model from seeing the same person or device in both training and validation.
Nested cross-validation
Uses an inner loop to tune settings and an outer loop to estimate performance. Helps reduce optimistic estimates when many settings are compared.
11. Diagnostics: what to do when results look wrong
Use the pattern of training and validation results to decide what to try next.
| What you observe | Possible reason | What to try |
|---|---|---|
| Training and validation both poor | Underfitting, weak features, poor data quality | Use a more suitable model, add useful features, train longer where appropriate, reduce excessive regularisation |
| Training strong, validation poor | Overfitting, leakage, train/test distribution difference | Reduce complexity, regularise, collect more varied data, use cross-validation, check leakage |
| Validation changes a lot across splits | Small dataset or unstable sample | Use repeated or K-fold validation; report variation |
| High accuracy but poor positive detection | Class imbalance or unsuitable threshold | Inspect confusion matrix, recall, precision, F1 and PR-AUC; tune threshold |
| Great test score that seems unrealistic | Data leakage or duplicate/related records across splits | Audit features, timestamps, preprocessing and group splitting |
| Good offline score, poor live results | Distribution shift, changing user behaviour, pipeline mismatch | Monitor data and performance, retrain carefully, test realistic future data |
Ways to reduce overfitting
- Collect more representative training data.
- Use a simpler model or fewer features.
- Use regularisation (L1/L2), pruning or dropout where appropriate.
- Use early stopping based on validation performance.
- Use data augmentation when it makes sense for the task.
- Use cross-validation for model selection.
Ways to address underfitting
- Try a more flexible model.
- Add useful features or interactions.
- Reduce overly strong regularisation.
- Train longer if the model has not converged.
- Check whether the inputs contain enough information.
- Review labels and data quality.
12. A reliable evaluation workflow
Follow these steps before trusting a machine learning result.
- Define the real goal. What decision will the model support? What mistakes are costly?
- Choose the right metric. Match it to regression, classification, clustering, anomaly detection or reward-based learning.
- Understand the data. Check missing values, duplicates, labels, time order, groups and class balance.
- Split the data safely. Avoid leakage and match the split to the way the model will be used.
- Build a simple baseline. Compare against a sensible easy rule, such as predicting the mean or majority class.
- Train and tune. Use training data to learn and validation data or cross-validation to select.
- Inspect errors. Look at residuals, confusion matrices, class-wise scores and failure examples.
- Evaluate once on the test set. Do this after choices are complete.
- Monitor after launch. Real-world data can change over time.
- Dataset and time period
- How train/validation/test were split
- Metric definitions
- Baseline result
- Average and variation across folds/seeds when useful
- Important limits and known failure cases
- Whether the test set was used during tuning
13. Python examples with scikit-learn
Common evaluation patterns you can adapt in a notebook.
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.linear_model import LinearRegression
import numpy as np
# X: input features; y: numerical target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
mae = mean_absolute_error(y_test, predictions)
mse = mean_squared_error(y_test, predictions)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, predictions)
print("MAE:", mae)
print("RMSE:", rmse)
print("R2:", r2)from sklearn.model_selection import train_test_split
from sklearn.metrics import (confusion_matrix, classification_report,
precision_score, recall_score, f1_score)
from sklearn.ensemble import RandomForestClassifier
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred))
print("Precision:", precision_score(y_test, pred))
print("Recall:", recall_score(y_test, pred))
print("F1:", f1_score(y_test, pred))from sklearn.model_selection import cross_validate, StratifiedKFold
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state=42)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_validate(
model, X, y, cv=cv,
scoring=["accuracy", "precision", "recall", "f1"]
)
for metric in ["test_accuracy", "test_precision", "test_recall", "test_f1"]:
values = scores[metric]
print(metric, values.mean(), "+/-", values.std())from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, davies_bouldin_score
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
model = KMeans(n_clusters=3, random_state=42, n_init=10)
labels = model.fit_predict(X_scaled)
print("Silhouette:", silhouette_score(X_scaled, labels))
print("Davies-Bouldin:", davies_bouldin_score(X_scaled, labels))
print("Inertia:", model.inertia_)Fit preprocessing steps only on training data. In a real workflow, put scaling, imputation and feature selection inside a scikit-learn Pipeline so cross-validation does not leak information.
14. Knowledge check
Answer one question at a time. The result and explanations appear after submission.