Quantitative Finance · Book 18 · Careers

Interviews I: Maths, Probability and Speed

Interviews I: Maths, Probability and Speed · Careers

21Machine Learning

Machine learning as interviews test it: bias and variance, trees and boosting, leakage and validation on time series, regularisation, neural networks by hand, metrics, and what low signal does to all of them. Almost every answer here is a number you can derive.

Question 21.1 ★ QR, DS, Analyst • any • junior

A model flags 100 days out of 1000 as days of a large upward move. Of the flagged days, 40 really were such days, and a further 10 such days went unflagged. Give accuracy, precision, recall and F1. What accuracy does a model reach that never calls anything?

Answer

Answer to Question 21.1.

Accuracy 0.930.93, precision 0.400.40, recall 0.800.80, F1 0.530.53. A model that never flags anything has accuracy 0.950.95, which is higher.

The counts are 40 true positives, 60 false positives, 10 false negatives, and so 890 true negatives. Accuracy is 930/1000930/1000. Precision is 40/10040/100, the share of flags that are right. Recall is 40/5040/50, the share of real events that are caught. F1 is their harmonic mean, 2(0.4)(0.8)/1.2=0.5332(0.4)(0.8)/1.2 = 0.533.

The empty model is right on the 950 days without the event, so it beats the real model on accuracy while being useless. When classes are rare, accuracy measures the base rate.

Classic wrong answer. Reporting accuracy of 0.930.93 as a strong result. Or adding 40 and 10 to get the flagged days, which confuses the two denominators.

Follow-up. Write F1 with no reference to true negatives. TP/(TP+12(FP+FN))=40/75\mathrm{TP}/(\mathrm{TP} + \frac12(\mathrm{FP} + \mathrm{FN})) = 40/75. The 890 true negatives have no effect, which is the point of the measure.

Why it matters. This is the fastest check that a candidate reads the right denominators, and the example with a useless model shows whether accuracy will be questioned.

Question 21.2 ★ QR, DS, QT • any • junior

You try 20 models with no skill at all, each on the same test set of 100 independent up-or-down days, with models independent of one another, and report the best. About what accuracy do you report? What should you have done differently?

Answer

Answer to Question 21.2.

About 59% accuracy, though every model is worth 50%. A test set is used once, after all selection is done.

Each model’s score is roughly normal, with mean 50% and standard deviation 5%. The largest of 20 independent normals lies about 1.871.87 standard deviations above the mean, so the expected best is about 59.3%59.3\%, and an exact binomial calculation and a simulation give the same value.

The right procedure: choose on a separate validation set, or by cross-validation, and then score the single chosen model once on the untouched test set. That score is unbiased for the chosen model, and here it would come back near 50%. If several models must be reported, adjust for the number tried.

Classic wrong answer. Reporting the best model’s test score, or using the test set to decide what to try next. Each peek turns the test set into a validation set.

Follow-up. How long a test set keeps the best of 20 null models below 52% on average? About 2200 days: 1.87×50/n=21.87 \times 50/\sqrt{n} = 2 gives n≈2180n \approx 2180.

Why it matters. The whole subject of overfitting research can be put in this one example. Quant interviewers listen for whether the candidate counts trials without being asked.

Question 21.3 ★ QR, DS, QD • any • junior

You record one feature in cents, not dollars, and refit. Which of these change their predictions: ordinary least squares, ridge regression, kk-nearest neighbours, a decision tree, a random forest, regression on the top two principal components?

Answer

Answer to Question 21.3.

Ridge, kk-nearest neighbours and principal component regression change. Ordinary least squares, the tree and the forest do not, apart from any random seeds.

Least squares rescales the coefficient by 1/1001/100, and predictions are unchanged. Ridge penalises the size of coefficients, so a smaller coefficient on the rescaled feature pays less, and the fit shifts. Nearest neighbours uses distances, so the feature in cents dominates them. Principal components chase variance, so the same feature takes over the first component.

A tree splits on order alone, and multiplying by 100 preserves order; a forest is a collection of trees. Runs on simulated data confirm each case.

Classic wrong answer. Saying that ridge is unaffected because least squares is. Or that all models should be fine after fitting. The rule is: anything that uses a distance or a penalty on size needs a common scale.

Follow-up. What should you do with such models, and when? Standardise each feature, using the training data only. Using all the data leaks information from the test period.

Why it matters. A basic preparation question that catches people who treat all models alike, and it is a real source of bugs.

Question 21.4 ★ QR, DS, Analyst • any • junior

A binary label equals 1 on 10% of rows. What log loss does the constant prediction 0.10.1 earn, and the constant 0.50.5? What single-row loss comes from predicting 0.9990.999 on a row whose label is 0, and why should this worry you?

Answer

Answer to Question 21.4.

The constant 0.10.1 earns 0.3250.325, the constant 0.50.5 earns 0.6930.693, and the single row costs ln⁡1000=6.91\ln 1000 = 6.91.

Log loss is the mean of −ln⁡(predicted probability of what happened)-\ln(\text{predicted probability of what happened}). For the constant 0.10.1: −0.1ln⁡0.1−0.9ln⁡0.9=0.325-0.1\ln 0.1 - 0.9\ln 0.9 = 0.325. For 0.50.5: −ln⁡0.5=0.693-\ln 0.5 = 0.693, for every row, whatever the base rate.

A prediction of 0.9990.999 on a label of 0 gives probability 0.0010.001 to what occurred, and it costs 6.916.91. That is more than twenty times the base loss, and one such row in 100 adds 0.0690.069, a fifth of the base loss. So the metric punishes overconfidence severely. A model that reports raw scores near 0 and 1 needs clipping or calibration.

Classic wrong answer. Comparing a model’s log loss to 0.6930.693 on an unbalanced problem. The fair baseline is the constant at the base rate, here 0.3250.325.

Follow-up. Which constant minimises log loss? The base rate. Setting the derivative of −bln⁡p−(1−b)ln⁡(1−p)-b\ln p - (1 - b)\ln(1 - p) to zero gives p=bp = b, which is why log loss rewards calibration.

Why it matters. Reading a loss needs a baseline. A candidate who gives the base-rate figure at once has used this metric on real data.

Question 21.5 ★ QR, DS, Analyst • any • junior

A logistic regression has a coefficient of 0.70.7 on a standardised feature. What happens to the odds when the feature rises by 1? Starting from probabilities 0.20.2 and from 0.50.5, what is the new probability in each case?

Answer

Answer to Question 21.5.

The odds double, since e0.7=2.01e^{0.7} = 2.01. A probability of 0.20.2 becomes 0.330.33, and 0.50.5 becomes 0.670.67.

The model is linear in the log-odds, so a unit rise adds 0.70.7 to the log-odds and multiplies the odds by e0.7e^{0.7}.

From 0.20.2, the odds are 0.250.25, which double to 0.50.5, and so p=0.5/1.5=1/3p = 0.5/1.5 = 1/3. From 0.50.5, the odds are 1, which double to 2, and so p=2/3p = 2/3. The same coefficient adds 0.130.13 in one case and 0.170.17 in the other. The effect on the probability depends on where you start.

Classic wrong answer. Saying that the probability rises by 0.70.7, or doubles. A probability cannot do that from 0.60.6, whereas the odds can.

Follow-up. Give a quick rule for the effect near p=12p = \frac12. The slope of the logistic curve there is 14\frac14, so the change is about the coefficient over 4. Here that is 0.1750.175, close to the true 0.170.17.

Why it matters. Coefficients are read wrongly more often than they are computed wrongly. Separating odds from probabilities is what the question tests.

Question 21.6 ★ QR, DS, QD • any • junior

You run 5-fold cross-validation on 1000 rows, over a grid of 10 values for each of 3 hyperparameters. How large is each training set? How many times is a given row validated, and how many models does it help train? How many fits does the search need in total?

Answer

Answer to Question 21.6.

Training sets have 800 rows. A row is validated once and helps train four models. The search needs 5000 fits.

Each fold holds out one fifth, 200 rows, and trains on the other 800. Over five folds, a row is in the held-out part exactly once and in the training part the other four times.

The grid has 103=100010^3 = 1000 points, and each needs 5 fits, for 5000 in all. Once the point is chosen, one more fit on all 1000 rows gives the final model.

The cross-validated score of the chosen point is biased upward, since it is the best of 1000. A separate test set, or an outer loop, is needed for an honest figure.

Classic wrong answer. Reporting the score of the best grid point as the expected performance, or multiplying 3 by 10 for the size of the grid. It is 10 to the power 3.

Follow-up. What does a nested search with 5 outer folds cost? 25 00025\,000 fits, five times as many. That is what an unbiased estimate of the whole procedure costs.

Why it matters. Simple counts reveal who has actually run such a search, and who has thought about what its best score means.

Question 21.7 ★ QR, DS, Risk • any • junior

Bad trades make up 1% of a stream. A detector catches 90% of them and wrongly flags 5% of the good ones. What share of flags are real? What is this share if the false positive rate falls to 1%? Does the area under the ROC curve change if the bad trades become 10% of the stream?

Answer

Answer to Question 21.7.

About 15% of flags are real, 48% at the lower false positive rate, and the ROC area does not change with prevalence.

Per 1000 trades: 10 are bad, of which 9 are caught, and 990 are good, of which 49.549.5 are flagged. So precision is 9/58.5=0.1549/58.5 = 0.154. With a false positive rate of 1%, the flags are 9+9.99 + 9.9, which gives 0.4760.476. A small improvement in the false positive rate has a large effect, because the good trades outnumber the bad.

The ROC curve plots the true positive rate against the false positive rate. Each is computed within a single class, so the mix of classes does not enter. A run at both prevalences gives the same area.

Classic wrong answer. Saying that a detector with 90% and 95% rates is right most of the time when it flags. Or reporting ROC area alone for a rare-event problem, where it hides the false alarm load.

Follow-up. What is the share of real flags at 10% prevalence? 0.09/(0.09+0.045)=0.6670.09/(0.09 + 0.045) = 0.667, with the same detector. Precision does depend on prevalence, so a figure measured on a balanced test set does not carry over to production.

Why it matters. It separates metrics that depend on prevalence from those that do not, and it comes up whenever a model moves to a stream with a different mix.

Question 21.8 ★ QR, DS, QD • any • junior

A fully connected network has 20 inputs, hidden layers of 64 and 32 units and one output, with a bias at each unit that computes. How many parameters does it have? You train it on 1250 daily rows. What should this make you think of?

Answer

Answer to Question 21.8.

There are 3457 parameters, about 2.82.8 per row, so with low-signal data the model will memorise unless heavily constrained.

Each layer has inputs times units for the weights, plus one bias per unit. Layer one: (20+1)×64=1344(20 + 1) \times 64 = 1344. Layer two: (64+1)×32=2080(64 + 1) \times 32 = 2080. Output: (32+1)×1=33(32 + 1) \times 1 = 33. The sum is 3457, and the count from a deep learning library agrees.

With 1250 rows, the model has more parameters than rows, and returns are mostly noise, so it can fit the training set with no real signal. Weight decay, dropout, early stopping and a smaller architecture are the normal responses. An honest walk-forward validation decides. A very small network, or a linear model, is the baseline to beat.

Classic wrong answer. Forgetting the biases, which gives 3360. Or concluding that the network must fail: overparameterised networks can generalise, but on noisy returns the size of the model is a warning that needs testing.

Follow-up. What would you try first with so little data? A regularised linear model, as the baseline. If a network cannot beat it out of sample, the extra parameters are not paying.

Why it matters. Counting parameters is mechanical, and what the interviewer listens for is the comparison with the number of rows.

Question 21.9 ★ QR, DS, QT • any • junior

Two models, with a target accuracy of 85%. Model A scores 99% in training and 70% on validation. Model B scores 72% and 70%. What is the likely problem with each? For each, does more data help, and what would you change?

