ML System Design · Module 16 of 47 · 12 concepts · about 16 min

Offline Evaluation

Measuring a model before any user sees it: the right measure for each kind of task, choosing a threshold from the cost of mistakes, evaluating over time with backtests, checking slices, and why a model that wins offline can still lose online.

At work: The daily feedback loop of model development and the evidence in every model review. Choosing the wrong measure is a quiet way to ship the wrong model.

What offline evaluation can and cannot tell you

What it is

Offline evaluation scores a model on held-out historical data. It can tell you:

  • whether the model predicts past outcomes better than the baseline and the champion;
  • where it is weak (which slices, which kinds of case);
  • whether it is fast and small enough.

It cannot tell you how users will react to its predictions; only an online experiment can (module 17).

Why it matters

Offline evaluation is fast and cheap, so it is where most decisions are made.

  • Minutes per run, no risk to users.
  • It filters out bad candidates before they cost anything.
  • But history only records reactions to the old model's choices, which limits what it can say about a new one.

In the real world: Kirana Kart requires an offline win to start an A/B test, and an A/B win to launch; about half of offline winners in recommendations fail to improve the online metric.

Treating an offline win as proof. Offline measures are a filter for what deserves an online test, not a verdict.

Precision, recall and the confusion matrix

What it is

For a yes/no decision at a threshold, every case lands in one of four cells:

  • true positive: flagged and really fraud;
  • false positive: flagged but honest;
  • false negative: not flagged but really fraud;
  • true negative: not flagged and honest.

Precision = true positives ÷ all flagged: how many flags were right. Recall = true positives ÷ all real frauds: how much fraud was caught.

Why it matters

The two answer the two questions the business asks.

  • Precision: how much reviewer time and customer annoyance are wasted?
  • Recall: how much fraud slips through?
  • Raising the threshold usually raises precision and lowers recall; the right balance depends on what each mistake costs.
  • F1 (their harmonic mean) is a single number when both matter equally, which is rarely exactly true in business.

In the real world: Kirana Kart's fraud dashboard shows precision and recall side by side at the live threshold, never one alone.

Reporting precision without recall, or the other way round. 'Ninety percent precision' is easy: flag only the five most obvious cases.

Practise it: Improve a Low-Recall Model

ROC-AUC and PR-AUC

What it is

Two summaries of a model across all thresholds:

  • ROC-AUC: the chance that a random positive is scored above a random negative. 0.5 is guessing; 1 is perfect.
  • PR-AUC (average precision): the area under the precision-recall curve. Its baseline is the positive rate (0.005 for 0.5% fraud), not 0.5.

Why it matters

For rare positives, PR-AUC is the more honest measure.

  • ROC-AUC counts true negatives, which are abundant, so a model can score 0.98 while most of its flags are wrong.
  • PR-AUC focuses on the positives and the flags, which is what matters for fraud, failures and ads.
  • Both measure ranking quality; neither says which threshold to use, and neither checks calibration.

In the real world: Fraud and anomaly teams typically report PR-AUC as the headline offline metric, plus precision and recall at the threshold actually used in production.

Celebrating a ROC-AUC of 0.97 on a problem with 0.1% positives. The precision at any useful recall may still be poor; look at PR-AUC and at precision at the operating point.

Choosing a threshold from costs

What it is

The best threshold minimises the total cost of mistakes:

  • put a price on each false positive (review time, an annoyed honest customer, a lost sale);
  • put a price on each false negative (the money lost to an uncaught fraud);
  • compute total cost = false positives × their cost + false negatives × their cost, at each threshold;
  • choose the lowest, then check it against limits such as how many cases reviewers can handle.

Why it matters

It turns an argument into arithmetic.

  • Product wants fewer annoyed customers; risk wants less fraud; both agree on prices, and the threshold follows.
  • When prices change (a costlier fraud wave), the threshold can be recomputed without retraining.

