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 , precision , recall , F1 . A model that never flags anything has accuracy , which is higher.
The counts are 40 true positives, 60 false positives, 10 false negatives, and so 890 true negatives. Accuracy is . Precision is , the share of flags that are right. Recall is , the share of real events that are caught. F1 is their harmonic mean, .
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 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. . 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 standard deviations above the mean, so the expected best is about , 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: gives .
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, -nearest neighbours, a decision tree, a random forest, regression on the top two principal components?
Answer
Answer to Question 21.3.
Ridge, -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 , 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 earn, and the constant ? What single-row loss comes from predicting on a row whose label is 0, and why should this worry you?
Answer
Answer to Question 21.4.
The constant earns , the constant earns , and the single row costs .
Log loss is the mean of . For the constant : . For : , for every row, whatever the base rate.
A prediction of on a label of 0 gives probability to what occurred, and it costs . That is more than twenty times the base loss, and one such row in 100 adds , 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 on an unbalanced problem. The fair baseline is the constant at the base rate, here .
Follow-up. Which constant minimises log loss? The base rate. Setting the derivative of to zero gives , 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 on a standardised feature. What happens to the odds when the feature rises by 1? Starting from probabilities and from , what is the new probability in each case?
Answer
Answer to Question 21.5.
The odds double, since . A probability of becomes , and becomes .
The model is linear in the log-odds, so a unit rise adds to the log-odds and multiplies the odds by .
From , the odds are , which double to , and so . From , the odds are 1, which double to 2, and so . The same coefficient adds in one case and in the other. The effect on the probability depends on where you start.
Classic wrong answer. Saying that the probability rises by , or doubles. A probability cannot do that from , whereas the odds can.
Follow-up. Give a quick rule for the effect near . The slope of the logistic curve there is , so the change is about the coefficient over 4. Here that is , close to the true .
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 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? 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 are flagged. So precision is . With a false positive rate of 1%, the flags are , which gives . 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? , 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 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: . Layer two: . Output: . 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 , and observations have noise of variance 1. You estimate at a point using the mean of its nearest neighbours, which lie at distances , all on one side. Write the bias and variance. Which minimises the squared error of the estimate? What happens to the best if the data are twice as dense?
Answer
Answer to Question 21.10.
Bias is and variance , so the best is 3, with squared error . Doubling the density raises the best to 6.
The mean of the neighbours has expected value away from the true value. Its variance is . So the squared error is
The values at are , , and , so the best is . A simulation of the three-neighbour estimate gives the same .
With spacing , the error is , with minimum at . 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 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 ? 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 , new-noise error . The gap of equals .
Fitting projects the noise on the regressors’ column space. The fit absorbs of the dimensions of noise, so the residual sum of squares has expectation , and the mean squared error is .
The fitted values carry noise of total variance . Against fresh noise at the same points, the expected error is the new noise plus that: . A simulation returns and .
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 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? . 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 , and the entropy by bits.
Left child: 30 and 10, right child: 10 and 50, with weights and .
Gini is . Parent: . Left: . Right: . Weighted: . So the decrease is .
Entropy is . Parent: . Left: . Right: . Weighted: . The decrease is .
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 for both. Gini gives for A and 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 . In B, the first child is wrong on 200 and the second on 0, also .
Gini for A: for each child. For B: the first child has of the rows, with , and the pure child has 0, so .
The misclassification rate is piecewise linear in . 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 and , for instance, have a worse error than A, , and a better Gini, .
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 models, each with variance , and pairwise correlation . Derive the variance of the average. For , and , what is it, and what does it become as grows? Using random feature subsets at each split lowers to but raises to . Is this a good trade?
Answer
Answer to Question 21.14.
The variance is , which is at , and in the limit. The trade is good, with at the same .
Expand the variance of the mean:
At the stated values: . Check the limits: gives , as one model does, and gives . A simulation of correlated models returns .
So more models stop helping at the shared part . To go lower, the models must be made less alike, and that is the purpose of feature subsampling in a random forest. With and : . 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 , how many models get within 1% of the limit? 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 . What share of the target is fitted after trees? When do you pass 90% and 99%? Why shrink at all?
Answer
Answer to Question 21.15.
The fitted share after trees is , which passes 90% at and 99% at . Shrinking averages over the noise.
For , the derivative with respect to is . 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 , the residual is multiplied by every round. After rounds, remains. Since and , the two thresholds are crossed at 22 and 44.
A real tree fits a noisy estimate of the residual. With , the whole of the noise in the last tree stays in the fit. With a small , 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? , which is at and 1 at . 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 , 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 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 . What is its vote ? 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.
. Wrong rows are multiplied by and right rows by . After normalising, the wrong rows hold a total weight of exactly .
. The factors are and .
The wrong rows held , so they now hold . The right rows held , now . These are equal, so each share is . The normaliser is .
This means that the last learner now has a weighted error of exactly 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 is, which is the reason for this choice of .
Classic wrong answer. Saying that wrong rows get “more weight” with no number. The exact is the content of the algorithm.
Follow-up. What are the votes for and ? Zero and . 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 and noise variance , and find . Then define its effective number of parameters, and compute it for squared singular values 100, 10 and 1, with . Check both limits of .
Answer
Answer to Question 21.18.
. The effective number of parameters is .
The log posterior is, up to a constant,
Multiplying by gives the ridge objective, with . The posterior is normal, so its mode is its mean, . A tighter prior or noisier data means more shrinkage.
The fit is with . The natural definition of effective parameters is the trace of , since for least squares this equals . In terms of the singular values of , it is .
With values and : . A matrix with these singular values gives the same trace. At the sum is 3, the full count, and at it is 0. The strong direction keeps its freedom, and the weak one is nearly removed.
Classic wrong answer. Treating 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 for noise of 1 and a prior standard deviation of ? . For returns, where signals are small, large values of 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: with label 0, and with label 1. What does the maximum likelihood do? Add a penalty with . What is now, and what probability does the model give at ?
Answer
Answer to Question 21.19.
With no penalty, runs off to infinity. With , , and the probability at is about .
The loss is , which falls forever as 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:
That equation has a single root at , found by bisection and matched by a library fit with the same penalty. The probability is .
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 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 ? , with probability . Weaker penalties allow more confidence, slowly: a tenfold fall in does not even double .
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 . 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 . 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 ?
Answer
Answer to Question 21.20.
The true posterior is and the classifier says , so the decision flips.
Naive Bayes multiplies the likelihood ratios, assuming independence given the class. With prior , the posterior odds are the product of the ratios.
The true odds use A once: , so the posterior is . Below , the decision is class 0.
The classifier counts A three times: , so the posterior is . Above , 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 , and the classifier’s is . These fall on the same side of , 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 , one sigmoid hidden unit , and output , with and . The target is and the loss . Find both gradients by the chain rule. Take a step of size on both weights, and give the new loss.
Answer
Answer to Question 21.21.
Both gradients are , the new weights are and , and the loss falls from to .
Forward: , , and the loss is .
Backward: .
For : , so the gradient is .
For : , and , so the gradient is . Central finite differences agree with both to eight decimals.
Step: , and . Then , , and the loss is . A first-order estimate of the fall is , and the actual fall is , so the numbers are consistent.
Classic wrong answer. Leaving out the derivative of the sigmoid, , which is here. Or updating first, and then using the new in the gradient for . 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 , what variance of the initial weights keeps the signal’s variance constant through depth?
Answer
Answer to Question 21.22.
The bound is . ReLU has derivative 1 where active, but units can die. The right variance is .
The sigmoid’s derivative is at most , at the middle of its range. With unit weights, the chain rule gives a product of ten such factors, at most . 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 , and inputs of mean square , the pre-activation has variance . ReLU keeps half of its second moment. So , which is constant at . A run through 30 layers of width 500 confirms it: the signal stays within a factor of 10 at , it collapses below at , and it explodes above at .
Classic wrong answer. Using 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 is . 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 , with the ReLU, computes it.
Suppose exactly for class 1. Inputs and give and . Inputs and give and (or weak inequalities). Adding the first pair gives , and adding the second pair gives . This is a contradiction.
The network, with , gives:
- : , so .
- or : , so .
- : , so .
The two hidden units create a kink in the function of , 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 above it.
Follow-up. How does this generalise to the parity of bits? One hidden layer of ReLU units works: with the sum of the bits, . A check of all inputs up to 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 , and the label is 1. Compute the gradient with respect to under cross-entropy and under squared loss . By what factor do they differ? Is each loss convex in ? What does this mean for training?
Answer
Answer to Question 21.24.
Cross-entropy gives and squared loss gives , a factor of about 1100. Cross-entropy is convex in , and squared loss is not.
Here .
Cross-entropy has . So when the model is badly wrong, the gradient is close to its largest value.
Squared loss has . The chain rule brings in , which is tiny at the tails. So the worst error produces almost no gradient. The factor is .
The second derivative of cross-entropy in is , so it is convex. Squared loss has second differences that are negative at and positive at , so it is not convex in , 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 and ? under cross-entropy, and 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 , , , and negatives score , , , . Compute the area by pair counting, and by rank sums.
Answer
Answer to Question 21.25.
The area is by each method.
Sort by score, and sweep the threshold down. Each positive raises the ROC curve by , and each negative moves it right by . The area under the staircase is a sum over negatives of the height when that negative is passed, times the share of positives ranked above it. So the area is
the share of pairs in the right order, with ties giving from the diagonal segment.
Pairs: beats all four negatives. beats , , , which makes 3. also beats those three. The total is 10 out of 12.
Ranks from the bottom: take 1, 2, 3; takes 4; takes 5; takes 6; takes 7. The positives sum to 16. Then , the same count. A trapezoid sum on the ROC curve also gives .
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 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 in the first case and above 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: , which gives . In general, . A costly miss lowers the threshold.
For the trade, the expected value is positive when . At , the expected value is exactly zero: .
These rules need the score to be a true probability. A score of from an overconfident model may truly mean , in which case the trade loses money while looking safe. So check calibration: among rows with a score near , 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 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 per trade change? gives . 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 units? What cost per trade brings the Sharpe ratio to zero?
Answer
Answer to Question 21.27.
Daily Sharpe , annual . With the cost, the annual figure is . A cost of brings it to zero.
The mean daily return is . The variance is , so the standard deviation is . The daily Sharpe ratio is , and the annual one is . A long simulation agrees.
A cost of per trade halves the mean to , and halves the Sharpe ratio to . The volatility does not change. So the break-even cost is exactly the edge, .
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 the size of losses? gives . 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 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 . You drop 38 rows, leaving 762. A random split reports a correlation above on pure noise.
Labels days apart share of their 20 independent daily returns, so their correlation is . At 5 days it is .
The test block holds days 400 to 599 in zero-based terms. The label at day uses days to . 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 . 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 . So, using the date alone, the model “predicts” pure noise with a correlation above 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 . Which of these leak, and how? (a) Close-to-close return of day . (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 .
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 , 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 ’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
-means runs on the four points , with . Start the centres at and . 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 , and five restarts all fail with chance .
Each point goes to the nearer centre, so the top two and the bottom two form clusters. Their means are the same centres . The algorithm has converged. Each point is 2 away from its centre horizontally, so the sum of squares is .
The left and right split has centres . Each point is away, so the sum of squares is , 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, and . Then the right points and 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 , and five restarts all fail with chance .
Classic wrong answer. Saying that -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 , what is the chance of the bad pair? , or about 3%. The squared distance favours far points, and this rule is the -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 , 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 , 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 , and the expected true Sharpe ratio is . With four times the history, the figures are and .
Measured values are normal with variance . The largest of 100 independent standard normals is on average, so the best measured value is .
Given a measured value , the true value has mean . Selection depends only on measured values, so this applies to the winner too, and . So 80% of the measured Sharpe ratio is noise, and it will not come back. A simulation of 200 000 such contests gives and .
With four times the history, the noise’s standard deviation halves, to . Now the variance of the measure is , and the best measured value is . The shrinkage factor is , which gives . 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 .
Classic wrong answer. Dividing by , 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 , after costs, what is the winner’s expected true value? Roughly . 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 , and you observe it with noise variance 1. You forecast its next value by the mean of the last observations. Derive the forecast’s mean squared error as a function of , and the best . How sensitive is the answer to ? What does this say about choosing a training window?
Answer
Answer to Question 21.33.
The error is , with the minimum at , where it equals . The curve is flat near the minimum.
The forecast uses the mean of the last observations to forecast the level one step beyond. The observation noise contributes . 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 , and so on down to . The variance is
For large , the sum of the two parts is about , with its minimum at . A search over integers gives 173, and a simulation gives the same error of .
The sensitivity is low. At or 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 , use all the data, and as 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 , which is a half-life of 69 steps, and an error of , 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 for positives. Derive the area under the ROC curve. What are the areas at , and 1? A return model reports an area of on balanced classes. What is , and what correlation does it imply between the score and the label?
Answer
Answer to Question 21.34.
The area is , which gives , and . An area of means , and a correlation of 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 and variance 2. So the chance that it is positive is .
For the second part, invert: .
For balanced classes, the label has variance . The score has variance , as the mixture of means adds . The covariance between them is . So
A simulation confirms both and the area of . At the area is , and the correlation is zero, as they must be.
In terms of return prediction, a correlation of with the sign of the return is a large effect. So an area of , 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 is a failure. Or equating the correlation with the area’s excess over .
Follow-up. What accuracy does that model reach at the midpoint threshold? . Directional accuracy of corresponds to the area of .
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 and 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 and . In a logistic regression, the correction changes only the intercept, by , and not the slopes.
Let be the share of negatives kept. Keeping is independent of the features, given the class. So Bayes’ rule gives
So the odds on the sampled data are ten times the true odds, whatever is, and the correction is .
At , the sampled odds are 1, and the true odds are , so . At , the sampled odds are 9, and the true odds are , so . A row the model calls is a coin flip.
In logistic regression, the log-odds are linear in , and sampling shifts them by the constant . So the sampled fit has the same slopes, with intercept up by , and the correction subtracts that. A run with 400 000 rows, an intercept of and a slope of 1 returns slope and intercept , as predicted.
The result relies on keeping being independent of 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 , what is the leaf’s new probability?
Answer
Answer to Question 21.36.
The initial log-odds are . The Newton leaf value is , the exact optimum is , and the new probability is .
With the log-odds and , the loss on a row is . Its gradient in is , and its Hessian is . The best constant is the base rate, so .
At , a positive has gradient , a negative has , and every row has Hessian .
For the leaf: , and . The Newton step is .
The exact optimum makes the leaf’s probability equal its share of positives, , whose log-odds are . So the exact step is , and a direct search agrees. Newton falls about 10% short here, and it improves in later rounds.
With shrinkage , the update is , so , up from , on the way to the leaf’s .
Classic wrong answer. Using the raw residual mean, , 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 . The exact step is . 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 , where and are the sums of the gradients and Hessians, and is the leaf’s value. Derive the best and the gain from a split. Compare, with , the split and with the split and . Which does it prefer, and what setting guards against this choice?
Answer
Answer to Question 21.37.
, with gain . The gains are and , so the library prefers the unbalanced split. A minimum Hessian in each child guards against it.
Minimising the quadratic over gives , and the minimum is . 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 , so the last term vanishes.
Split one: , with leaf values .
Split two: , with a left leaf value of .
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 helps, but even leaves the preference: the gains are and . The direct guard is a minimum sum of Hessians per child. A limit of 5 rejects split two outright. At , the second gain is , so the regulariser is doing a good deal already.
Classic wrong answer. Thinking that 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 is the row count. With log loss, a row has , 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 , where is the ordinary residual and is the leverage. Then fit a line with an intercept to and , 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 by both routes.
Let and let be row . Removing the row gives . The Sherman–Morrison formula gives
Then . Multiplying out and simplifying,
So . It needs only one fit.
On the data: , , and the slope is . The fitted value at 10 is , so . The leverage is . The formula gives .
From its meaning: without the last point, the other four lie exactly on . That line predicts 10 at , while . So the residual is , 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 , out of a sum of 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 by its mean . What does this give for the last row? , 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 , where equals 1 with probability 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 , how do the coefficients compare with ordinary least squares at and ?
Answer
Answer to Question 21.39.
The expected loss is the ordinary squared loss plus . In the example the coefficients are times the least squares ones: half at , and of them at .
For one row, write . Since , the mean of is , the ordinary prediction. So
which is the bias–variance split for a single prediction. The variance of is , and the are independent, so the variance is . 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 , the penalty is with . So the solution is
At , there is no change, as expected, and as , 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 , 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 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 , 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 , a one-hidden-layer ReLU network with units gives at most how many linear pieces? Write the tent map, on the first half and on the second, with two ReLU units. How many pieces does the map composed with itself times have? Compare the number of units needed by the deep network and by the shallow one at .
Answer
Answer to Question 21.40.
A shallow network with units has at most pieces. The -fold tent map has pieces and uses units. At this means 20 units deep, against 1023 units shallow.
Each ReLU unit has one kink, and the output is a sum of them, plus a constant. So there are at most kinks, and pieces.
The tent map on is . Check: below , the second term vanishes, and it equals . Above , it gives . So two units per layer.
Under composition, maps each of its two pieces onto all of , so a function with linear pieces that each cover becomes one with . Thus has pieces, a sawtooth with teeth. A count of slope changes on a fine grid confirms it up to .
To match this exactly, a shallow network needs at least kinks. For , 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 ? Sixty units in depth, against , 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 and standardised columns, show that all coefficients are zero exactly when . Take , , independent columns and pure-noise of variance 1. What is this threshold about? What does it say about choosing when the signal is weak?
Answer
Answer to Question 21.41.
The threshold is about , close to the rule of thumb . On pure noise, any below it lets noise features in, and with weak signals it can hide the real ones.
At , the objective’s smooth part has gradient . The subgradient of at 0 is any value in . So is optimal, by convexity, exactly when for all . That gives the threshold, called .
With pure noise, each is about normal, with standard deviation . The largest absolute value of 1000 such normals is on average standard deviations. So . The upper envelope overstates this slightly at . A run gives a value in this range, an all-zero fit just above it, some nonzero coefficients at , 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 exceeds it. With a coefficient of in this setup, a real feature contributes about , which lies below the noise’s maximum. So at this level the lasso finds nothing, and a lower 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 that keeps several features.
Follow-up. How does the threshold scale if grows to ? Only with . The envelope goes from to 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, independent of the features, on independent standard normal features, using rows and least squares, taking the minimum-norm solution when . Derive the expected test error on a new row as a function of , for below and above . Evaluate it at . Why does it peak, and why does it fall again?
Answer
Answer to Question 21.43.
The test error is for , and for . The values are , , , and .
The new row is independent of the fit, and has variance 1 and is unrelated to . Then the test error is , since for standard normal .
For : , so, using , . is Wishart, and the mean of its inverse is . So the term is .
For : the minimum-norm solution is , so . Here is Wishart of size with degrees of freedom, so the term is .
At : . At : . At : . At : . At : . Simulations match to within a few percent, and to within 10% at , where the tails are heavy.
The peak is at . There is then exactly one solution through the points, and fitting pure noise demands huge coefficients, as the matrix is nearly singular. Beyond , there are many interpolators, and taking the smallest spreads the noise over many directions, each with a small coefficient. As , 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 has size , spread evenly, a term appears for , since the fit can only see the -dimensional part.
Follow-up. With true signal size and no noise, what is that term at ? . A run gives . 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 dimensions, and their means differ by a vector of length 2 lying in the first coordinate only, so that 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 , and evaluate it at , 100 and 1000. What is the error with the known means?
Answer
Answer to Question 21.44.
The error is about , which gives , and . The error with known means is .
With known means, the rule is optimal, and in the direction joining them each class is normal with variance 1, at distance from the midpoint. So the error is .
With estimated means, let , where is the true difference and has independent entries of variance . Classify a new from class 1 by the sign of , where is the midpoint of the estimates.
Given the estimates, the score is normal with variance and mean . Now , with a small noise, independent of . To leading order, the mean is , as the cross terms average to zero and are small. And , since each of the noise entries adds .
So the error is
with and . The values are as stated. A simulation with these values matches at each . As with fixed, the error goes to , and as it goes to .
The conclusion: useless features actively hurt. The noise in the estimated direction adds to the squared length, and only the 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 does the error reach 30%? gives . 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 , where is the weighted error at round , and that this is at most , with . If every round has , 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 the two bounds require 226 and 231 rounds. Beyond the requirement that , the data do not enter.
Let the labels be and . The weights start at , and each update multiplies by and divides by the normaliser . After rounds,
The weights sum to 1, so .
An error has , where , so the indicator of error is at most this exponential. Hence the training error is at most .
Next, . The given minimises this, with value . With , it is , because . A product gives the sum in the exponent.
At : , and gives . For the second bound, , so , which gives 231. The exponential bound loses very little, as is small.
A run with stumps on 400 rows confirms at each round that 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 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 . What does this imply? Once the bound is below , the training error must be exactly zero. With and , 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.