Answer

Answer to Question 21.9.

Model A overfits, with high variance. Model B underfits, with high bias. More data helps A and not B.

A has a gap of 29 points between training and validation. It is memorising. More data narrows the gap, as do stronger regularisation, fewer features and a simpler model.

B has almost no gap, and both are far below the target of 85%. It lacks capacity or information. Adding rows moves both curves very little. It needs a more flexible model, or better features. If the target is out of reach for any model, the noise in the labels may be the real limit, so check this first.

A run shows both. A 1-nearest-neighbour classifier on a noisy wave has a wide gap that narrows with more rows. A linear classifier on the same wave stays low on both sets and does not improve.

Classic wrong answer. Saying that more data always helps. It does nothing for a model that is already too simple, as B’s curves have met already.

Follow-up. What would a validation score higher than the training score suggest? Regularisation active only in training, such as dropout, or an easier validation period. If neither applies, suspect a split that leaks.

Why it matters. Diagnosis decides where time goes. A candidate who can say which fix is wasted saves weeks of work.

Question 21.10 ★★ QR, DS, QD • any • junior

The true function is f(x)=xf(x) = x, and observations have noise of variance 1. You estimate ff at a point using the mean of its kk nearest neighbours, which lie at distances 0.2,0.4,…,0.2k0.2, 0.4, \dots, 0.2k, all on one side. Write the bias and variance. Which kk minimises the squared error of the estimate? What happens to the best kk if the data are twice as dense?

Answer

Answer to Question 21.10.

Bias is 0.1(k+1)0.1(k + 1) and variance 1/k1/k, so the best kk is 3, with squared error 0.4930.493. Doubling the density raises the best kk to 6.

The mean of the kk neighbours has expected value 0.2(1+⋯+k)/k=0.1(k+1)0.2(1 + \dots + k)/k = 0.1(k + 1) away from the true value. Its variance is 1/k1/k. So the squared error is

1k+0.01(k+1)2.\frac{1}{k} + 0.01(k + 1)^2.

The values at k=1,2,3,4k = 1, 2, 3, 4 are 1.041.04, 0.590.59, 0.4930.493 and 0.50.5, so the best is k=3k = 3. A simulation of the three-neighbour estimate gives the same 0.4930.493.

With spacing 0.10.1, the error is 1/k+0.0025(k+1)21/k + 0.0025(k + 1)^2, with minimum 0.2890.289 at k=6k = 6. More data allows a larger neighbourhood, which lowers the variance while the distances stay small. Both bias and variance fall.

Each new observation still has noise of variance 1, which no choice of kk removes.

Classic wrong answer. Adding the bias to the variance with no square. The terms that add are the variance and the squared bias.

Follow-up. If the neighbours lie evenly on both sides, what is the best kk? As large as the data allow, in this model. A straight line gives zero bias under symmetric averaging, so only the variance remains. Curvature is what would stop it.

Why it matters. An explicit bias-variance curve is more convincing than the usual picture, and it shows how the best complexity moves with the data.

Question 21.11 ★★ QR, DS • any • junior

A correct linear model with 20 parameters is fitted on 100 rows, with noise variance 1 and fixed regressors. What is the expected mean squared error on the training rows? What is it on new noise at the same regressors? Interpret the gap, and say how it depends on the number of parameters.

Answer

Answer to Question 21.11.

Training error 0.80.8, new-noise error 1.21.2. The gap of 0.40.4 equals 2pσ2/n2p\sigma^2/n.

Fitting projects the noise on the regressors’ column space. The fit absorbs pp of the nn dimensions of noise, so the residual sum of squares has expectation σ2(n−p)\sigma^2(n - p), and the mean squared error is 1−20/100=0.81 - 20/100 = 0.8.

The fitted values carry noise of total variance pσ2p\sigma^2. Against fresh noise at the same points, the expected error is the new noise plus that: 1+20/100=1.21 + 20/100 = 1.2. A simulation returns 0.800.80 and 1.201.20.

The fit therefore looks better than the noise level, and predicts worse by the same amount. The gap is linear in the number of parameters. This is what Mallows’s CpC_p and the Akaike criterion add back to the training error.

Classic wrong answer. Saying that a correct model has no overfitting. Being correct removes the bias, not the variance from estimating 20 numbers.

Follow-up. What do ten more useless parameters add to the gap? 2×10/100=0.22 \times 10/100 = 0.2. A criterion accepts a new feature only if it lowers the training error by more than this charge.

Why it matters. This is the simplest exact result behind model selection. It shows that the training error misleads even when the model is right.

Question 21.12 ★★ QR, DS, Analyst • any • junior

A node has 40 positives and 60 negatives. A split sends 30 positives and 10 negatives left, and the rest right. Compute the decrease in Gini impurity and in entropy, in bits.

Answer

Answer to Question 21.12.

The Gini impurity falls by 0.1630.163, and the entropy by 0.2560.256 bits.

Left child: 30 and 10, right child: 10 and 50, with weights 0.40.4 and 0.60.6.

Gini is 2p(1−p)2p(1 - p). Parent: 2(0.4)(0.6)=0.482(0.4)(0.6) = 0.48. Left: 2(0.75)(0.25)=0.3752(0.75)(0.25) = 0.375. Right: 2(16)(56)=0.2782(\frac16)(\frac56) = 0.278. Weighted: 0.4(0.375)+0.6(0.278)=0.3170.4(0.375) + 0.6(0.278) = 0.317. So the decrease is 0.1630.163.

Entropy is −plog⁡2p−(1−p)log⁡2(1−p)-p\log_2 p - (1 - p)\log_2(1 - p). Parent: 0.9710.971. Left: 0.8110.811. Right: 0.6500.650. Weighted: 0.7150.715. The decrease is 0.2560.256.

The two criteria are on different scales, so the numbers are not comparable, and in practice they rank most splits the same way.

Classic wrong answer. Averaging the two children with equal weights, which gives a different number. The weights are the shares of rows.

Follow-up. What is the meaning of the Gini impurity? The chance that two rows drawn at random with replacement from the node have different labels, or the error of a rule that guesses at random in the node’s proportions.

Why it matters. A simple check that someone can compute what a library computes, with the weighting as the common mistake.

Question 21.13 ★★ QR, DS • any • junior

A node has 400 positives and 400 negatives. Split A gives children (300, 100) and (100, 300). Split B gives (200, 400) and (200, 0). Compare them by misclassification error and by Gini impurity. Which should you prefer, and what general property of the criterion explains the result?

Answer

Answer to Question 21.13.

Misclassification error gives 0.250.25 for both. Gini gives 0.3750.375 for A and 0.3330.333 for B, so B is preferred, since it creates a pure node. The cause is that Gini is strictly concave.

Under the majority rule: in A, each child is wrong on 100, for 200/800200/800. In B, the first child is wrong on 200 and the second on 0, also 200/800200/800.

Gini for A: 2(34)(14)=0.3752(\frac34)(\frac14) = 0.375 for each child. For B: the first child has 34\frac34 of the rows, with 2(13)(23)=0.4442(\frac13)(\frac23) = 0.444, and the pure child has 0, so 0.75×0.444=0.3330.75 \times 0.444 = 0.333.

The misclassification rate is piecewise linear in pp. Unless the majority changes across the children, mixing two children gives the same weighted error, so the split shows no gain. A strictly concave function always falls under a split that separates the classes at all, and it rewards purity. The pure node is valuable since later splits only have to work on the rest.

Classic wrong answer. Saying that A is better because it is symmetric, or concluding that the criteria always disagree. They usually agree, but ties and near-ties, where they can differ, are frequent early in a tree. Children (210,400)(210, 400) and (190,0)(190, 0), for instance, have a worse error than A, 0.26250.2625, and a better Gini, 0.3440.344.

Follow-up. When does a split give zero gain, for every concave criterion? When both children have the parent’s proportions. In that case nothing has been learned about the label.

Why it matters. It explains why a tree does not simply optimise the metric used in the end, and that is a useful general principle.

Question 21.14 ★★ QR, DS, QT • any • junior, experienced

You average BB models, each with variance σ2\sigma^2, and pairwise correlation ρ\rho. Derive the variance of the average. For σ2=1\sigma^2 = 1, ρ=0.3\rho = 0.3 and B=100B = 100, what is it, and what does it become as BB grows? Using random feature subsets at each split lowers ρ\rho to 0.10.1 but raises σ2\sigma^2 to 1.21.2. Is this a good trade?

Answer

Answer to Question 21.14.

The variance is ρσ2+(1−ρ)σ2/B\rho\sigma^2 + (1 - \rho)\sigma^2/B, which is 0.3070.307 at B=100B = 100, and 0.30.3 in the limit. The trade is good, with 0.1310.131 at the same BB.

Expand the variance of the mean:

1B2(Bσ2+B(B−1)ρσ2)=ρσ2+(1−ρ)σ2B.\frac{1}{B^2}\left(B\sigma^2 + B(B - 1)\rho\sigma^2\right) = \rho\sigma^2 + \frac{(1 - \rho)\sigma^2}{B}.

At the stated values: 0.3+0.7/100=0.3070.3 + 0.7/100 = 0.307. Check the limits: ρ=1\rho = 1 gives σ2\sigma^2, as one model does, and ρ=0\rho = 0 gives σ2/B\sigma^2/B. A simulation of correlated models returns 0.3070.307.

So more models stop helping at the shared part ρσ2\rho\sigma^2. To go lower, the models must be made less alike, and that is the purpose of feature subsampling in a random forest. With ρ=0.1\rho = 0.1 and σ2=1.2\sigma^2 = 1.2: 0.12+1.08/100=0.1310.12 + 1.08/100 = 0.131. The individual models are worse, while the average is more than twice as good.

Classic wrong answer. Assuming that the variance goes to zero with enough trees. That holds only for independent models, which trees built on the same data are not.

Follow-up. At ρ=0.3\rho = 0.3, how many models get within 1% of the limit? 0.7/B≤0.0030.7/B \le 0.003 gives about 234. Past this, adding more is waste.

Why it matters. The formula explains why forests work and why ensembles of similar alphas disappoint. Quants meet the same formula when they combine correlated signals.

Question 21.15 ★★ QR, DS • any • junior

In gradient boosting with squared loss, show that the residual is the negative gradient. Suppose each new tree fits the current residual of a given row exactly, and is added with shrinkage ν=0.1\nu = 0.1. What share of the target is fitted after mm trees? When do you pass 90% and 99%? Why shrink at all?

Answer

Answer to Question 21.15.

The fitted share after mm trees is 1−0.9m1 - 0.9^m, which passes 90% at m=22m = 22 and 99% at m=44m = 44. Shrinking averages over the noise.

For L=12(y−F)2L = \frac12(y - F)^2, the derivative with respect to FF is −(y−F)-(y - F). So the negative gradient is the residual, and fitting a tree to residuals is a gradient step in function space.

If each tree fits the residual exactly and is added with weight ν\nu, the residual is multiplied by 1−ν=0.91 - \nu = 0.9 every round. After mm rounds, 0.9m0.9^m remains. Since 0.922=0.0980.9^{22} = 0.098 and 0.944=0.00970.9^{44} = 0.0097, the two thresholds are crossed at 22 and 44.

A real tree fits a noisy estimate of the residual. With ν=1\nu = 1, the whole of the noise in the last tree stays in the fit. With a small ν\nu, the fit is an average over many trees, each with different noise. The price is more trees.

Classic wrong answer. Thinking that shrinkage changes the final target. It only changes how fast it is reached and how much noise comes along.

Follow-up. If each tree’s estimate of the residual has noise of variance 1, independently, what noise variance does the fit settle at? ν/(2−ν)\nu/(2 - \nu), which is 0.0530.053 at ν=0.1\nu = 0.1 and 1 at ν=1\nu = 1. A simulation agrees.