In the real world: Payment companies commonly set fraud thresholds from expected loss against the cost of a false decline, and revisit them when fraud patterns or review capacity change.

Visual example

Computed

100,000 payments, 500 frauds. A false alarm costs ₹50; a missed fraud ₹2,000. The cheapest threshold is 0.3.

Illustrative counts at each threshold
thresholdfrauds caughthonest flaggedprecisionrecallcost of mistakes
0.91505075%30%₹7 lakh
0.728030048%56%₹4.6 lakh
0.536090029%72%₹3.3 lakh
0.34202,50014%84%₹2.9 lakh
0.14709,0005%94%₹5.1 lakh

At 0.3

fp: 2,500 false alarms × ₹50 = ₹1.3 lakh

fn: 80 missed frauds × ₹2,000 = ₹1.6 lakh

sum: total = ₹2.9 lakh

Ignoring capacity. The cheapest threshold here flags about 2,900 of every 100,000 payments; if reviewers can only handle 1,000, the decision needs a second, automatic tier or a higher threshold.

Measures for numbers

What it is

For predicted numbers (minutes, rupees):

  • MAE (mean absolute error): the average size of a miss, in the same units. Easy to explain.
  • RMSE (root mean squared error): punishes large misses much more. Use when big misses are much worse.
  • Percentiles of error: the 90th or 99th percentile miss shows the tail that customers remember.
  • Asymmetric measures: count late and early misses differently, or report the share of orders more than 5 minutes late.

Why it matters

The average hides what customers feel.

  • One delivery 12 minutes late generates a complaint; nine within a couple of minutes generate nothing.
  • RMSE and tail percentiles expose those large misses.
  • Pick the measure that matches the business harm, and report the tail beside the average.

In the real world: Food and grocery delivery apps typically track both average error and the share of orders arriving later than the promised time, since lateness drives complaints.

Visual example

Computed

Ten deliveries, error = actual − promised minutes. One 12-minute miss barely moves MAE but dominates RMSE.

Errors: -2, 1, 3, -1, 0, 4, -3, 2, 12, -1
measurevaluereads as
MAE2.9 minAverage miss
RMSE4.35 minPulled up by the big miss
Late by over 5 min1 of 10What customers complain about

Optimising MAE when the product promise is 'arrives by the time shown'. A model can lower MAE by predicting the middle, while being late on almost half of orders.

Measures for ranking

What it is

For an ordered list, measure whether the good items are near the top:

  • Precision at k: share of the top k that are relevant.
  • Recall at k: share of all relevant items that are in the top k.
  • MRR (mean reciprocal rank): 1 ÷ the position of the first relevant item, averaged. Good when one right answer is enough.
  • NDCG at k: rewards relevant items more the higher they are, supports graded relevance (bought > added > clicked), and is scaled so 1 is the best possible order.

Why it matters

Position matters: an item at position 1 is seen by nearly everyone, at position 10 by few.

  • NDCG captures both position and degrees of relevance, which is why it is the standard ranking measure.
  • Recall at k suits retrieval; NDCG and MRR suit the final list.

In the real world: Kirana Kart's search team reports NDCG at 10 with grades 3 for bought, 2 for added, 1 for clicked and 0 for shown only.

Visual example

Computed

One search's top five, graded 3, 0, 2, 1, 0. NDCG at 5 = 0.951: good, but the second slot was wasted.

Gain = 2^grade − 1, discounted by log2(position + 1)
positiongradegaindiscountcontribution
13717
2000.6310
3230.51.5
4110.4310.431
5000.3870

NDCG

dcg: DCG = 8.931

idcg: best possible order 3, 2, 1, 0, 0 gives 9.393

ndcg: NDCG = 8.931 / 9.393 = 0.951

Computing NDCG only over clicked items. The list must include the items shown and ignored, or every list looks perfect.

Practise it: Design a Recommendation System, Design a Personalized News Feed

Measures for forecasts

What it is

