RecSys · textbook
Widgets Revision About All chapters

The trainer

Metrics: compute them by hand and turn the knobs

In an interview you are asked to compute a metric, not to describe it. Here you can both practise computing in your head and see how a metric reacts to a change in the output.

The drill: compute the metric

Sixteen types of task: ranking metrics, the confusion matrix, AUC computed two ways, smoothed CTR, IPS, the end-to-end recall of a funnel, a Bloom filter, hash collisions. The answer is checked to within 0.005; you can enter a fraction (2/5), a decimal (0.4) or a percentage (40).

The type of the next task is chosen with a bias towards your weak spots: the more often you erred on a type, the more often it comes up. The table under the drill shows what exactly is sagging. The button «a session of 10 tasks» hides the explanation until the end — that is closer to an interview, where nobody prompts you after every answer. The statistics are stored locally in your browser.

All the ranking metrics on one output

The main widget of the page. A click on a row toggles relevance, the arrows change the order, the slider sets \(K\).

What to look for here
  1. Take the preset «positives at the bottom» and lift both positives to the top with the arrows. Precision@K and Recall@K will not change at all — they do not see the order. RR, AP and NDCG will grow.
  2. Reduce \(K\): recall falls, precision may grow — the classic trade-off.
  3. The preset «one positive»: RR becomes exactly \(1/\text{position}\), and NDCG the same number, only with a logarithmic discount instead of a linear one.
  4. Switch on graded relevance — now a click on a row cycles 0 → 1 → 2. Precision and recall simply binarise the grades, while NDCG really does tell «2» from «1».
  5. Then switch to gain = 2^rel − 1. The numerator in DCG changes, and NDCG with it — under one and the same ranking. There is no single «correct» gain, it is a convention, and in an interview it is spelled out.
  6. Note the names: there is one query here, so it is honest to write RR and AP. The letter M in MRR and MAP is mean over queries, and what you average over changes the result: a separate widget below.

AUC, the threshold and class imbalance

The second most frequent question after precision and recall. The widget shows three things at once: how the threshold moves the point along the curves, how ROC differs from PR, and why AUC is the share of correctly ordered pairs.

What to look for here
  1. Move the threshold: precision and recall go in opposite directions, while the ROC-AUC does not change at all — it does not depend on the threshold, it is a property of the ranking rather than of the decision rule.
  2. Move the share of positives at a fixed model quality: from 5% to 60% the ROC-AUC travels 0.868 → 0.852 (sixteen thousandths), while AP collapses from 0.890 to 0.341. Hence the rule: on strongly imbalanced tasks you look at PR, not at ROC.
  3. The tab «AUC as a share of pairs»: count the green cells and see that the share equals the ROC-AUC on the same points exactly.
  4. The data here is deterministic: the slider picks points out of one and the same fixed pool rather than resampling. Otherwise the noise of the estimate (at 5% positives the standard deviation of the ROC-AUC itself reaches 0.145) would completely swallow the effect you are meant to see.

What to average over: micro against macro

The letter M in MRR and MAP is mean. The question «and what do you average over» is asked in an interview right after «what is MAP», and the right answer is «it depends on what we want to see».

What to look for here
  1. By headcount half the users are newcomers, while the queries from them are a few percent. So micro is almost entirely determined by the active ones.
  2. Drop the metric on the newcomers to zero. Micro sags by hundredths, macro by tenths. A release that kills onboarding looks neutral by micro.
  3. The converse is also true: macro over-rates the contribution of those who made one query and left. So both are looked at — and slices by cohort are cut separately.

What to say in an interview: «Averaging over queries measures the average query, averaging over users the average user. With a heavy tail of activity these are different numbers, and the degradation of newcomers is visible only in the second».

Calibration: why a good AUC is not enough

A trap question: «the model has an AUC of 0.85, can it go into an auction?» The answer is no, not until the calibration has been checked. AUC is about order, an auction is about values.