Why it matters. A candidate should know what boosting does at the level of one row. The formula explains the usual advice about small learning rates with more trees.

Question 21.16 ★★ QR, DS, QT • hedge fund • junior, experienced

The data have one real pattern in two features, and 20% of the labels are flipped at random. You increase the number of trees to 1000, first in a random forest of deep trees, then in boosting of small trees with a large learning rate. What do the training and test errors do in each case? Why the difference?

Answer

Answer to Question 21.16.

The forest’s test error levels off and stays there, a little above the 20% noise. The boosting training error goes to zero, while its test error falls and then rises.

A forest averages trees. Adding a tree changes only the estimate of an average, whose variance falls with BB, so the error approaches a limit. It cannot overfit by having too many trees, although each deep tree has fitted the noise, and the forest’s training error is close to zero too.

Boosting is sequential. Each tree aims at what is still unexplained, and once the pattern is exhausted, this is the flipped labels. The model has unbounded capacity in the number of rounds, and it goes on fitting them.

A run on 400 rows, with a checkerboard pattern and 20% flips, shows it. Boosting with learning rate 0.50.5 reaches a training error below 1%, and its test error ends above 25%, more than two points above its minimum. For the forest, going from 100 to 1000 trees moves test error by less than a point. So in boosting the number of trees is a hyperparameter to tune by early stopping, and in a forest it is a question of computation.

Classic wrong answer. Saying that both overfit with more trees, or that a forest never overfits. It does not overfit through the number of trees, but it can through deep trees on noisy data.

Follow-up. How do you choose the number of rounds on financial data? By early stopping on a later block of time, separated from the training data by a gap, and not on a random subset of the rows.

Why it matters. It is the central contrast between the two families. The interviewer wants the reason, not only the fact.

Question 21.17 ★★ QR, DS • any • junior

In AdaBoost, a weak learner has a weighted error of 0.30.3. What is its vote α=12ln⁡((1−ε)/ε)\alpha = \frac12\ln((1 - \varepsilon)/\varepsilon)? By what factors are the weights of wrong and right rows multiplied, and what total weight do the wrong rows hold after normalising? What does this total mean for the next learner?

Answer

Answer to Question 21.17.

α=0.424\alpha = 0.424. Wrong rows are multiplied by 1.5281.528 and right rows by 0.6550.655. After normalising, the wrong rows hold a total weight of exactly 12\frac12.

α=12ln⁡(0.7/0.3)=0.424\alpha = \frac12\ln(0.7/0.3) = 0.424. The factors are eα=7/3e^{\alpha} = \sqrt{7/3} and e−α=3/7e^{-\alpha} = \sqrt{3/7}.

The wrong rows held 0.30.3, so they now hold 0.37/3=0.210.3\sqrt{7/3} = \sqrt{0.21}. The right rows held 0.70.7, now 0.73/7=0.210.7\sqrt{3/7} = \sqrt{0.21}. These are equal, so each share is 12\frac12. The normaliser is 20.21=0.9172\sqrt{0.21} = 0.917.

This means that the last learner now has a weighted error of exactly 12\frac12 on the new weights: it is worth nothing. So the next learner must find something new. It cannot score by repeating the last one. That holds whatever ε\varepsilon is, which is the reason for this choice of α\alpha.

Classic wrong answer. Saying that wrong rows get “more weight” with no number. The exact 12\frac12 is the content of the algorithm.

Follow-up. What are the votes for ε=0.5\varepsilon = 0.5 and ε=0.6\varepsilon = 0.6? Zero and 12ln⁡(2/3)=−0.20\frac12\ln(2/3) = -0.20. A coin flip gets no vote, and a learner worse than a coin gets a negative vote, so that its opposite is used.

Why it matters. It tests whether the reweighting is known as a calculation, and it leads to the bound on the training error.

Question 21.18 ★★ QR, DS • hedge fund • junior, experienced

Show that ridge regression is the posterior mean under a normal prior, with β∼N(0,τ2I)\beta \sim N(0, \tau^2 I) and noise variance σ2\sigma^2, and find λ\lambda. Then define its effective number of parameters, and compute it for squared singular values 100, 10 and 1, with λ=10\lambda = 10. Check both limits of λ\lambda.

Answer

Answer to Question 21.18.

λ=σ2/τ2\lambda = \sigma^2/\tau^2. The effective number of parameters is ∑di2/(di2+λ)=1.5\sum d_i^2/(d_i^2 + \lambda) = 1.5.

The log posterior is, up to a constant,

−12σ2∥y−Xβ∥2−12τ2∥β∥2.-\frac{1}{2\sigma^2}\|y - X\beta\|^2 - \frac{1}{2\tau^2}\|\beta\|^2.

Multiplying by 2σ22\sigma^2 gives the ridge objective, with λ=σ2/τ2\lambda = \sigma^2/\tau^2. The posterior is normal, so its mode is its mean, (X⊤X+λI)−1X⊤y(X^\top X + \lambda I)^{-1}X^\top y. A tighter prior or noisier data means more shrinkage.

The fit is y^=Hy\hat{y} = Hy with H=X(X⊤X+λI)−1X⊤H = X(X^\top X + \lambda I)^{-1}X^\top. The natural definition of effective parameters is the trace of HH, since for least squares this equals pp. In terms of the singular values did_i of XX, it is ∑di2/(di2+λ)\sum d_i^2/(d_i^2 + \lambda).

With values 100,10,1100, 10, 1 and λ=10\lambda = 10: 100/110+10/20+1/11=0.909+0.5+0.091=1.5100/110 + 10/20 + 1/11 = 0.909 + 0.5 + 0.091 = 1.5. A matrix with these singular values gives the same trace. At λ→0\lambda \to 0 the sum is 3, the full count, and at λ→∞\lambda \to \infty it is 0. The strong direction keeps its freedom, and the weak one is nearly removed.

Classic wrong answer. Treating λ\lambda as a tuning knob with no units. It depends on the scale of the features and on the noise, which the Bayesian form makes obvious.

Follow-up. What is λ\lambda for noise of 1 and a prior standard deviation of 0.10.1? λ=1/0.01=100\lambda = 1/0.01 = 100. For returns, where signals are small, large values of λ\lambda are normal and not a sign of a mistake.

Why it matters. The two views of ridge, penalty and prior, are often asked together. Effective parameters are what let a candidate compare a ridge fit with an unpenalised one.

Question 21.19 ★★ QR, DS • any • junior, experienced

Logistic regression with no intercept and one feature has two rows: x=−1x = -1 with label 0, and x=1x = 1 with label 1. What does the maximum likelihood do? Add a penalty 12λβ2\frac12\lambda\beta^2 with λ=0.1\lambda = 0.1. What is β\beta now, and what probability does the model give at x=1x = 1?

Answer

Answer to Question 21.19.

With no penalty, β\beta runs off to infinity. With λ=0.1\lambda = 0.1, β≈2.13\beta \approx 2.13, and the probability at x=1x = 1 is about 0.890.89.

The loss is 2ln⁡(1+e−β)2\ln(1 + e^{-\beta}), which falls forever as β\beta rises, and approaches 0 with no minimiser. Separable data has no finite maximum likelihood estimate. In practice the coefficient grows until the solver stops, and the software may warn or may not.

With the penalty, set the derivative to zero:

−21+eβ+0.1β=0.-\frac{2}{1 + e^{\beta}} + 0.1\beta = 0.

That equation has a single root at β=2.13\beta = 2.13, found by bisection and matched by a library fit with the same penalty. The probability is 1/(1+e−2.13)=0.8941/(1 + e^{-2.13}) = 0.894.

So the penalty has a direct meaning here: it decides how confident the model may be with no contradicting data. The result is a finite and sensible probability from a dataset of two rows.

Classic wrong answer. Reporting the unpenalised fit as β\beta large but finite, or as a probability of 1. Also saying that separable data is a good sign. With many features and few rows, it is often just a sign of overfitting.

Follow-up. What happens at λ=0.01\lambda = 0.01? β≈3.91\beta \approx 3.91, with probability 0.980.98. Weaker penalties allow more confidence, slowly: a tenfold fall in λ\lambda does not even double β\beta.

Why it matters. This is a classic numerical surprise. The candidate should know why a logistic fit fails to converge, and what regularisation does about it.

Question 21.20 ★★ QR, DS • any • junior

A naive Bayes classifier starts from a prior of 12\frac12. Feature A has a likelihood ratio of 3 for class 1. It was accidentally included three times. Feature B, included once, has a likelihood ratio of 0.10.1. Give the true posterior and the classifier’s posterior if A and B are truly independent given the class. Does the decision change at a threshold of 12\frac12?

Answer

Answer to Question 21.20.

The true posterior is 0.230.23 and the classifier says 0.730.73, so the decision flips.

Naive Bayes multiplies the likelihood ratios, assuming independence given the class. With prior 12\frac12, the posterior odds are the product of the ratios.

The true odds use A once: 3×0.1=0.33 \times 0.1 = 0.3, so the posterior is 0.3/1.3=0.230.3/1.3 = 0.23. Below 12\frac12, the decision is class 0.

The classifier counts A three times: 33×0.1=2.73^3 \times 0.1 = 2.7, so the posterior is 2.7/3.7=0.732.7/3.7 = 0.73. Above 12\frac12, the decision is class 1. A true evidence ratio of 3 has been treated as 27.

With A alone, the problem is hidden: the true posterior is 0.750.75, and the classifier’s is 0.9640.964. These fall on the same side of 12\frac12, so the error is only in confidence. A second feature is what turns it into a wrong decision.

Classic wrong answer. Saying that naive Bayes is immune to correlation because it often ranks well. That is often true of ranking, but correlated features cause overconfidence that can change decisions.

Follow-up. Would logistic regression suffer in the same way? No. It shares the coefficient among the copies, so that their sum stays the same, and it returns the same fit. A run with three copies confirms this.

Why it matters. It makes concrete what the independence assumption costs. In finance, where features are highly correlated, this is an everyday issue.

Question 21.21 ★★ QR, DS, QD • any • junior

A network has one input x=1x = 1, one sigmoid hidden unit h=σ(w1x)h = \sigma(w_1x), and output y^=w2h\hat{y} = w_2h, with w1=0w_1 = 0 and w2=2w_2 = 2. The target is y=0y = 0 and the loss 12(y^−y)2\frac12(\hat{y} - y)^2. Find both gradients by the chain rule. Take a step of size 0.10.1 on both weights, and give the new loss.

Answer

Answer to Question 21.21.

Both gradients are 0.50.5, the new weights are −0.05-0.05 and 1.951.95, and the loss falls from 0.50.5 to 0.4520.452.

Forward: h=σ(0)=0.5h = \sigma(0) = 0.5, y^=2×0.5=1\hat{y} = 2 \times 0.5 = 1, and the loss is 12\frac12.

Backward: ∂L/∂y^=y^−y=1\partial L/\partial\hat{y} = \hat{y} - y = 1.

For w2w_2: ∂y^/∂w2=h=0.5\partial\hat{y}/\partial w_2 = h = 0.5, so the gradient is 0.50.5.

For w1w_1: ∂y^/∂h=w2=2\partial\hat{y}/\partial h = w_2 = 2, and ∂h/∂w1=σ′(0)x=0.25\partial h/\partial w_1 = \sigma'(0)x = 0.25, so the gradient is 1×2×0.25=0.51 \times 2 \times 0.25 = 0.5. Central finite differences agree with both to eight decimals.

Step: w1=0−0.1(0.5)=−0.05w_1 = 0 - 0.1(0.5) = -0.05, and w2=2−0.1(0.5)=1.95w_2 = 2 - 0.1(0.5) = 1.95. Then h=σ(−0.05)=0.4875h = \sigma(-0.05) = 0.4875, y^=0.9506\hat{y} = 0.9506, and the loss is 0.45180.4518. A first-order estimate of the fall is 0.1×(0.52+0.52)=0.050.1 \times (0.5^2 + 0.5^2) = 0.05, and the actual fall is 0.0480.048, so the numbers are consistent.

