21. Handling class imbalance
You train a churn classifier where only 5% of users churn. Which approach is a sound first step?
- A.Delete all churned users so the model is not confused
- B.Use class weights (or resampling on the training set only) and tune the decision threshold on validation data
- C.Oversample the minority class before splitting into train and test
- D.Report accuracy and stop there
Show answer
Answer: B. Use class weights (or resampling on the training set only) and tune the decision threshold on validation data
Class weights or resampling help the model pay attention to the rare class, and tuning the threshold lets you choose the precision/recall trade-off. Resampling must happen after the split and only on training data, otherwise duplicated rows leak into the test set.
22. Which regularisation gives sparse weights
You want a linear model that automatically sets many feature weights to exactly zero. Which regularisation should you use?
- A.L2 (ridge) regularisation
- B.Dropout
- C.Batch normalisation
- D.L1 (lasso) regularisation
Show answer
Answer: D. L1 (lasso) regularisation
The L1 penalty has a sharp corner at zero, so the optimum often lands exactly on zero for weak features, giving sparse models and built-in feature selection. L2 shrinks weights towards zero but rarely makes them exactly zero.
23. F1 score from a confusion matrix
A fraud model has TP = 40, FP = 10, FN = 20 and TN = 130. What is its F1 score?
- A.0.67
- B.0.73
- C.0.80
- D.0.85
Show answer
Answer: B. 0.73
Precision is 40 / 50 = 0.80 and recall is 40 / 60, about 0.667. F1 is their harmonic mean: 2 * 0.8 * 0.667 / (0.8 + 0.667), about 0.73. The harmonic mean sits closer to the weaker of the two numbers.
24. NDCG for a three-item ranking
A search returns three results with relevance 1, 0, 1 in that order. Using gain = relevance and discount 1 / log2(position + 1), what is NDCG@3?
- A.0.50
- B.0.67
- C.0.81
- D.0.92
Show answer
Answer: D. 0.92
DCG = 1/1 + 0/log2(3) + 1/log2(4) = 1 + 0 + 0.5 = 1.5. The ideal order 1, 1, 0 gives IDCG = 1 + 1/log2(3), about 1.631. NDCG = 1.5 / 1.631, about 0.92. Putting the second relevant item lower costs only a little.
25. Loss for logistic regression
Why is logistic regression trained with log loss (cross-entropy) rather than mean squared error on the sigmoid output?
- A.MSE cannot be computed for values between 0 and 1
- B.Log loss needs no gradient to be minimised
- C.MSE always gives the same weights but slower
- D.Log loss with a sigmoid is convex in the weights; MSE is not
Show answer
Answer: D. Log loss with a sigmoid is convex in the weights; MSE is not
Combining the sigmoid with log loss gives a convex objective with a single global minimum and well-behaved gradients. MSE through a sigmoid is non-convex and gives tiny gradients when the model is confidently wrong. Log loss is also the negative log-likelihood of a Bernoulli model.
26. Rows left out of a bootstrap
Each tree in a random forest is trained on a bootstrap sample of n rows drawn with replacement from n rows. For large n, roughly what fraction of the original rows are left out of a given tree (out-of-bag)?
- A.About 50%
- B.About 10%
- C.About 37%
- D.About 63%
Show answer
Answer: C. About 37%
The chance a row is never picked in n draws is (1 − 1/n)ⁿ, which tends to 1/e ≈ 0.368. So about 37% of rows are out-of-bag for each tree and about 63% are in the sample. The OOB rows give a free validation estimate.
27. What bagging and boosting each reduce
Broadly, which statement about bagging and boosting is right?
- A.Bagging mainly cuts bias; boosting mainly cuts variance
- B.Both only reduce training time
- C.Bagging mainly cuts variance; boosting mainly cuts bias
- D.Both need models that are trained in sequence
Show answer
Answer: C. Bagging mainly cuts variance; boosting mainly cuts bias
Bagging averages many high-variance models trained in parallel on resampled data, which smooths out their errors. Boosting trains weak, high-bias learners in sequence, each fixing what the previous ones got wrong, which reduces bias.
28. Why k-means++ is used
Running k-means twice with random starting centres gives quite different clusters. What does k-means++ initialisation do to help?
- A.Picks spread-out starting centres
- B.Finds the best value of k automatically
- C.Guarantees the global optimum every time
- D.Removes outliers before the clustering starts
Show answer
Answer: A. Picks spread-out starting centres
k-means only finds a local optimum that depends on the starting centres. k-means++ picks each new centre with probability proportional to its squared distance from the nearest chosen centre, which spreads them out. It usually gives better, more stable results, and running several initialisations helps further.
29. Encoding hour of day
A demand model uses hour of day as a number 0–23, so 23 and 0 look far apart even though they are one hour apart. What is a common fix for a linear or distance-based model?
- A.Divide the hour by 24 to scale it
- B.Take the logarithm of the hour value
- C.Sort the training rows by hour first
- D.Add sin(2π·h/24) and cos(2π·h/24) features
Show answer
Answer: D. Add sin(2π·h/24) and cos(2π·h/24) features
Mapping the hour onto a circle with sine and cosine makes 23:00 and 00:00 close together, matching reality. Dividing by 24 only rescales the same jump. Tree models can also handle hour with splits or one-hot encoding.
30. MAPE on low-selling products
You report MAPE for a demand forecast. Many products sell 0 or 1 unit on some days. What goes wrong?
- A.MAPE ignores errors on the low sellers
- B.MAPE turns negative for small values
- C.MAPE gives the same value as MAE
- D.Errors explode or are undefined at tiny actuals
Show answer
Answer: D. Errors explode or are undefined at tiny actuals
MAPE divides each error by the actual value, so actuals of 0 make it undefined and actuals of 1 make small misses look like 100%+ errors. Alternatives include weighted MAPE (total absolute error / total actuals) or MASE.
31. Which class gets confused
Rows are true labels and columns are predictions. What is the recall for class "refund"?
billing refund other
billing 80 15 5
refund 30 60 10
other 5 5 90
- A.0.75
- B.0.80
- C.0.60
- D.0.30
Show answer
Answer: C. 0.60
Recall for refund = correct refund predictions / all true refunds = 60 / (30 + 60 + 10) = 0.60. Precision for refund would use the column: 60 / (15 + 60 + 5) = 0.75. The matrix also shows refunds are often mistaken for billing.
32. MRR across three queries
For three queries, the first relevant result appears at ranks 1, 2 and 4. What is the mean reciprocal rank?
- A.About 0.43
- B.About 2.33
- C.About 0.75
- D.About 0.58
Show answer
Answer: D. About 0.58
Reciprocal ranks are 1/1, 1/2 and 1/4 = 1, 0.5 and 0.25. Their mean is 1.75 / 3 ≈ 0.583. MRR only looks at the first relevant item, which suits tasks like FAQ search with one right answer.
33. Better offline, flat online
A new recommender raises offline NDCG by 4%, but an A/B test shows no change in orders. What is the most reasonable reading?
- A.The A/B test setup must be broken somehow
- B.NDCG gains always show up in order counts
- C.Offline metrics are proxies; trust the test
- D.Orders are not a valid metric to look at
Show answer
Answer: C. Offline metrics are proxies; trust the test
Offline data reflects past behaviour under the old system, and NDCG may not capture what drives orders. A well-run A/B test measures the real effect. The gap is a reason to revisit the offline metric, not to ignore the experiment.
34. Negative scores from cross_val_score
Why does this print negative numbers?
scores = cross_val_score(reg, X, y, cv=5, scoring='neg_mean_squared_error')
print(scores) # e.g. [-412.3 -398.1 -455.0 -401.7 -420.9]
- A.The model is predicting negative values
- B.Scorers are maximised, so losses are negated
- C.MSE turns negative when the model is poor
- D.The folds were not shuffled before splitting
Show answer
Answer: B. Scorers are maximised, so losses are negated
scikit-learn's scorers follow "higher is better", so error metrics are returned as negatives. Negate them to get MSE: about 418 on average here. The sign has nothing to do with the predictions.
35. Precision and recall at 0.6
Six cases have (score, true label): (0.9, 1), (0.8, 0), (0.7, 1), (0.5, 1), (0.4, 0), (0.2, 0). At threshold 0.6, what are precision and recall?
- A.Precision 0.67, recall 1.0
- B.Precision 0.67, recall 0.67
- C.Precision 1.0, recall 0.67
- D.Precision 0.5, recall 0.5
Show answer
Answer: B. Precision 0.67, recall 0.67
Predicted positive (score ≥ 0.6): 0.9, 0.8, 0.7, of which 2 are true, so precision = 2/3. There are 3 actual positives (0.9, 0.7, 0.5) and 2 were caught, so recall = 2/3. The 0.5 case is a false negative.
36. Reading a MASE of 0.8
A demand forecast has mean absolute scaled error (MASE) of 0.8. What does this mean?
- A.It is 80% accurate
- B.80% of forecasts are within 1 unit
- C.Its MAE is 80% of the naive forecast's MAE
- D.It is 20% worse than the naive forecast
Show answer
Answer: C. Its MAE is 80% of the naive forecast's MAE
MASE divides the model's MAE by the MAE of a naive forecast (such as last period's value) on the training data. Below 1 means it beats the naive method; above 1 means it is worse. It works even when actuals include zeros.
37. Which prediction hurts log loss most
Each pair is (true label, predicted probability of class 1). Which single prediction adds the most to log loss?
- A.(1, 0.6)
- B.(0, 0.3)
- C.(0, 0.9)
- D.(1, 0.05)
Show answer
Answer: D. (1, 0.05)
Log loss for one example is -ln of the probability given to the true class. These are -ln(0.6) = 0.51, -ln(0.7) = 0.36, -ln(0.1) = 2.30 and -ln(0.05) = 3.00. Confident wrong predictions are punished very hard, which is why log loss rewards good calibration.
38. Why a forest beats one tree
Why does a random forest usually generalise better than a single deep decision tree?
- A.Averaging many decorrelated trees reduces variance
- B.Each tree in the forest is deeper and more accurate
- C.Random forests remove bias completely
- D.Random forests do not need training data
Show answer
Answer: A. Averaging many decorrelated trees reduces variance
A single deep tree has low bias but high variance: small data changes produce very different trees. A forest trains trees on bootstrap samples with random feature subsets, so their errors are less correlated, and averaging them cuts variance. Bias stays roughly the same.
39. Unseen category at predict time
A OneHotEncoder fitted on training cities raises an error when a new city appears in production. What setting avoids the crash?
- A.sparse_output=False always
- B.drop="first" on the encoder
- C.dtype=float on the encoder
- D.handle_unknown="ignore"
Show answer
Answer: D. handle_unknown="ignore"
By default OneHotEncoder raises on unseen categories. handle_unknown="ignore" encodes them as all zeros, and "infrequent_if_exist" maps them to the infrequent bucket. Also monitor how often unknown values occur.
40. Precision moved, AUC did not
With a fixed 0.5 threshold, precision fell sharply this month, but AUC is unchanged. What is a likely explanation?
- A.Scores shifted, so the fixed cut lands elsewhere
- B.AUC must be wrong because precision has fallen
- C.The model has stopped ranking cases correctly
- D.Precision does not depend on the threshold used
Show answer
Answer: A. Scores shifted, so the fixed cut lands elsewhere
Threshold metrics like precision and recall depend on where the cut sits in the score distribution. A score shift or a change in base rate can move them while ranking quality (AUC) holds. Recalibration or threshold re-tuning may be enough.