edSlash Labs  /  Machine Learning Lab  /  Model Evaluation & Generalisation
Shared machine learning foundation

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.

All learning families

The big idea

A model is useful when it works beyond the examples used to train it.

Learn on known data → Test on unseen data

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.

Generalisation means the model can use what it learned to make sensible predictions or decisions on new examples.

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.

Common clue: training score is poor and validation score is also poor.

Good generalisation

The model learns useful patterns and performs similarly on training and unseen data.

Common clue: training and validation results are both good and reasonably close.

Overfitting

The model learns training examples too closely, including noise and accidental details.

Common clue: training result is very good but validation/test result is much worse.

Data leakage

Information from validation or test data accidentally enters training. This can make a model look better than it really is.

Rule: keep the test set untouched until final evaluation.

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.

Example: A spam filter should recognise new spam messages, not only the exact messages it saw during training.
Another example: A house-price model should estimate prices for houses it has not seen, not simply repeat prices from its training table.

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.

Generalisation gap = validation error − training error

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

TermSimple meaningWhat it is used for
Training errorHow wrong the model is on data it learned fromChecks how well it learned the training examples
Validation errorHow wrong it is on data used during model selectionCompare settings and choose a model
Test errorHow wrong it is on a final held-aside setEstimate final performance once
GeneralisationHow well it handles new examplesJudge real-world usefulness
Data leakageTest/validation information slips into trainingAvoid 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.

Train 70%
Val 15%
Test 15%
70% trains the model, 15% helps choose settings, and 15% is saved for the final check.

What each set does

1. Training set
The model uses these examples to learn its parameters.
2. Validation set
You use this to compare models, tune settings and decide when to stop training.
3. Test set
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.
How to read regression scores

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 mistake

Use 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.

Do not choose a metric just because it is popular. Think about what a prediction error means in the real task.

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.
How to read classification scores

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 threshold

ROC-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.

Choose the score that matches the cost of a false alarm, a missed positive, or an incorrect category.

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.

Actual valuesPredicted values
MAE—Average absolute error
MSE—Average squared error
RMSE—Error in target units
R²—Compared with mean baseline

How to interpret these scores

MetricBetter directionWhat it tells youWatch out for
MAELowerTypical absolute missDoes not heavily punish very large errors
MSELowerSquared error sizeUnits are squared
RMSELowerPenalises large errors, in original unitsCan be pulled by outliers
R²Usually higherImprovement over predicting the meanNot a percentage of predictions that are correct
MAPELowerAverage relative errorProblematic 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.

True positives—
False positives—
True negatives—
False negatives—

Confusion matrix

True Positive
—
Predicted yes, actually yes
False Positive
—
False alarm
False Negative
—
Missed positive
True Negative
—
Predicted no, actually no
Accuracy—
Precision—
Recall—
F1 score—
Threshold trade-off: lowering the threshold usually catches more positives (higher recall) but can create more false alarms (lower precision). Raising it often does the opposite. The best threshold depends on the real cost of each mistake.

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.
External measures when labels exist
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.
Illustrative silhouette0.71
Davies–Bouldin0.48
Inertia—

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?
For PCA, keeping 95% variance is a common teaching rule, not a universal law. A lower number may be enough, or the task may need more.

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.
Association is not causation. A rule that says two products are often bought together does not prove one causes the other to be purchased.

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.

Evaluate the ranking of alerts and the number of alerts people can realistically review. If labels are missing, use expert review, synthetic tests and careful investigation of flagged examples.

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.

Do not judge an agent from one lucky run. Evaluate many episodes and report average performance plus variation.

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

Training examplesTest examplesModel curve
Training error—
Test error—

Bias–variance trade-off

High bias
The model makes assumptions that are too simple. It misses important patterns. Often linked with underfitting.
High variance
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.

Use a random split or shuffled K-fold when rows are independent and similarly distributed. Keep a final test set untouched.

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 observePossible reasonWhat to try
Training and validation both poorUnderfitting, weak features, poor data qualityUse a more suitable model, add useful features, train longer where appropriate, reduce excessive regularisation
Training strong, validation poorOverfitting, leakage, train/test distribution differenceReduce complexity, regularise, collect more varied data, use cross-validation, check leakage
Validation changes a lot across splitsSmall dataset or unstable sampleUse repeated or K-fold validation; report variation
High accuracy but poor positive detectionClass imbalance or unsuitable thresholdInspect confusion matrix, recall, precision, F1 and PR-AUC; tune threshold
Great test score that seems unrealisticData leakage or duplicate/related records across splitsAudit features, timestamps, preprocessing and group splitting
Good offline score, poor live resultsDistribution shift, changing user behaviour, pipeline mismatchMonitor 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.

  1. Define the real goal. What decision will the model support? What mistakes are costly?
  2. Choose the right metric. Match it to regression, classification, clustering, anomaly detection or reward-based learning.
  3. Understand the data. Check missing values, duplicates, labels, time order, groups and class balance.
  4. Split the data safely. Avoid leakage and match the split to the way the model will be used.
  5. Build a simple baseline. Compare against a sensible easy rule, such as predicting the mean or majority class.
  6. Train and tune. Use training data to learn and validation data or cross-validation to select.
  7. Inspect errors. Look at residuals, confusion matrices, class-wise scores and failure examples.
  8. Evaluate once on the test set. Do this after choices are complete.
  9. Monitor after launch. Real-world data can change over time.
Before you publish a score, report:
  • 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
A score without its test method is incomplete. Always explain how you measured it.

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.

Question 1 of 12