Classic wrong answer. Leaving out the derivative of the sigmoid, σ(1−σ)\sigma(1 - \sigma), which is 14\frac14 here. Or updating w2w_2 first, and then using the new w2w_2 in the gradient for w1w_1. Both gradients come from the same forward pass.

Follow-up. Why compute derivatives backward, and not forward? One loss and many weights: a backward pass gets every partial derivative for about the cost of one forward pass, and a forward pass would need one sweep per weight.

Why it matters. Any candidate who claims neural network experience should be able to do this with a pen. The check against the predicted fall shows care.

Question 21.22 ★★ QR, DS, QD • any • junior, experienced

Ten sigmoid layers are chained, with weights of 1. What upper bound applies to the gradient reaching the first layer? What does ReLU change, and what new failure does it bring? In a ReLU layer of width nn, what variance of the initial weights keeps the signal’s variance constant through depth?

Answer

Answer to Question 21.22.

The bound is 4−10≈10−64^{-10} \approx 10^{-6}. ReLU has derivative 1 where active, but units can die. The right variance is 2/n2/n.

The sigmoid’s derivative is at most 14\frac14, at the middle of its range. With unit weights, the chain rule gives a product of ten such factors, at most 9.5×10−79.5 \times 10^{-7}. Early layers hardly learn. Larger weights do not fix this in general, because they push the units to saturation, where the derivative is near zero.

ReLU has derivative 1 on its active side, so the product does not shrink through active paths. The new failure is that a unit which is negative on all data has a zero gradient and never recovers: a dead unit. A large learning rate is the usual cause.

For initial variance: with weights of variance vv, and nn inputs of mean square qq, the pre-activation has variance nvqnvq. ReLU keeps half of its second moment. So qnext=12nvqq_{\text{next}} = \frac12 nvq, which is constant at v=2/nv = 2/n. A run through 30 layers of width 500 confirms it: the signal stays within a factor of 10 at 2/n2/n, it collapses below 10−510^{-5} at 1/n1/n, and it explodes above 10510^5 at 4/n4/n.

Classic wrong answer. Using v=1/nv = 1/n with ReLU, which is right for a symmetric activation but loses half the signal per layer.

Follow-up. What does a residual connection do for the gradient? The derivative of x+g(x)x + g(x) is 1+g′(x)1 + g'(x). So a path through the identity carries gradient with no attenuation, however deep the network is.

Why it matters. It tests what the standard fixes really do. An exact value for the variance shows that the candidate can derive them and does not just name them.

Question 21.23 ★★ QR, DS, QD • any • junior

Prove that no linear classifier computes the exclusive or of two bits. Then write a network with one hidden layer of two ReLU units that computes it exactly, and check all four inputs.

Answer

Answer to Question 21.23.

No line separates the classes, by a sum of two inequalities. The network y=r(x1+x2)−2r(x1+x2−1)y = r(x_1 + x_2) - 2r(x_1 + x_2 - 1), with rr the ReLU, computes it.

Suppose w1x1+w2x2+c>0w_1x_1 + w_2x_2 + c > 0 exactly for class 1. Inputs (1,0)(1, 0) and (0,1)(0, 1) give w1+c>0w_1 + c > 0 and w2+c>0w_2 + c > 0. Inputs (0,0)(0, 0) and (1,1)(1, 1) give c<0c < 0 and w1+w2+c<0w_1 + w_2 + c < 0 (or weak inequalities). Adding the first pair gives w1+w2+2c>0w_1 + w_2 + 2c > 0, and adding the second pair gives w1+w2+2c<0w_1 + w_2 + 2c < 0. This is a contradiction.

The network, with s=x1+x2s = x_1 + x_2, gives:

  • (0,0)(0, 0): s=0s = 0, so r(0)−2r(−1)=0r(0) - 2r(-1) = 0.
  • (1,0)(1, 0) or (0,1)(0, 1): s=1s = 1, so r(1)−2r(0)=1r(1) - 2r(0) = 1.
  • (1,1)(1, 1): s=2s = 2, so r(2)−2r(1)=2−2=0r(2) - 2r(1) = 2 - 2 = 0.

The two hidden units create a kink in the function of ss, which is exactly what a linear model lacks. Any tree of depth 2 can do it too.

Classic wrong answer. Saying that a hidden layer makes the problem linearly separable with no construction. Or using two units with the same threshold, which is still a linear function of ss above it.

Follow-up. How does this generalise to the parity of nn bits? One hidden layer of nn ReLU units works: with ss the sum of the bits, r(s)+∑k=1n−12(−1)kr(s−k)r(s) + \sum_{k = 1}^{n - 1}2(-1)^kr(s - k). A check of all inputs up to n=5n = 5 confirms it.

Why it matters. This is the classical reason for hidden layers. Writing the weights down is what an interview adds to the slogan.

Question 21.24 ★★ QR, DS, QD • any • junior

A sigmoid output has logit z=−7z = -7, and the label is 1. Compute the gradient with respect to zz under cross-entropy and under squared loss 12(p−y)2\frac12(p - y)^2. By what factor do they differ? Is each loss convex in zz? What does this mean for training?

Answer

Answer to Question 21.24.

Cross-entropy gives −0.999-0.999 and squared loss gives −0.00091-0.00091, a factor of about 1100. Cross-entropy is convex in zz, and squared loss is not.

Here p=σ(−7)=0.00091p = \sigma(-7) = 0.00091.

Cross-entropy −ln⁡p-\ln p has ∂/∂z=p−1=−0.999\partial/\partial z = p - 1 = -0.999. So when the model is badly wrong, the gradient is close to its largest value.

Squared loss has ∂/∂z=(p−1)×σ′(z)=(p−1)p(1−p)=−9.09×10−4\partial/\partial z = (p - 1) \times \sigma'(z) = (p - 1)p(1 - p) = -9.09 \times 10^{-4}. The chain rule brings in σ′\sigma', which is tiny at the tails. So the worst error produces almost no gradient. The factor is 1/(p(1−p))≈11001/(p(1 - p)) \approx 1100.

The second derivative of cross-entropy in zz is p(1−p)>0p(1 - p) > 0, so it is convex. Squared loss has second differences that are negative at z=−7z = -7 and positive at z=1z = 1, so it is not convex in zz, and it has flat regions from which training hardly moves.

Classic wrong answer. Saying that squared loss is wrong because it is not a likelihood. It is the likelihood for a different model. The issue for training is the gradient.

Follow-up. What are the gradients when the model is right, at z=7z = 7 and y=1y = 1? −0.00091-0.00091 under cross-entropy, and −8.3×10−7-8.3 \times 10^{-7} under squared loss. Cross-entropy stops pushing once right, and only then.

Why it matters. It explains a design choice nearly everyone accepts unexamined, and it gives another example of where a small derivative does the damage.

Question 21.25 ★★ QR, DS, Analyst • any • junior

Show that the area under the ROC curve equals the chance that a random positive scores above a random negative, with ties counted as half. Positives score 0.90.9, 0.60.6, 0.40.4, and negatives score 0.70.7, 0.30.3, 0.20.2, 0.10.1. Compute the area by pair counting, and by rank sums.

Answer

Answer to Question 21.25.

The area is 10/12=0.83310/12 = 0.833 by each method.

Sort by score, and sweep the threshold down. Each positive raises the ROC curve by 1/n+1/n_+, and each negative moves it right by 1/n−1/n_-. The area under the staircase is a sum over negatives of the height when that negative is passed, 1/n−1/n_- times the share of positives ranked above it. So the area is

1n+n−∑+,−1(s+>s−),\frac{1}{n_+n_-}\sum_{+, -}\mathbf{1}(s_+ > s_-),

the share of pairs in the right order, with ties giving 12\frac12 from the diagonal segment.

Pairs: 0.90.9 beats all four negatives. 0.60.6 beats 0.30.3, 0.20.2, 0.10.1, which makes 3. 0.40.4 also beats those three. The total is 10 out of 12.

Ranks from the bottom: 0.1,0.2,0.30.1, 0.2, 0.3 take 1, 2, 3; 0.40.4 takes 4; 0.60.6 takes 5; 0.70.7 takes 6; 0.90.9 takes 7. The positives sum to 16. Then U=16−3×4/2=10U = 16 - 3 \times 4/2 = 10, the same count. A trapezoid sum on the ROC curve also gives 0.8330.833.

Classic wrong answer. Saying that the area is the accuracy at some threshold. It involves all thresholds, and it is about ordering pairs, not about classifying rows.

Follow-up. What happens to the area if you take the exponential of all scores? Nothing. It depends only on ranks, so a badly calibrated model can have a fine area.

Why it matters. The result gives a meaning to a number often quoted without one, and the rank-sum form is how it is computed in practice.

Question 21.26 ★★ QR, DS, QT • any • junior

A false alarm costs 1 and a miss costs 9. Above what calibrated probability should you act? Now a trade wins 0.5%0.5\% if right and loses 1% if wrong. Above what probability is it worth doing? What can go wrong if the scores are not calibrated?

Answer

Answer to Question 21.26.

Act above probability 0.10.1 in the first case and above 2/32/3 in the second. With uncalibrated scores, those thresholds do not mean what they say.

Act when the expected cost of acting is below the expected cost of not acting: (1−p)×1<p×9(1 - p) \times 1 < p \times 9, which gives p>1/10p > 1/10. In general, p∗=cFP/(cFP+cFN)p^* = c_{\text{FP}}/(c_{\text{FP}} + c_{\text{FN}}). A costly miss lowers the threshold.

For the trade, the expected value 0.5p−1(1−p)0.5p - 1(1 - p) is positive when p>1/1.5=2/3p > 1/1.5 = 2/3. At p=2/3p = 2/3, the expected value is exactly zero: 13−13\frac13 - \frac13.

These rules need the score to be a true probability. A score of 0.70.7 from an overconfident model may truly mean 0.550.55, in which case the trade loses money while looking safe. So check calibration: among rows with a score near 0.70.7, about 70% should be positive, on data from after the training period. Then either recalibrate, or pick the threshold directly from a validation period by measured profit.

Classic wrong answer. Using 12\frac12 by default, which is right only if the two errors cost the same. Or choosing the threshold that maximises accuracy when the costs are not equal.

Follow-up. What does a cost of 0.1%0.1\% per trade change? 0.5p−(1−p)−0.1>00.5p - (1 - p) - 0.1 > 0 gives p>1.1/1.5=0.733p > 1.1/1.5 = 0.733. Small costs raise the bar a long way when the win is small.

Why it matters. A prediction is only useful through a decision. It is a good sign when a candidate turns costs into a threshold and only then asks about calibration.

Question 21.27 ★★ QR, QT, DS • hedge fund, market maker • junior

A direction model is right on 52% of days, and each day’s move has the same size, 1 unit. What daily and annual Sharpe ratio does a daily position earn, using 252 days a year and no costs? What if each day’s trade costs 0.020.02 units? What cost per trade brings the Sharpe ratio to zero?

Answer

Answer to Question 21.27.

Daily Sharpe 0.040.04, annual 0.640.64. With the cost, the annual figure is 0.320.32. A cost of 0.040.04 brings it to zero.

The mean daily return is 0.52−0.48=0.040.52 - 0.48 = 0.04. The variance is 1−0.0421 - 0.04^2, so the standard deviation is 0.99920.9992. The daily Sharpe ratio is 0.040.04, and the annual one is 0.04252=0.6350.04\sqrt{252} = 0.635. A long simulation agrees.

A cost of 0.020.02 per trade halves the mean to 0.020.02, and halves the Sharpe ratio to 0.320.32. The volatility does not change. So the break-even cost is exactly the edge, 0.040.04.