Forecasts are judged over many items and days:

  • WAPE (weighted absolute percentage error): total absolute error ÷ total actual. Robust and easy to explain.
  • MASE: error relative to a naive forecast (such as 'same as last week'). Below 1 beats naive.
  • Pinball (quantile) loss: for forecasts of a percentile, such as the 90th, used to set stock levels.
  • Bias: whether forecasts are too high or too low on average.

Why it matters

Percentage error per item (MAPE) breaks on small or zero values, which are common for slow-selling items.

  • WAPE weights by volume, so a big miss on a best-seller counts more than on a niche item.
  • Bias matters on its own: steady over-forecasting wastes stock even if the error is small.

In the real world: Retail forecasting teams commonly report WAPE and bias by category and store, and pinball loss for the percentile forecasts that drive orders.

Visual example

Computed

Five store-days. WAPE = 18.3%; percentage error is undefined on the day that sold nothing.

Units of one product
actualforecastabsolute errorpercentage error
1201002017%
80901013%
01010÷ 0
4035513%
60701017%

WAPE

w: 55 total error ÷ 300 total sold = 18.3%

bias: bias: forecast 305 vs actual 300, slightly high

Using MAPE when some actuals are zero. One store-day that sold nothing makes the average percentage error infinite.

Backtesting

What it is

Backtesting (rolling-origin evaluation) repeats a time split several times:

  • train on data up to cut-off 1, test on the period after;
  • move the cut-off forward, retrain, test again;
  • repeat over many cut-offs and average, or look at the spread.

Why it matters

One time split can be lucky or unlucky.

  • A model tested only on a quiet week looks better than it is.
  • Backtesting over months, including holidays and promotions, shows how the model really behaves and how variable it is.
  • It also mimics retraining exactly as production will do it.

In the real world: Kirana Kart backtests demand models over the last 26 weeks, retraining at each weekly cut-off, and reports error separately for festival weeks.

Visual example

Backtest

Each round trains on everything before its cut-off.

Rolling-origin evaluation

  1. three rounds, each retrained
    Round 1Train to week 40 → test week 41
    Round 2Train to week 41 → test week 42
    Round 3Train to week 42 → test week 43
  2. SummariseAverage, spread, worst week

Tuning settings on all the backtest periods and then reporting the same periods as the result. Keep the last periods untouched for the final number.

Practise it: Design a Demand Forecasting Platform

Why offline and online disagree

What it is

A model that wins offline can lose online. Common reasons:

  • the data records the old model's choices: you only see reactions to items the old model showed, so a new model's different picks cannot be judged fairly;
  • the measure is a proxy: NDCG on clicks is not revenue;
  • skew: live features differ from training features (module 11);
  • users react: novelty, learning, changed behaviour;
  • latency: a slower model costs engagement that offline scores ignore.

Why it matters

Knowing the reasons tells you which checks to add.

  • Counterfactual methods (re-weighting logged data by how likely each item was to be shown) reduce the first problem.
  • Replay tests catch skew before launch.
  • Only an online experiment settles the rest.

In the real world: Netflix and others have written that offline metrics are used to choose which ideas to test online, and that the correlation between the two must itself be monitored.

Visual example

Gap

Several can apply at once.

Reasons offline and online results differ, and the check for each
reasoncheck
Logged data reflects the old modelCounterfactual re-weighting; small exploration traffic
Proxy measureTrack offline-vs-online agreement over many launches
Training-serving skewReplay test before launch
User reaction and noveltyRun experiments long enough; watch the trend
LatencyMeasure p99 in the experiment; include it in guardrails

Responding to an online loss by tuning the offline score harder. If the offline measure does not track the online one, better offline numbers will not help; fix the measure.

Practise it: Design an ML Feature Store, Design Continuous ML Deployment

Evaluation code people get wrong

What it is

A few rules that prevent most evaluation mistakes:

  • compute every measure on a later period than training;
  • keep a test set untouched until the final decision;
  • evaluate per slice as well as overall;
  • report uncertainty: a confidence interval from bootstrap resampling;
  • compare with the baseline and the champion on the same rows.

