Skip to content
London, United Kingdom · Est. 1994
English

Unit 4: Evaluating and Selecting Models

How to measure model performance with the right metrics, how to detect and prevent overfitting using sound validation, and how to choose, tune and check models for fairness and robustness before relying on them.

Unit 4 of 5 · about 54 minutes

4.1 Measuring performance: choosing the right metrics

A model is only useful if we can tell how well it works, and "how well" depends on the purpose. Choosing evaluation measures, called metrics, is therefore a business decision as much as a technical one. The wrong metric can make a poor model look excellent or lead a team to optimise for something that does not matter.

Metrics for regression

  • Mean absolute error (MAE) is the average size of the errors, ignoring whether they are too high or too low. It is easy to explain: "on average, our delivery-time predictions are out by 12 minutes".
  • Root mean squared error (RMSE) squares errors before averaging and then takes the square root. It penalises large errors more heavily, which suits situations where big mistakes are especially costly.
  • Mean absolute percentage error (MAPE) expresses errors as percentages, which helps when comparing across items of very different sizes, but behaves badly when actual values are close to zero.
  • R-squared describes the proportion of variation in the label that the model explains. It is widely reported but can be misleading on its own.

The confusion matrix

For classification, the starting point is the confusion matrix, which counts the four possible outcomes of a binary prediction:

PredictionActually positiveActually negative
Predicted positiveTrue positive (correctly flagged)False positive (false alarm)
Predicted negativeFalse negative (missed case)True negative (correctly cleared)

In fraud detection, a false positive inconveniences a genuine customer; a false negative lets fraud through. In medical screening support, a false negative may delay treatment. The costs differ by context, and metrics should reflect them.

Metrics for classification

  • Accuracy is the proportion of all predictions that are correct. It is intuitive but misleading when classes are imbalanced.
  • Precision answers: of the cases we flagged, how many were truly positive? High precision means few false alarms.
  • Recall, also called sensitivity, answers: of all the truly positive cases, how many did we catch? High recall means few missed cases.
  • F1 score combines precision and recall into a single number, useful when both matter.
  • Specificity is the proportion of truly negative cases correctly cleared.

Precision and recall usually trade off against each other through the decision threshold. Lowering the threshold flags more cases, increasing recall but usually reducing precision.

Threshold-independent measures

The ROC curve plots the rate of true positives against false positives across all thresholds, and the area under the curve (AUC) summarises it in a single number between 0.5, no better than chance, and 1, perfect separation. AUC is useful for comparing models' ability to rank cases. For heavily imbalanced problems, the precision-recall curve is often more informative.

Tip: Translate metrics into business terms. "This model catches 80 out of every 100 fraudulent transactions, and one in five transactions it flags is genuinely fraudulent" is far more useful to decision-makers than "F1 of 0.8".

Comparing with a baseline

Every metric needs context. Compare the model with a simple baseline, such as always predicting the most common class, using last year's value or applying an existing business rule. A model with 92 per cent accuracy sounds impressive until you discover that the baseline achieves 90 per cent. Equally, compare against current human performance where relevant, recognising that people and models may make different kinds of mistakes.

Business metrics

Ultimately, models exist to improve outcomes such as revenue, cost, customer satisfaction, safety or staff time. Where possible, link model metrics to these outcomes, for example by estimating the cost of false positives and false negatives and choosing the threshold that minimises total cost. After deployment, controlled experiments, such as comparing a group using the model with a group that is not, provide the strongest evidence of real benefit.

In practice

Before any modelling begins, agree with stakeholders which errors matter most, which metric will be used to compare models, what baseline must be beaten and what level of performance would justify deployment. Writing this down in advance prevents teams from choosing whichever metric makes their results look best after the fact.

4.2 Overfitting, underfitting and validation

The central goal of machine learning is generalisation: performing well on new data, not just on the examples used for training. Two opposite failures threaten this goal, and understanding them is essential for building and judging models.

Underfitting and overfitting

  • Underfitting happens when a model is too simple to capture the real patterns in the data. It performs poorly on both training and test data. A straight line fitted to a strongly curved relationship underfits.
  • Overfitting happens when a model learns the training data too closely, including its random noise and quirks. It performs very well on training data but noticeably worse on new data. A very deep decision tree that creates a separate rule for almost every training example overfits.