Two lessons follow. Very modest hit rates matter: 52% looks like a coin and gives a respectable figure, if the bets are independent. And the edge per trade is so small that the cost easily decides everything. A model’s accuracy cannot be judged without knowing its turnover and its costs.

Classic wrong answer. Assuming that the Sharpe ratio from a hit rate alone is robust. The whole calculation relies on wins and losses having equal size, and that often fails.

Follow-up. What hit rate breaks even if wins are 0.90.9 the size of losses? 0.9p=1−p0.9p = 1 - p gives p=1/1.9=0.526p = 1/1.9 = 0.526. So a 52% model loses money.

Why it matters. This turns machine learning metrics into trading ones, and it is where a data scientist usually needs to convert units for the first time.

Question 21.28 ★★ QR, DS, QT • hedge fund • junior, experienced

Your label at each day is the total return of the following 20 days, and you have 1000 days. What is the correlation between labels kk days apart, under independent daily returns? For a test block of 200 days in the middle, how many training rows must go, so that no training label shares a day with a test label? Suppose the only feature is the date, and the model is 1-nearest neighbour. What does a random 5-fold split report on pure noise?

Answer

Answer to Question 21.28.

The correlation is 1−k/201 - k/20. You drop 38 rows, leaving 762. A random split reports a correlation above 0.90.9 on pure noise.

Labels kk days apart share 20−k20 - k of their 20 independent daily returns, so their correlation is (20−k)/20(20 - k)/20. At 5 days it is 0.750.75.

The test block holds days 400 to 599 in zero-based terms. The label at day tt uses days t+1t + 1 to t+20t + 20. A training label overlaps a test label if the two starts are less than 20 days apart. So the last 19 training rows before the block and the first 19 after it must go. That leaves 800−38=762800 - 38 = 762. Counting rows directly gives the same answer.

A random 5-fold split has neighbours of each test row in training, because only one row in five is held out. The nearest neighbour is usually 1 day away, with a correlation of 0.950.95. So, using the date alone, the model “predicts” pure noise with a correlation above 0.90.9 in a run. With blocks and purging, the same model gives a correlation close to zero over many runs. Nothing in the model has changed.

Classic wrong answer. Thinking that only the data before the test block need removing. Training labels after the block share days too, since a test label reaches forward. Or shuffling because the model has no time features. The leak is in the labels.

Follow-up. You also leave a gap of 5 days after the block, in case the features are autocorrelated. How many rows are left? 757. This is called an embargo, and its length comes from the memory of the features and not from the label.

Why it matters. This is the standard mistake in applying machine learning to returns. The expected answer contains the count, and the striking result on pure noise.

Question 21.29 ★★ QR, DS, QT • hedge fund • junior, experienced

A model predicts each stock’s open-to-close return on day tt. Which of these leak, and how? (a) Close-to-close return of day t−1t - 1. (b) The stock’s sector, using today’s classification, in a ten-year history. (c) Features standardised with the mean and variance of the whole sample. (d) Quarterly earnings placed on the last day of the fiscal quarter. (e) An indicator of whether the stock is in the index, using today’s members. (f) The volume of day tt.

Answer

Answer to Question 21.29.

(a) is fine; the rest leak. (b) is look-ahead in a slow variable, (c) is look-ahead in scale, (d) uses information not yet public, (e) is survivorship, (f) uses the future of the day being predicted.

(a) The previous close is known before the open of day tt, so this is a legitimate feature.

(b) A company’s current sector may reflect what it later became: a firm reclassified after its business took off carries that outcome back through history. This is usually small but real. Use the classification known at the time.

(c) The whole-sample mean and variance contain the test period. When the scale of a variable drifts, this tells the model about later values. Use training-period or trailing estimates.

(d) A fiscal quarter’s results are reported weeks after the quarter ends. Placing them on the last day of the quarter gives the model several weeks of foresight. Use the announcement date, and the first figures reported, not later restated ones.

(e) Today’s index members are the survivors and winners. Membership tells the model the stock will do well enough to remain. Use membership as it stood on each day.

(f) Day tt’s volume is known only at the close, and it is related to the size of the day’s move. It is a typical leak with an impressive backtest.

Classic wrong answer. Treating leakage as only using the label. Most leaks are about when a value was truly known, and a timestamp is needed for every feature.

Follow-up. How can a leak be detected with no list like this? Be suspicious of a result that is too good. Then shift each feature forward by a day and watch which ones lose nearly all their value, and train on shuffled labels to confirm that the pipeline gives no skill.

Why it matters. Finding leaks is a large part of the real job, and the example with an arguably mild case tests judgement as well as knowledge.

Question 21.30 ★★ QR, DS • any • junior

kk-means runs on the four points (±2,±0.5)(\pm 2, \pm 0.5), with k=2k = 2. Start the centres at (0,0.5)(0, 0.5) and (0,−0.5)(0, -0.5). What happens, and what is the sum of squares? What is the optimum? If the start is two different data points chosen at random, what is the chance of the bad result? With five independent restarts?

Answer

Answer to Question 21.30.

It stays at the top/bottom split, with a sum of squares of 16. The optimum is left/right, with sum 1. A random start falls into the bad result with chance 13\frac13, and five restarts all fail with chance 0.4%0.4\%.

Each point goes to the nearer centre, so the top two and the bottom two form clusters. Their means are the same centres (0,±0.5)(0, \pm 0.5). The algorithm has converged. Each point is 2 away from its centre horizontally, so the sum of squares is 4×4=164 \times 4 = 16.

The left and right split has centres (±2,0)(\pm 2, 0). Each point is 0.50.5 away, so the sum of squares is 4×0.25=14 \times 0.25 = 1, which is far better. Each step of the algorithm lowers the objective, but it only reaches a local minimum.

There are six pairs of data points to start from. Take the pair on the short left side, (−2,0.5)(-2, 0.5) and (−2,−0.5)(-2, -0.5). Then the right points (2,0.5)(2, 0.5) and (2,−0.5)(2, -0.5) go by height, and the bad top/bottom result appears. The same holds for the pair on the right side. The other four pairs lead to left/right, as a run of all six confirms. So the chance is 2/62/6, and five restarts all fail with chance (1/3)5=0.004(1/3)^5 = 0.004.

Classic wrong answer. Saying that kk-means finds the optimum because the objective falls at each step. A falling objective shows that it converges, not where it converges.

Follow-up. A smarter start draws the first centre at random, and then the next with probability proportional to squared distance. From (2,0.5)(2, 0.5), what is the chance of the bad pair? 1/(1+16+17)=1/341/(1 + 16 + 17) = 1/34, or about 3%. The squared distance favours far points, and this rule is the kk-means++ start.

Why it matters. Algorithms that stop are not algorithms that succeed. This small example gives an exact account of why restarts and careful starts are used.

Question 21.31 ★★★ QR, DS • hedge fund • junior, experienced

You have 50 rows, balanced random labels and 5000 pure-noise features. You keep the 100 features most correlated with the labels on all the data, then run 5-fold cross-validation of a nearest-centroid classifier on those 100. What error does this report, and what is the truth? Give the right procedure, and show the difference by a run.

Answer

Answer to Question 21.31.

The cross-validation reports an error under 5%, close to zero, and the true error is 50%. Feature selection belongs inside each fold.

With 5000 noise features and only 50 rows, some features are correlated with the labels by chance. The top 100 are selected using all rows, including those later held out. So, in each fold, the features already know the held-out labels. A nearest-centroid classifier then has an easy job.

The right procedure treats selection as part of the model. In each fold, select the 100 features using only the training rows, fit on those rows, and predict the held-out rows. Now the held-out rows’ labels have no effect on the features, and the error is about 50%, as it must be, since the labels are random.

A run over 40 random datasets gives a mean below 5% with the wrong procedure, and 50%50\%, up to noise, with the right one. Nothing else differs.

The same mistake appears when target-dependent preprocessing of any kind is done first: target encoding, resampling, choosing the universe by later performance, or choosing the tuning range by looking at full-sample results.

Classic wrong answer. Thinking that, since the classifier is trained only on training folds, the validation is honest. The classifier is only the last step. Everything that saw the labels counts.

Follow-up. Is it also a leak to drop features with low variance before cross-validation? No, with respect to the labels, since that filter does not use them. Over time, though, using the variance of the whole sample does leak some scale information.

Why it matters. This is a very common error in the field, with a dramatic result. The candidate is expected to say at once where the screen belongs.

Question 21.32 ★★★ QR, QT, DS • hedge fund • experienced

The true annual Sharpe ratios of a set of candidate signals are normal, centred on 0, with a standard deviation of 0.50.5, and a backtest measures each one with noise of standard deviation 1. You test 100 of them independently and select the best. What Sharpe ratio do you expect to measure on it, and what is its expected true Sharpe ratio? How do the numbers change with four times as much history?

Answer

Answer to Question 21.32.

You measure about 2.802.80, and the expected true Sharpe ratio is 0.560.56. With four times the history, the figures are 1.771.77 and 0.890.89.

Measured values are normal with variance τ2+σ2=0.25+1=1.25\tau^2 + \sigma^2 = 0.25 + 1 = 1.25. The largest of 100 independent standard normals is 2.512.51 on average, so the best measured value is 2.51×1.25=2.802.51 \times \sqrt{1.25} = 2.80.

Given a measured value mm, the true value has mean τ2τ2+σ2m=0.2m\frac{\tau^2}{\tau^2 + \sigma^2}m = 0.2m. Selection depends only on measured values, so this applies to the winner too, and 0.2×2.80=0.560.2 \times 2.80 = 0.56. So 80% of the measured Sharpe ratio is noise, and it will not come back. A simulation of 200 000 such contests gives 2.802.80 and 0.560.56.

With four times the history, the noise’s standard deviation halves, to 0.50.5. Now the variance of the measure is 0.50.5, and the best measured value is 2.51×0.707=1.772.51 \times 0.707 = 1.77. The shrinkage factor is 12\frac12, which gives 0.890.89. So the measured figure falls, and the true one rises: better evidence gives a smaller, more real number.

In the limit of very noisy measurement, the factor goes to zero, and the winner is no better than the average candidate, as it should be. With perfect measurement, the factor is 1, and the winner’s true value is 0.5×2.51=1.250.5 \times 2.51 = 1.25.

Classic wrong answer. Dividing by 100\sqrt{100}, or by the number of trials, as a rule of thumb. The right haircut depends on the prior and on the amount of data, and the number of trials only enters through the size of the maximum.

Follow-up. If true Sharpe ratios had a prior mean of −0.2-0.2, after costs, what is the winner’s expected true value? Roughly −0.2+0.2×2.80=0.36-0.2 + 0.2 \times 2.80 = 0.36. A negative prior mean takes off its full amount, because the measured deviations are about the mean.

Why it matters. A compact model of research: many ideas, noisy tests, and a winner’s curse. It gives a defensible number for how much to believe a backtest.

Question 21.33 ★★★ QR, DS, QT • hedge fund • junior, experienced

A slowly moving mean follows a random walk with innovation variance q=0.0001q = 0.0001, and you observe it with noise variance 1. You forecast its next value by the mean of the last ww observations. Derive the forecast’s mean squared error as a function of ww, and the best ww. How sensitive is the answer to ww? What does this say about choosing a training window?

Answer

Answer to Question 21.33.

The error is 1/w+q(w+1)(2w+1)/(6w)1/w + q(w + 1)(2w + 1)/(6w), with the minimum at w≈3/q=173w \approx \sqrt{3/q} = 173, where it equals 0.01160.0116. The curve is flat near the minimum.

The forecast uses the mean of the last ww observations to forecast the level one step beyond. The observation noise contributes σ2/w=1/w\sigma^2/w = 1/w. For the level, the forecast error is a weighted sum of random-walk steps. The most recent step is missed entirely, with weight 1, the one before with weight (w−1)/w(w - 1)/w, and so on down to 1/w1/w. The variance is