Why it matters

Small evaluation mistakes cause large wrong decisions.

  • A difference of 0.3% may be noise; the interval says whether it is.
  • Comparing on different rows makes any model look better or worse at random.

In the real world: Kirana Kart's model-review template requires a bootstrap interval for every headline difference; a gain whose interval includes zero is reported as 'no measurable difference'.

import numpy as np

def bootstrap_diff(y, p_new, p_old, metric, n=1000, seed=0):
    """Confidence interval for metric(new) - metric(old) on the same rows."""
    rng = np.random.default_rng(seed)
    diffs = []
    for _ in range(n):
        idx = rng.integers(0, len(y), len(y))
        diffs.append(metric(y[idx], p_new[idx]) - metric(y[idx], p_old[idx]))
    return np.percentile(diffs, [2.5, 97.5])   # if both ends are above 0, the gain is real

Declaring a winner from one number with no interval. On small slices, differences of several percent are often noise.

Interview questions: offline evaluation

What it is

The questions interviewers ask about offline evaluation, from the first screening call to the senior round. Cover the answer, say yours aloud, then compare.

Why it matters

Reading an idea and explaining it are different skills.

  • Each answer below is the two or three sentences an interviewer is listening for.
  • The reasoning behind each one is in the cards above. If an answer surprises you, go back to that card.

In the real world: Interviewers nearly always ask 'how would you evaluate it offline?' then 'and online?'. Naming a measure that fits the task, with a reason, is what is scored.

Q: Precision or recall for fraud?

Both, at the operating threshold, chosen from the cost of each mistake. Precision measures wasted reviews and annoyed customers; recall measures fraud let through.

Q: Why PR-AUC over ROC-AUC for imbalanced data?

ROC-AUC counts plentiful true negatives and can look excellent while most flags are wrong. PR-AUC focuses on positives and flags; its baseline is the positive rate.

Q: How do you choose a threshold?

Price false positives and false negatives, compute total cost at each threshold, pick the minimum, then check constraints like review capacity.

Q: What measures would you use for ranking?

NDCG at k with graded relevance for the final list, recall at k for retrieval, and MRR when one right answer is enough.

Q: Why WAPE instead of MAPE for forecasts?

MAPE breaks on zero or small actuals; WAPE divides total error by total volume, so it is stable and weights big sellers more. Also track bias.

Q: Why might a model win offline and lose online?

Logged data reflects the old model's choices, the offline measure is a proxy, training-serving skew, user reactions such as novelty, and latency costs.

Saying 'accuracy' for a ranking or an imbalanced problem.

Exercise: write an evaluation report

What it is

A short build that uses this module's ideas. Write it yourself before looking anything up; the checks at the end tell you whether it works.

Why it matters

An idea you have only read fades in a week.

  • Building it once, even in fifty lines, is what makes it yours.
  • Interviewers can tell the difference between someone who has read about a loop and someone who has debugged one.

In the real world: Model reviews at most companies are built around exactly this page; writing one well is a core ML engineering skill.

Your task. Write the one-page offline evaluation of a candidate model against a baseline and a champion, as a model review would expect.

Steps

  1. Take two models from earlier exercises as champion and candidate, plus a rule baseline.
  2. Choose measures that fit the task, with one sentence each on why.
  3. Evaluate all three on the same later period, overall and on at least three slices.
  4. For a classifier, price the two mistakes and find the cheapest threshold; report precision and recall there.
  5. Add bootstrap intervals for the candidate-minus-champion difference.
  6. Run a three-round backtest and report the spread.

You are done when

  • Every number is on the same rows for all three models.
  • Each headline difference has an interval, and you state whether it is real.
  • You recommend ship, hold or reject, with the reason in one sentence.

Stretch. List three reasons this candidate might still lose online, and the check you would add for each.