An analogy is preparing for an exam. A student who learns only a few general ideas underfits and struggles with most questions. A student who memorises past papers word for word overfits: perfect on familiar questions, lost on new ones. The aim is to understand the underlying principles.

The bias-variance trade-off

These failures are often described in terms of bias and variance. Bias is error from overly simple assumptions, causing underfitting. Variance is error from excessive sensitivity to the particular training data, causing overfitting. Increasing model complexity usually reduces bias but increases variance. Good modelling finds a balance that minimises error on unseen data.

Diagnosing the problem

  • Poor on training data and poor on validation data: underfitting, because the model is too simple or the features are uninformative.
  • Very good on training data but much worse on validation data: overfitting, because the model is too complex or there is too little data.
  • Good on both, with similar results: a reasonable fit.
  • Validation results that seem too good to be true: possible data leakage or a flawed split.

Remedies

For underfitting: add more informative features, use a more flexible model, or reduce excessive regularisation. For overfitting: gather more training data, simplify the model, remove noisy or irrelevant features, apply regularisation, limit tree depth, use ensembles, or stop training a neural network before it begins to memorise, a technique called early stopping.

Cross-validation

A single split into training and validation data can be unlucky, especially with smaller datasets. k-fold cross-validation gives a more reliable estimate:

  1. Divide the training data into k equal parts, or folds, commonly five or ten.
  2. Train the model on all folds except one and evaluate it on the fold left out.
  3. Repeat so that each fold is used once for evaluation.
  4. Average the results, and look at how much they vary between folds.

Large variation between folds is itself a warning that performance is unstable. Variants of cross-validation preserve the proportion of rare classes in each fold, keep all records for the same person together, or respect time order for forecasting problems, where models must always be validated on periods after those used for training.

Remember: Cross-validation is for developing and choosing models. A separate test set, untouched until the end, is still needed for an honest final estimate.

Learning curves

A learning curve plots performance on training and validation data as the amount of training data increases. If the two lines converge at a poor level, the model is underfitting and more data will not help much; better features or a more flexible model are needed. If a large gap remains, the model is overfitting and more data is likely to help. Learning curves help decide whether to invest in collecting more data.

Common mistakes

  • Reporting performance on training data as if it reflected real-world performance.
  • Preparing data, such as scaling or selecting features, using the full dataset before splitting, which leaks information.
  • Trying hundreds of model variations and reporting only the best result, which overfits to the validation data.
  • Using random cross-validation for time-based problems.

In practice

When a model's results are presented, ask to see performance on training, validation and test data side by side, and how much results varied across cross-validation folds. A large gap between training and test performance, or results that seem too good to be true, deserve careful questioning before anyone relies on the model.

4.3 Tuning, selecting and checking models responsibly

Once a team has candidate models and a sound validation approach, it must tune them, select one and check that it is fit for use. This final step goes beyond headline accuracy to include fairness, robustness and explainability, which are increasingly expected by customers, regulators and the public.

Parameters and hyperparameters

A model's parameters are learned from data during training, such as the weights in a regression. Hyperparameters are settings chosen before training that control how learning happens, such as the maximum depth of a decision tree, the number of trees in a forest, the strength of regularisation or the learning rate in gradient boosting. Choosing hyperparameters well can make a substantial difference.

Tuning methods

  • Grid search tries every combination from a set of candidate values. It is thorough but becomes slow as the number of hyperparameters grows.
  • Random search tries random combinations within ranges. It is often more efficient than grid search for the same computing time.
  • Bayesian optimisation and similar methods use the results of earlier trials to choose promising settings to try next.

Tuning should always be evaluated with cross-validation or a validation set, never the final test set.

Selecting a model

The model with the best validation score is not automatically the right choice. Consider:

  1. Size of the improvement: is the gain over a simpler model meaningful, or within the normal variation between folds?
  2. Interpretability: can the model's decisions be explained to those who need to understand them?
  3. Operational cost: how fast is it, what resources does it need and how easily can it be maintained?
  4. Robustness: how does it behave with unusual inputs, missing values or slightly changed data?
  5. Fairness: does it perform acceptably for all relevant groups?