q∑k=1w(k/w)2=q(w+1)(2w+1)6w.q\sum_{k = 1}^{w}(k/w)^2 = q\frac{(w + 1)(2w + 1)}{6w}.

For large ww, the sum of the two parts is about 1/w+qw/31/w + qw/3, with its minimum at w=3/q=173w = \sqrt{3/q} = 173. A search over integers gives 173, and a simulation gives the same error of 0.01160.0116.

The sensitivity is low. At w=100w = 100 or w=300w = 300 the error rises by only 15%. So a window can be off by a factor of nearly 2 without much harm, and the two limiting cases are clear: as q→0q \to 0, use all the data, and as qq grows, the window shrinks.

The lesson for training windows is that the right length is set by how fast the relation drifts relative to its noise. Since neither is known well, tuning this finely by backtest is likely to overfit.

Classic wrong answer. Saying that more data is always better, or choosing the window that performed best historically to many decimal places. The flat minimum means that the choice cannot be determined well, and doesn’t need to be.

Follow-up. What does exponential weighting achieve here? The optimal filter has gain about q=0.01\sqrt{q} = 0.01, which is a half-life of 69 steps, and an error of 0.010050.01005, 13% below the best window. It discounts old data smoothly, and it is the steady-state Kalman filter for this model.

Why it matters. Every model on non-stationary data has to choose a window. Few candidates can derive one and say how much the choice matters.

Question 21.34 ★★★ QR, DS, QT • hedge fund • junior, experienced

Scores are normal with variance 1, with mean 0 for negatives and mean dd for positives. Derive the area under the ROC curve. What are the areas at d=0.1d = 0.1, 0.50.5 and 1? A return model reports an area of 0.550.55 on balanced classes. What is dd, and what correlation does it imply between the score and the label?

Answer

Answer to Question 21.34.

The area is Φ(d/2)\Phi(d/\sqrt{2}), which gives 0.5280.528, 0.6380.638 and 0.7600.760. An area of 0.550.55 means d=0.178d = 0.178, and a correlation of 0.0890.089 with the label.

The area is the chance that a positive beats a negative. The difference between the positive’s score and the negative’s is normal, with mean dd and variance 2. So the chance that it is positive is Φ(d/2)\Phi(d/\sqrt{2}).

For the second part, invert: d=2 Φ−1(0.55)=2×0.1257=0.178d = \sqrt{2}\,\Phi^{-1}(0.55) = \sqrt{2} \times 0.1257 = 0.178.

For balanced classes, the label y∈{0,1}y \in \{0, 1\} has variance 14\frac14. The score has variance 1+d2/41 + d^2/4, as the mixture of means adds d2/4d^2/4. The covariance between them is d/4d/4. So

corr⁡=d/4121+d2/4=d/21+d2/4=0.089.\operatorname{corr} = \frac{d/4}{\frac12\sqrt{1 + d^2/4}} = \frac{d/2}{\sqrt{1 + d^2/4}} = 0.089.

A simulation confirms both 0.0890.089 and the area of 0.550.55. At d=0d = 0 the area is 12\frac12, and the correlation is zero, as they must be.

In terms of return prediction, a correlation of 0.090.09 with the sign of the return is a large effect. So an area of 0.550.55, which sounds weak to someone used to images and text, is very strong if real, and it deserves suspicion.

Classic wrong answer. Using the benchmarks from other fields, where 0.550.55 is a failure. Or equating the correlation with the area’s excess over 12\frac12.

Follow-up. What accuracy does that model reach at the midpoint threshold? Φ(d/2)=0.535\Phi(d/2) = 0.535. Directional accuracy of 53.5%53.5\% corresponds to the area of 0.550.55.

Why it matters. Converting between metrics is how results are compared across teams. It also calibrates what counts as impressive in finance.

Question 21.35 ★★★ QR, DS, Risk • any • junior, experienced

You keep every positive but only 10% of the negatives, chosen at random, and then train a probabilistic classifier. It outputs 0.50.5 and 0.90.9 on two rows. What are the correct probabilities for the original population? What changes in a logistic regression, and what does not? Derive the formula.

Answer

Answer to Question 21.35.

The corrected probabilities are 0.0910.091 and 0.4740.474. In a logistic regression, the correction changes only the intercept, by ln⁡0.1=−2.30\ln 0.1 = -2.30, and not the slopes.

Let β=0.1\beta = 0.1 be the share of negatives kept. Keeping is independent of the features, given the class. So Bayes’ rule gives

p′1−p′=P(y=1∣x)β P(y=0∣x)=1β⋅p1−p.\frac{p'}{1 - p'} = \frac{P(y = 1 \mid x)}{\beta\,P(y = 0 \mid x)} = \frac{1}{\beta}\cdot\frac{p}{1 - p}.

So the odds on the sampled data are ten times the true odds, whatever xx is, and the correction is p=βp′/(βp′+1−p′)p = \beta p'/(\beta p' + 1 - p').

At p′=0.5p' = 0.5, the sampled odds are 1, and the true odds are 0.10.1, so p=0.1/1.1=0.091p = 0.1/1.1 = 0.091. At p′=0.9p' = 0.9, the sampled odds are 9, and the true odds are 0.90.9, so p=0.9/1.9=0.474p = 0.9/1.9 = 0.474. A row the model calls 90%90\% is a coin flip.

In logistic regression, the log-odds are linear in xx, and sampling shifts them by the constant −ln⁡β-\ln\beta. So the sampled fit has the same slopes, with intercept up by ln⁡10=2.30\ln 10 = 2.30, and the correction subtracts that. A run with 400 000 rows, an intercept of −3-3 and a slope of 1 returns slope 1.01.0 and intercept −0.70-0.70, as predicted.

The result relies on keeping being independent of xx given the class. A filter that also depends on the features breaks it, and then the shift is not constant. Ranking metrics do not change under this correction, while the probabilities change a lot, so any decision rule needs them corrected.

Classic wrong answer. Using scores from the balanced data directly as probabilities in a cost rule. Or applying a uniform rescaling of the probability, as opposed to the odds.

Follow-up. What is an alternative to correcting afterwards? Weight each kept negative by 10 in the loss. The weighted fit estimates the original population directly, with no correction, but the estimates are noisier than with all the data.

Why it matters. Undersampling is common for rare events. Many pipelines report badly calibrated numbers, because this step is forgotten.

Question 21.36 ★★★ QR, DS • any • junior, experienced

Gradient boosting with log loss starts on a dataset with 60 positives out of 100. Find the initial log-odds, and the gradient and Hessian of each row. A tree isolates a leaf of 30 positives and 10 negatives. Find the Newton leaf value, and compare it with the exact optimum for that leaf. With shrinkage 0.10.1, what is the leaf’s new probability?

Answer

Answer to Question 21.36.

The initial log-odds are ln⁡1.5=0.405\ln 1.5 = 0.405. The Newton leaf value is 0.6250.625, the exact optimum is 0.6930.693, and the new probability is 0.6150.615.

With FF the log-odds and p=σ(F)p = \sigma(F), the loss on a row is −yln⁡p−(1−y)ln⁡(1−p)-y\ln p - (1 - y)\ln(1 - p). Its gradient in FF is p−yp - y, and its Hessian is p(1−p)p(1 - p). The best constant is the base rate, so F0=ln⁡(0.6/0.4)F_0 = \ln(0.6/0.4).

At p=0.6p = 0.6, a positive has gradient −0.4-0.4, a negative has +0.6+0.6, and every row has Hessian 0.240.24.

For the leaf: G=30(−0.4)+10(0.6)=−6G = 30(-0.4) + 10(0.6) = -6, and H=40(0.24)=9.6H = 40(0.24) = 9.6. The Newton step is −G/H=0.625-G/H = 0.625.

The exact optimum makes the leaf’s probability equal its share of positives, 34\frac34, whose log-odds are ln⁡3=1.099\ln 3 = 1.099. So the exact step is 1.099−0.405=0.6931.099 - 0.405 = 0.693, and a direct search agrees. Newton falls about 10% short here, and it improves in later rounds.

With shrinkage 0.10.1, the update is F=0.405+0.0625=0.468F = 0.405 + 0.0625 = 0.468, so p=0.615p = 0.615, up from 0.60.6, on the way to the leaf’s 0.750.75.

Classic wrong answer. Using the raw residual mean, 6/40=0.156/40 = 0.15, as the leaf value. That is a step on the probability scale, and not the log-odds one. Or forgetting the Hessian, which is what converts between them.

Follow-up. The other leaf has 30 positives and 30 negatives. What is its Newton value, and the exact one? Newton gives −6/14.4=−0.417-6/14.4 = -0.417. The exact step is ln⁡1−0.405=−0.405\ln 1 - 0.405 = -0.405. Here Newton slightly overshoots.

Why it matters. Second-order boosting is the standard tabular tool, and few can compute one step by hand. Doing so settles what is actually fitted at a leaf.

Question 21.37 ★★★ QR, DS • any • junior, experienced

A second-order boosting library approximates the loss in a leaf by Gw+12(H+λ)w2Gw + \frac12(H + \lambda)w^2, where GG and HH are the sums of the gradients and Hessians, and ww is the leaf’s value. Derive the best ww and the gain from a split. Compare, with λ=1\lambda = 1, the split (GL,HL)=(−10,20)(G_L, H_L) = (-10, 20) and (GR,HR)=(10,20)(G_R, H_R) = (10, 20) with the split (−10,1)(-10, 1) and (10,39)(10, 39). Which does it prefer, and what setting guards against this choice?

Answer

Answer to Question 21.37.

w∗=−G/(H+λ)w^* = -G/(H + \lambda), with gain 12(GL2HL+λ+GR2HR+λ−(GL+GR)2HL+HR+λ)\frac12\bigl(\frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{(G_L + G_R)^2}{H_L + H_R + \lambda}\bigr). The gains are 4.764.76 and 26.2526.25, so the library prefers the unbalanced split. A minimum Hessian in each child guards against it.

Minimising the quadratic over ww gives w∗=−G/(H+λ)w^* = -G/(H + \lambda), and the minimum is −12G2/(H+λ)-\frac12G^2/(H + \lambda). The gain from a split is the parent’s minimum minus the children’s, which is the formula above. A constant charge per leaf can be subtracted too.

Here both parents have G=0G = 0, so the last term vanishes.

Split one: 12(100/21+100/21)=4.76\frac12(100/21 + 100/21) = 4.76, with leaf values ±0.476\pm 0.476.

Split two: 12(100/2+100/40)=26.25\frac12(100/2 + 100/40) = 26.25, with a left leaf value of 10/2=510/2 = 5.

So the second wins by a wide margin, and it rests on a Hessian of 1, which is very little evidence: a few rows at most. Its leaf value is more than ten times larger. A search over the quadratic confirms the leaf’s value of 5.

A larger λ\lambda helps, but even λ=10\lambda = 10 leaves the preference: the gains are 3.333.33 and 5.575.57. The direct guard is a minimum sum of Hessians per child. A limit of 5 rejects split two outright. At λ=0\lambda = 0, the second gain is 51.2851.28, so the regulariser is doing a good deal already.

Classic wrong answer. Thinking that λ\lambda is only a penalty on leaf size that doesn’t affect split choice. It appears in the gain, as shown.

Follow-up. Why does the Hessian measure evidence? With squared loss, each row has Hessian 1, so HH is the row count. With log loss, a row has p(1−p)p(1 - p), so rows the model is already sure of count for almost nothing.

Why it matters. This is the formula inside the standard libraries, and a parameter people set by habit. Candidates who can derive the gain understand what they are tuning.

Question 21.38 ★★★ QR, DS, QD • any • junior, experienced