What to look for here
  1. Both sliders are monotone transformations of the score. The order of the objects does not change at all, so the ROC-AUC stands dead still at one and the same number.
  2. Meanwhile ECE, LogLoss and Brier wander by multiples. Compare the «average prediction» and the «observed frequency»: the discrepancy is the systematic error of calibration.
  3. Press Platt scaling. ECE falls from about 0.16 to 0.02, LogLoss from 0.65 to 0.48 — while the AUC does not change by a single unit in the fourth digit. Calibration is fixed after training and does not interfere with the ranking.

What to say in an interview: «AUC is invariant to any monotone transformation of the score, so it says nothing about calibration. Where a prediction is multiplied by money — an auction, a budget, expected revenue — LogLoss, ECE and a calibration curve are needed».

Off-policy evaluation: IPS, SNIPS and DR

«How do you evaluate a new policy without rolling it out» is the question that separates those who have read about recommendations from those who have built them.

What to look for here
  1. The cloud of points is 200 independent runs. The mean of IPS lies exactly on the true value (it is unbiased), but the cloud is wide: on a single log you can be off by a factor of several.
  2. Pull the divergence of the policies: the ESS falls from 400 to 25 out of 500 records, and the spread of IPS grows fourfold. That is what «the estimate falls apart under weak overlap» means.
  3. Switch clipping on. At \(w \le 15\) the bias is −0.053, but the RMSE improves; at \(w \le 5\) the bias is −0.164 and the RMSE is already worse than with no clipping. The threshold has an optimum.
  4. DM is biased but stable. DR usually wins on RMSE — it combines a reward model with a correction through the weights.

What to say in an interview: «IPS is unbiased provided the policies overlap and the propensities are known. Its trouble is variance: the weight \(1/p\) explodes on rare actions. It is cured by self-normalisation, clipping or DR, and every way pays with bias».

A/B: sample size, MDE and peeking

Two things that are asked almost always: «how much traffic is needed» and «why can I not look at the result every day».

What to look for here
  1. The MDE curve falls as \(1/\sqrt{n}\). To tell apart an effect twice as small you need four times as much data — that is the answer to «let us go and measure +0.1%».
  2. Reduce the base conversion at the same relative lift: the required sample grows, because the absolute difference \(p_0 \cdot \text{lift}\) became smaller.
  3. The tab «peeking» is an A/A test, there is no real effect at all. Checking once at the end gives an honest ≈5%, while checking daily over two weeks gives about 22%. Every new look is one more chance of crossing the threshold by accident.

What to say in an interview: «We fix the horizon in advance and compute the MDE before the start. If we have to look along the way, we take a sequential test or alpha spending, otherwise the nominal 5% turns into 20-plus%».

Recall@K against latency

A metric of candidate generation is never compared at a fixed \(K\): candidate generators cost different amounts. Move the budget and the winner changes.

The softmax temperature

A numerical example for the temperature: with a cosine the logits are squeezed into \([-1;1]\), and without a temperature the softmax is almost uniform.

In-batch negatives and the LogQ correction

Not an illustration but real training — a sampled softmax with in-batch negatives. Two models see one and the same stream of batches: one without a correction, the other subtracting \(\log Q\) from the logit.

What to look for here
  1. The teal points (with the correction) lie on the diagonal «learned = truth». The pink ones do not, and the bigger the point — that is, the more popular the item — the further down it has travelled.
  2. Check the numbers: without the correction the correlation of the learned score with \(\log p - \log Q\) is ≈ 0.99. The model learned exactly what theory predicts for a sampled softmax without a correction — it is simply not what we need.
  3. The rank correlation with the truth: ≈0.57 without the correction against ≈0.96 with it. In the top-5 of the model without the correction, rare items climb in.
  4. Set \(\alpha = 0\) — popularity becomes uniform, \(Q\) a constant, and the correction stops changing anything. That is a check of understanding: the correction cures precisely the skew of \(Q\), not «noise».