Tip: When two models perform similarly, choose the simpler one. It will usually be easier to explain, cheaper to run and less likely to fail in unexpected ways.

Fairness

Models trained on historical data can reproduce or amplify past unfairness. A hiring model trained on past decisions may learn to disadvantage groups that were previously under-represented; a model may also perform worse for groups with less data. Even if protected characteristics such as sex or ethnicity are excluded, other features, such as postcode or career gaps, can act as proxies for them.

Fairness checks typically compare performance and outcomes across groups: are error rates, approval rates or precision substantially different? There are several mathematical definitions of fairness, and they cannot all be satisfied at once, so organisations must decide which matters most in context, often with legal and ethical advice. Many countries have equality and anti-discrimination laws that apply to automated decisions, and data protection laws such as the GDPR include provisions on significant decisions made solely by automated means.

Robustness and stress testing

A robust model performs reliably when conditions differ from the training data. Stress tests include evaluating performance on recent data, on specific subgroups and on edge cases; checking behaviour when inputs are missing or extreme; and considering whether someone could deliberately manipulate inputs to obtain a favourable prediction. Models used in security or fraud settings may face adversaries actively trying to evade them.

Explainability

Different audiences need different explanations. Data scientists want to understand overall behaviour, using feature importance and similar tools. Business owners want to know whether the model's logic is sensible. Individuals affected by a decision may need a clear explanation of the main reasons. Simpler models are inherently easier to explain, while complex models rely on post-hoc explanation methods, which are approximations and should be presented as such.

Documentation

Good practice is to document each model in a short model card or similar record, covering its purpose, intended users and uses, training data, features, evaluation results overall and for key groups, known limitations, fairness checks and the owner responsible. This record supports review, audit and future maintenance.

In practice

Before approving a model for use, ask for its model card and a short evaluation summary showing comparison with a baseline, results by relevant group, performance on recent data and known limitations. Insist on clarity about how decisions will be reviewed and how people can challenge outcomes that affect them.

Case study: Choosing a triage model at a home insurance provider

Northgate Home Insurance, a fictional insurer, wanted to route incoming claims either to a fast-track team or to detailed investigation. The data science team built three candidate models and compared them using five-fold cross-validation on two years of claims.

The most complex model achieved slightly higher overall performance, but the difference from a regularised logistic regression was within the normal variation between folds. Results by region showed the complex model sent claims from two rural areas to investigation far more often, without a corresponding rise in confirmed problems; investigation revealed that postcode-related features were acting as a proxy for property age and repair costs in ways the claims team considered unfair.

The team chose the logistic regression, removed the problematic features and set a threshold based on the estimated costs of delays and missed fraud. The final model was evaluated once on a held-back test set of recent claims. A model card recorded its limitations, and claims handlers could override any routing decision with a brief reason, which was reviewed monthly.

Activity

A classification model for detecting faulty products on a production line has been tested on 1,000 items, 50 of which were actually faulty. It flagged 60 items, of which 40 were truly faulty. Calculate its precision and recall, explain what each means in this context, and recommend whether to raise or lower the threshold if missed faults are very costly.

Compare with a model answer

Precision is 40 divided by 60, about 67 per cent: two in every three flagged items are genuinely faulty, and one in three is a false alarm that wastes an inspector's time. Recall is 40 divided by 50, which is 80 per cent: the model catches four out of five faulty items, so 10 faulty items were missed.

If missed faults are very costly, for example because faulty products reach customers or create safety risks, the team should lower the threshold. This will flag more items, increasing recall so that fewer faults are missed, at the cost of lower precision and more inspections. A strong answer suggests estimating the cost of each missed fault and each unnecessary inspection to choose the threshold, and confirming the new setting on validation data.

Key takeaways

  • Metrics must reflect the purpose: MAE and RMSE for regression; precision, recall, F1 and AUC for classification, especially with imbalanced classes.
  • Always compare models with a simple baseline and translate results into business terms.
  • Overfitting means learning noise in the training data; underfitting means missing real patterns; comparing training and validation results reveals which is occurring.
  • Cross-validation gives more reliable estimates during development, but a separate untouched test set is still needed for the final assessment.
  • Model selection should weigh accuracy against simplicity, interpretability, robustness and fairness, documented in a model card.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 3 Unit 5 →
WhatsApp