Prove that for least squares the leave-one-out residual is ei/(1−hii)e_i/(1 - h_{ii}), where eie_i is the ordinary residual and hiih_{ii} is the leverage. Then fit a line with an intercept to x=0,1,2,3,10x = 0, 1, 2, 3, 10 and y=0,1,2,3,0y = 0, 1, 2, 3, 0, and compute the leave-one-out residual of the last point both by formula and from its meaning.

Answer

Answer to Question 21.38.

The result follows from the Sherman–Morrison formula, and the last point’s leave-one-out residual is −10-10 by both routes.

Let A=X⊤XA = X^\top X and let xix_i be row ii. Removing the row gives A−i=A−xixi⊤A_{-i} = A - x_ix_i^\top. The Sherman–Morrison formula gives

A−i−1=A−1+A−1xixi⊤A−11−hii,hii=xi⊤A−1xi.A_{-i}^{-1} = A^{-1} + \frac{A^{-1}x_ix_i^\top A^{-1}}{1 - h_{ii}}, \qquad h_{ii} = x_i^\top A^{-1}x_i.

Then β^−i=A−i−1(X⊤y−xiyi)\hat{\beta}_{-i} = A_{-i}^{-1}(X^\top y - x_iy_i). Multiplying out and simplifying,

β^−i=β^−A−1xiei1−hii.\hat{\beta}_{-i} = \hat{\beta} - \frac{A^{-1}x_ie_i}{1 - h_{ii}}.

So yi−xi⊤β^−i=ei+hiiei/(1−hii)=ei/(1−hii)y_i - x_i^\top\hat{\beta}_{-i} = e_i + h_{ii}e_i/(1 - h_{ii}) = e_i/(1 - h_{ii}). It needs only one fit.

On the data: xˉ=3.2\bar{x} = 3.2, ∑(x−xˉ)2=62.8\sum(x - \bar{x})^2 = 62.8, and the slope is −5.2/62.8=−0.083-5.2/62.8 = -0.083. The fitted value at 10 is 0.6370.637, so e5=−0.637e_5 = -0.637. The leverage is 15+46.24/62.8=0.9363\frac15 + 46.24/62.8 = 0.9363. The formula gives −0.637/0.0637=−10-0.637/0.0637 = -10.

From its meaning: without the last point, the other four lie exactly on y=xy = x. That line predicts 10 at x=10x = 10, while y=0y = 0. So the residual is 0−10=−100 - 10 = -10, which agrees. Brute-force refits match at all five rows.

The ordinary residual looks small because this point pulls the line onto itself. Its leverage is 0.940.94, out of a sum of 22 over the five points.

Classic wrong answer. Judging outliers from ordinary residuals. A high-leverage point can have a tiny residual, which is why the ratio matters.

Follow-up. Generalised cross-validation replaces hiih_{ii} by its mean p/np/n. What does this give for the last row? −0.637/(1−2/5)=−1.06-0.637/(1 - 2/5) = -1.06, which is a tenth of the true size. It is a good estimate of the average, but it hides exactly this kind of point.

Why it matters. This is an elegant result with immediate use, as cross-validation for linear models is then free. The small example shows how much a good residual can hide.

Question 21.39 ★★★ QR, DS • any • junior, experienced

In linear regression, each input is multiplied at random by δj/q\delta_j/q, where δj\delta_j equals 1 with probability qq and 0 otherwise, a form of dropout. Show that the expected squared loss is a ridge penalty on the coefficients, and find its weights. For uncorrelated features with ∑ixij2=n\sum_i x_{ij}^2 = n, how do the coefficients compare with ordinary least squares at q=0.5q = 0.5 and q=0.8q = 0.8?

Answer

Answer to Question 21.39.

The expected loss is the ordinary squared loss plus 1−qq∑jβj2∑ixij2\frac{1 - q}{q}\sum_j\beta_j^2\sum_ix_{ij}^2. In the example the coefficients are qq times the least squares ones: half at q=0.5q = 0.5, and 0.80.8 of them at q=0.8q = 0.8.

For one row, write y~i=∑jxijβjδij/q\tilde{y}_i = \sum_j x_{ij}\beta_j\delta_{ij}/q. Since E[δij/q]=1\mathbb{E}[\delta_{ij}/q] = 1, the mean of y~i\tilde{y}_i is xi⊤βx_i^\top\beta, the ordinary prediction. So

E(yi−y~i)2=(yi−xi⊤β)2+Var⁡(y~i),\mathbb{E}(y_i - \tilde{y}_i)^2 = (y_i - x_i^\top\beta)^2 + \operatorname{Var}(\tilde{y}_i),

which is the bias–variance split for a single prediction. The variance of δ/q\delta/q is (1−q)/q(1 - q)/q, and the δij\delta_{ij} are independent, so the variance is 1−qq∑jxij2βj2\frac{1 - q}{q}\sum_jx_{ij}^2\beta_j^2. Summing over rows gives the stated penalty. A sampling check of the expected loss, with 200 000 masks, agrees to within 1%.

For uncorrelated features with ∑ixij2=n\sum_ix_{ij}^2 = n, the penalty is λ∥β∥2\lambda\|\beta\|^2 with λ=n(1−q)/q\lambda = n(1 - q)/q. So the solution is

β^j=xj⊤yn+λ=nn+n(1−q)/qβ^jOLS=q β^jOLS.\hat{\beta}_j = \frac{x_j^\top y}{n + \lambda} = \frac{n}{n + n(1 - q)/q}\hat{\beta}^{\text{OLS}}_j = q\,\hat{\beta}^{\text{OLS}}_j.

At q=1q = 1, there is no change, as expected, and as q→0q \to 0, the coefficients go to zero.

Note that the penalty on each coefficient is weighted by the size of its column. So dropout is not ridge with a single λ\lambda, unless columns are standardised, and that weighting makes it insensitive to a column’s units.

Classic wrong answer. Saying that dropout reduces the model’s output by the factor qq at test time. With this scaling the mean is unchanged, and the shrinkage comes from the variance, through the penalty.

Follow-up. What does this say about dropout on rare features? A feature that is mostly zero has a small ∑xij2\sum x_{ij}^2, so its coefficient is lightly penalised. Unlike plain ridge, dropout goes easy on rare features that are strong when present.

Why it matters. This turns a technique that feels like a hack into a calculation. The bias-variance step is short and is what a good candidate uses.

Question 21.40 ★★★ QR, DS, QD • any • junior, experienced

With one input on [0,1][0, 1], a one-hidden-layer ReLU network with nn units gives at most how many linear pieces? Write the tent map, T(x)=2xT(x) = 2x on the first half and 2−2x2 - 2x on the second, with two ReLU units. How many pieces does the map composed with itself dd times have? Compare the number of units needed by the deep network and by the shallow one at d=10d = 10.

Answer

Answer to Question 21.40.

A shallow network with nn units has at most n+1n + 1 pieces. The dd-fold tent map has 2d2^d pieces and uses 2d2d units. At d=10d = 10 this means 20 units deep, against 1023 units shallow.

Each ReLU unit r(ax+b)r(a x + b) has one kink, and the output is a sum of them, plus a constant. So there are at most nn kinks, and n+1n + 1 pieces.

The tent map on [0,1][0, 1] is T(x)=2r(x)−4r(x−12)T(x) = 2r(x) - 4r(x - \frac12). Check: below 12\frac12, the second term vanishes, and it equals 2x2x. Above 12\frac12, it gives 2x−4x+2=2−2x2x - 4x + 2 = 2 - 2x. So two units per layer.

Under composition, TT maps each of its two pieces onto all of [0,1][0, 1], so a function with mm linear pieces that each cover [0,1][0, 1] becomes one with 2m2m. Thus T∘dT^{\circ d} has 2d2^d pieces, a sawtooth with 2d−12^{d - 1} teeth. A count of slope changes on a fine grid confirms it up to d=10d = 10.

To match this exactly, a shallow network needs at least 2d−12^d - 1 kinks. For d=10d = 10, that is 1023 units, against 20. The depth gives exponential economy, on this function. It does not say that typical functions need depth, nor that training will find such weights.

Classic wrong answer. Claiming that universal approximation with one layer means depth is pointless. Universal approximation says nothing about how many units are needed.

Follow-up. What about d=30d = 30? Sixty units in depth, against 230−12^{30} - 1, which is more than a billion units in one layer.

Why it matters. This is the cleanest proof of why depth helps, and it can be done by hand in minutes. It also tests whether the candidate knows the limits of the claim.

Question 21.41 ★★★ QR, DS • hedge fund • junior, experienced

For the lasso, with objective 12n∥y−Xβ∥2+λ∥β∥1\frac{1}{2n}\|y - X\beta\|^2 + \lambda\|\beta\|_1 and standardised columns, show that all coefficients are zero exactly when λ≥max⁡j∣xj⊤y∣/n\lambda \ge \max_j|x_j^\top y|/n. Take n=1000n = 1000, p=1000p = 1000, independent columns and pure-noise yy of variance 1. What is this threshold about? What does it say about choosing λ\lambda when the signal is weak?

Answer

Answer to Question 21.41.

The threshold is about 0.110.11, close to the rule of thumb 2ln⁡p/n=0.118\sqrt{2\ln p/n} = 0.118. On pure noise, any λ\lambda below it lets noise features in, and with weak signals it can hide the real ones.

At β=0\beta = 0, the objective’s smooth part has gradient −X⊤y/n-X^\top y/n. The subgradient of λ∣βj∣\lambda|\beta_j| at 0 is any value in [−λ,λ][-\lambda, \lambda]. So β=0\beta = 0 is optimal, by convexity, exactly when ∣xj⊤y∣/n≤λ|x_j^\top y|/n \le \lambda for all jj. That gives the threshold, called λmax⁡\lambda_{\max}.

With pure noise, each xj⊤y/nx_j^\top y/n is about normal, with standard deviation 1/n1/\sqrt{n}. The largest absolute value of 1000 such normals is on average 3.433.43 standard deviations. So λmax⁡≈3.43/1000=0.108\lambda_{\max} \approx 3.43/\sqrt{1000} = 0.108. The upper envelope 2ln⁡p/n=0.118\sqrt{2\ln p/n} = 0.118 overstates this slightly at p=1000p = 1000. A run gives a value in this range, an all-zero fit just above it, some nonzero coefficients at 0.9λmax⁡0.9\lambda_{\max}, and more than 50 nonzero at half of it, on pure noise.

So this level is the floor at which noise stops coming in. A true signal is detected only if ∣xj⊤y∣/n|x_j^\top y|/n exceeds it. With a coefficient of 0.050.05 in this setup, a real feature contributes about 0.050.05, which lies below the noise’s maximum. So at this level the lasso finds nothing, and a lower λ\lambda picks up noise as well as signal. With weak signals in many features, it cannot separate them, and ridge often predicts better.

Classic wrong answer. Reading selected features as true ones. On pure noise, cross-validation can pick a λ\lambda that keeps several features.

Follow-up. How does the threshold scale if pp grows to 10610^6? Only with ln⁡p\sqrt{\ln p}. The envelope goes from 3.723.72 to 5.265.26 standard deviations, so it rises by about 40%, which is why screening many features is not as costly as it may seem, for this one number.

Why it matters. The derivation is short and gives a number with immediate use: how large a signal has to be, before a sparse method can see it.

Question 21.42 ★★★ QR, DS, QT • hedge fund • junior, experienced

A random forest uses a real feature, an exact copy of it, and a useless feature with a different value on every row. What do impurity importance and held-out permutation importance say about the real feature and its copy? What about the useless feature? How would you assess a group of correlated features?

Answer

Answer to Question 21.42.

Impurity importance divides the real feature’s score between the two copies and gives the useless row-identifier a large share. Held-out permutation importance gives the identifier about zero, and understates each copy. Permute correlated features as a group.