Bandits: ε-greedy, UCB, Thompson

Three algorithms on the same knobs. Run 500 steps and compare the shape of the regret curves.

Widgets about the mechanisms of systems

Metrics and statistics are gathered here. The interactives about how the systems themselves are built — the long tail, the funnel, embeddings and the cosine, ALS, MMR, hashing, the Bloom filter, PID blending, PLE, attention, semantic IDs, ANN, negatives — are embedded in the corresponding weeks and collected in the widget catalogue.

The formulas that get asked

Precision@K

\(\frac{\#\{\text{rel. in top-}K\}}{K}\) — the share of relevant items among those served.

Recall@K

\(\frac{\#\{\text{rel. in top-}K\}}{\#\{\text{all rel.}\}}\) — what fraction was retrieved.

HitRate@K

1 if the top-\(K\) holds at least one relevant item.

MRR

\(\frac{1}{\text{position of the first relevant}}\), averaged over queries.

AP@K

\(\frac{1}{|R|}\sum_{k} \mathrm{P@}k \cdot rel_k\) — the precision at every «lucky» position.

NDCG@K

\(\frac{\sum_k g(rel_k)/\log_2(k+1)}{\mathrm{IDCG@}K}\); the gain can be your own — even the price.

ROC-AUC

\(P\bigl(s(\text{pos}) > s(\text{neg})\bigr)\) — the share of correctly ordered pairs; a tie = 0.5.

Precision / Recall

\(\frac{TP}{TP+FP}\) and \(\frac{TP}{TP+FN}\). F1 is their harmonic mean.

FPR

\(\frac{FP}{FP+TN}\) — the X axis of ROC. Recall (TPR) is the Y axis.

Smoothed CTR

\(\frac{c+\alpha}{n+\alpha+\beta}\) — otherwise one impression with one click gives a CTR of 1.

LogLoss

\(-\frac{1}{N}\sum y\log p + (1-y)\log(1-p)\) — unlike AUC, sensitive to the values and not only to the order.

ECE

\(\sum_b \frac{n_b}{N}\bigl|\overline{p}_b - \overline{y}_b\bigr|\) — the average gap between confidence and fact across the buckets.

IPS

\(\frac{1}{N}\sum_i \frac{r_i \mathbb{1}[a_i = \pi(x_i)]}{p_i}\) — unbiased, but the variance grows as \(1/p\).

ESS

\(\frac{(\sum w)^2}{\sum w^2}\) — how many «effective» observations are left after reweighting.

Sample size

\(n = \frac{2(z_{1-\alpha/2}+z_{\beta})^2 \bar p(1-\bar p)}{\Delta^2}\) per group; the MDE is the same, solved for \(\Delta\).

The traps people fail on
  • Recall with zero relevant items is undefined — agree that it is 0 and say so out loud.
  • AP is normalised by \(|R|\) (as in most textbooks) or by \(\min(|R|, K)\) — clarify the convention, otherwise the numbers will not agree.
  • NDCG depends on the definition of the gain: \(rel\) against \(2^{rel}-1\) give different numbers.
  • ROC-AUC is insensitive to imbalance, PR is sensitive. That is literally the next question after «what is AUC».
  • Ties in the scores give 0.5 to the pair — otherwise the AUC comes out over-stated.
  • A metric is averaged over queries, but it is also useful to average over users: otherwise the active cohorts pull the mean.
  • AUC says nothing about calibration. Any monotone transformation of the score leaves the AUC exactly the same while possibly breaking the values entirely.
  • IPS without overlapping policies is meaningless. If the target policy chooses what the logging one hardly ever showed, the estimate is formally unbiased, but its spread makes it useless — look at the ESS.
  • Peeking in an A/B breaks the significance level. Five percent turns into twenty if you look every day without a correction.