Impurity importance sums the decreases in impurity from splits on each feature, measured on the training rows. With two copies, a tree chooses either at each split, so the credit is divided about evenly. Each copy appears to be worth about half.

A feature with a different value on every row offers many possible splits. Deep trees can use it to isolate noisy training rows, and each such split lowers training impurity. So it earns real importance, even with no information. In a run, it takes more than 10% of the total.

Permutation importance measures how much the score falls on held-out data when a column is shuffled. The row identifier has no value on new data, so the fall is close to zero. That is the right reading.

But when one copy is shuffled, the forest can still use the other copy, so a real feature can look less important than it is. A run shows that the per-copy value falls below three quarters of the single-feature value.

The remedy for correlated features is to permute a group together. In the run, this recovers more than 80% of the single-feature value. Dropping and refitting the group gives a more expensive and cleaner answer. Do this on later data, for financial uses, and report the result by groups, not one by one.

Classic wrong answer. Dropping a feature because its importance is low, when it has a close relative. A strong signal shared across several columns can look like several weak ones.

Follow-up. What does importance not say? It does not say that the feature causes anything, or that it will last, or the direction of its effect. It describes how this model uses this column on this sample.

Why it matters. Most candidates print these charts. Few can say when they lie, or what to do about it.

Question 21.43 ★★★★ QR, DS • hedge fund • experienced

Regress pure noise of variance 1, yy independent of the features, on pp independent standard normal features, using n=100n = 100 rows and least squares, taking the minimum-norm solution when p>np > n. Derive the expected test error on a new row as a function of pp, for pp below and above nn. Evaluate it at p=50,90,110,200,1000p = 50, 90, 110, 200, 1000. Why does it peak, and why does it fall again?

Answer

Answer to Question 21.43.

The test error is 1+p/(n−p−1)1 + p/(n - p - 1) for p<n−1p < n - 1, and 1+n/(p−n−1)1 + n/(p - n - 1) for p>n+1p > n + 1. The values are 2.022.02, 1111, 12.112.1, 2.012.01 and 1.111.11.

The new row xx is independent of the fit, and yy has variance 1 and is unrelated to xx. Then the test error is 1+E∥β^∥21 + \mathbb{E}\|\hat{\beta}\|^2, since E(x⊤β^)2=∥β^∥2\mathbb{E}(x^\top\hat{\beta})^2 = \|\hat{\beta}\|^2 for standard normal xx.

For p<np < n: β^=(X⊤X)−1X⊤e\hat{\beta} = (X^\top X)^{-1}X^\top e, so, using e⊥Xe \perp X, E∥β^∥2=tr⁡E(X⊤X)−1\mathbb{E}\|\hat{\beta}\|^2 = \operatorname{tr}\mathbb{E}(X^\top X)^{-1}. X⊤XX^\top X is Wishart, and the mean of its inverse is I/(n−p−1)I/(n - p - 1). So the term is p/(n−p−1)p/(n - p - 1).

For p>np > n: the minimum-norm solution is β^=X⊤(XX⊤)−1e\hat{\beta} = X^\top(XX^\top)^{-1}e, so ∥β^∥2=e⊤(XX⊤)−1e\|\hat{\beta}\|^2 = e^\top(XX^\top)^{-1}e. Here XX⊤XX^\top is Wishart of size nn with pp degrees of freedom, so the term is n/(p−n−1)n/(p - n - 1).

At p=50p = 50: 1+50/491 + 50/49. At 9090: 1+90/9=111 + 90/9 = 11. At 110110: 1+100/9=12.11 + 100/9 = 12.1. At 200200: 1+100/99=2.011 + 100/99 = 2.01. At 10001000: 1+100/899=1.111 + 100/899 = 1.11. Simulations match to within a few percent, and to within 10% at p=90p = 90, where the tails are heavy.

The peak is at p≈np \approx n. There is then exactly one solution through the nn points, and fitting pure noise demands huge coefficients, as the matrix is nearly singular. Beyond nn, there are many interpolators, and taking the smallest spreads the noise over many directions, each with a small coefficient. As p→∞p \to \infty, β^→0\hat{\beta} \to 0 in size, and the error approaches 1, the noise level.

Classic wrong answer. Concluding that more features are free. This calculation has no signal. If the true β\beta has size rr, spread evenly, a term r2(1−n/p)r^2(1 - n/p) appears for p>np > n, since the fit can only see the nn-dimensional part.

Follow-up. With true signal size r=1r = 1 and no noise, what is that term at p=200p = 200? 1×(1−100/200)=0.51 \times (1 - 100/200) = 0.5. A run gives 0.500.50. So half the signal’s energy is simply out of sight.

Why it matters. This is the simplest exact form of a result that overturned the usual picture. The candidate should derive it and avoid both extreme conclusions.

Question 21.44 ★★★★ QR, DS • hedge fund • experienced

Two normal classes have identity covariance in pp dimensions, and their means differ by a vector of length 2 lying in the first coordinate only, so that p−1p - 1 features are useless. The classes are equally likely. You estimate the means from 50 rows per class, and classify using the hyperplane midway between the estimated means. Derive the approximate test error as a function of pp, and evaluate it at p=1p = 1, 100 and 1000. What is the error with the known means?

Answer

Answer to Question 21.44.

The error is about Φ(−2/4+2p/n)\Phi\bigl(-2/\sqrt{4 + 2p/n}\bigr), which gives 0.1600.160, 0.2400.240 and 0.3820.382. The error with known means is Φ(−1)=0.159\Phi(-1) = 0.159.

With known means, the rule is optimal, and in the direction joining them each class is normal with variance 1, at distance Δ/2=1\Delta/2 = 1 from the midpoint. So the error is Φ(−Δ/2)\Phi(-\Delta/2).

With estimated means, let w=μ^1−μ^0=δ+εw = \hat{\mu}_1 - \hat{\mu}_0 = \delta + \varepsilon, where δ\delta is the true difference and ε\varepsilon has independent entries of variance 2/n2/n. Classify a new xx from class 1 by the sign of w⊤(x−m^)w^\top(x - \hat{m}), where m^\hat{m} is the midpoint of the estimates.

Given the estimates, the score is normal with variance ∥w∥2\|w\|^2 and mean w⊤(μ1−m^)w^\top(\mu_1 - \hat{m}). Now μ1−m^=δ/2−η\mu_1 - \hat{m} = \delta/2 - \eta, with η\eta a small noise, independent of ε\varepsilon. To leading order, the mean is w⊤δ/2≈Δ2/2w^\top\delta/2 \approx \Delta^2/2, as the cross terms average to zero and are small. And ∥w∥2≈Δ2+2p/n\|w\|^2 \approx \Delta^2 + 2p/n, since each of the pp noise entries adds 2/n2/n.

So the error is

Φ(−Δ2/2Δ2+2p/n)=Φ(−24+2p/n),\Phi\left(-\frac{\Delta^2/2}{\sqrt{\Delta^2 + 2p/n}}\right) = \Phi\left(-\frac{2}{\sqrt{4 + 2p/n}}\right),

with Δ=2\Delta = 2 and n=50n = 50. The values are as stated. A simulation with these values matches at each pp. As p→∞p \to \infty with nn fixed, the error goes to 12\frac12, and as n→∞n \to \infty it goes to Φ(−1)\Phi(-1).

The conclusion: useless features actively hurt. The noise in the estimated direction adds 2p/n2p/n to the squared length, and only the Δ2\Delta^2 part is signal. With 1000 features and 50 rows per class, the classifier’s direction is mostly noise. This is why feature selection or shrinkage matters so much at low signal, and a chance-level result does not need a bug to explain it.

Classic wrong answer. Saying that extra features cannot hurt, since their weights will simply be near zero. Each weight is small, but there are many, and together they have more length than the signal.

Follow-up. At what pp does the error reach 30%? 2/4+p/25=Φ−1(0.7)=0.5242/\sqrt{4 + p/25} = \Phi^{-1}(0.7) = 0.524 gives p≈264p \approx 264. With 100 rows, this means about 260 features, of which one is real.

Why it matters. An exact and memorable reason for why more features can worsen a model. The derivation uses only a mean and a variance, once the score has been written down.

Question 21.45 ★★★★ QR, DS • hedge fund • experienced

Prove that AdaBoost’s training error is at most ∏t2εt(1−εt)\prod_t 2\sqrt{\varepsilon_t(1 - \varepsilon_t)}, where εt\varepsilon_t is the weighted error at round tt, and that this is at most exp⁡(−2∑tγt2)\exp(-2\sum_t\gamma_t^2), with γt=12−εt\gamma_t = \frac12 - \varepsilon_t. If every round has ε=0.4\varepsilon = 0.4, how many rounds does each bound require to reach a training error below 1%? Why does the bound require no assumption on the data?

Answer

Answer to Question 21.45.

The bound comes from the exponential loss. At ε=0.4\varepsilon = 0.4 the two bounds require 226 and 231 rounds. Beyond the requirement that εt<12\varepsilon_t < \frac12, the data do not enter.

Let the labels be ±1\pm 1 and F=∑tαthtF = \sum_t\alpha_th_t. The weights start at 1/n1/n, and each update multiplies by e−αtyiht(xi)e^{-\alpha_ty_ih_t(x_i)} and divides by the normaliser ZtZ_t. After TT rounds,

wT+1(i)=e−yiF(xi)n∏tZt.w_{T + 1}(i) = \frac{e^{-y_iF(x_i)}}{n\prod_tZ_t}.

The weights sum to 1, so 1n∑ie−yiF(xi)=∏tZt\frac1n\sum_ie^{-y_iF(x_i)} = \prod_tZ_t.

An error has yiF(xi)≤0y_iF(x_i) \le 0, where e−yiF(xi)≥1e^{-y_iF(x_i)} \ge 1, so the indicator of error is at most this exponential. Hence the training error is at most ∏tZt\prod_tZ_t.

Next, Zt=(1−εt)e−αt+εteαtZ_t = (1 - \varepsilon_t)e^{-\alpha_t} + \varepsilon_te^{\alpha_t}. The given αt\alpha_t minimises this, with value 2εt(1−εt)2\sqrt{\varepsilon_t(1 - \varepsilon_t)}. With εt=12−γt\varepsilon_t = \frac12 - \gamma_t, it is 1−4γt2≤e−2γt2\sqrt{1 - 4\gamma_t^2} \le e^{-2\gamma_t^2}, because 1−u≤e−u1 - u \le e^{-u}. A product gives the sum in the exponent.

At ε=0.4\varepsilon = 0.4: Z=20.24=0.9798Z = 2\sqrt{0.24} = 0.9798, and ln⁡0.01/ln⁡0.9798\ln 0.01/\ln 0.9798 gives T=226T = 226. For the second bound, γ=0.1\gamma = 0.1, so T≥ln⁡(100)/(2×0.01)T \ge \ln(100)/(2 \times 0.01), which gives 231. The exponential bound loses very little, as γ\gamma is small.

A run with stumps on 400 rows confirms at each round that ZtZ_t equals its formula, that the mean exponential loss equals the product, and that the training error stays below it.

The proof needs only that each weak learner beats a coin on the current weights, and there is no assumption on the distribution of the data. The catch is that such a learner may not exist on later rounds, and γt\gamma_t typically shrinks. And it says nothing about test error, which often keeps falling after the training error reaches zero, an observation explained by margins.

Classic wrong answer. Assuming that the bound guarantees generalisation. It is a statement about training rows only. On noisy financial labels, driving training error to zero is exactly what should be avoided.

Follow-up. The training error can take only values in steps of 1/n1/n. What does this imply? Once the bound is below 1/n1/n, the training error must be exactly zero. With n=400n = 400 and ε=0.4\varepsilon = 0.4, that takes at most 294 rounds.

Why it matters. This is a tidy example of a proof with a surprising strength, and each step is elementary. It tests whether the candidate can move between the algorithm’s update and the bound.