Machine Learning Interview Questions

Reviewed by Mark Dickie · Last updated

Machine learning is a branch of artificial intelligence where models learn patterns from data instead of following hand-written rules. For an ML interview you should know supervised vs. unsupervised learning, bias-variance tradeoff, regularization, gradient descent, evaluation metrics, and the assumptions behind common algorithms like linear regression, logistic regression, decision trees, SVMs, and k-means. Interviewers also expect you to explain model selection, cross-validation, overfitting, and the practical differences between batch and online learning. Below is a summary of the most commonly tested topic areas and what an interviewer probes in each one.

CategoryWhat an interview tests
Supervised learningChoice of algorithm, decision boundaries, and when linear models suffice
Unsupervised learningClustering validity, dimensionality reduction, and use cases
Model evaluationMetric selection (accuracy, precision/recall, F1, AUC), train/validation/test splits
OptimizationGradient descent variants, learning rate, convergence behavior
RegularizationL1 vs. L2, what each penalizes, and effects on sparsity
Deep learning basicsForward/backward pass, activation functions, and common pitfalls
  1. Explain bias and variance, and draw the tradeoff curve.
  2. Compare L1 and L2 regularization: what does each penalty term do to the weights?
  3. Walk through gradient descent: how does the learning rate affect convergence?
  4. Describe cross-validation and why it gives a better generalization estimate than a single train/test split.
  5. Outline how a decision tree splits a node, and what information gain or Gini impurity measures.

What does a machine learning interview test?

Most ML interviews split into three parts: conceptual understanding, algorithm derivation or implementation, and applied problem-solving. The conceptual portion checks whether you can state assumptions and tradeoffs clearly, for example why you would pick a tree-based model over a linear one for tabular data with nonlinear feature interactions. The implementation portion may ask you to code a simple model or loss function from scratch. The applied portion gives you a dataset scenario and asks you to choose features, models, and validation strategy, then defend your choices.

How should you prepare for machine learning interview questions?

Start by reviewing the math behind the core algorithms rather than memorizing APIs. Knowing why logistic regression outputs probabilities, what the kernel trick does in an SVM, and how backpropagation chains derivatives together will carry you through most whiteboard rounds. Practice explaining each concept out loud, because interviewers care about communication as much as correctness. Use the quiz below to test yourself on real interview questions before you walk into the room.

Key facts

  • Tarmac has 100 Machine Learning interview questions on this topic, 25 of them on this page, at difficulty 1–5 of 5.
  • Tarmac last reviewed these Machine Learning interview questions on 31 August 2026.

At a glance

Questions25 shown · 100 in the bank
Difficulty1–5 of 5
FormatsMultiple answer, Code output, Fill in the blank, Multiple choice, True / false, Ordering, Flashcard, Short answer, Design exercise, Find the bug

What you'll review

  1. model selection tradeoffs
  2. feature engineering
  3. train val test split
  4. bias variance tradeoff
  5. evaluation metrics
  6. data leakage
  7. overfitting underfitting

Practice questions

Machine Learning/algorithm-tradeoffs/model-selection-tradeoffs

Which of the following are generally accepted as advantages of using a simpler model (e.g., logistic regression) over a more complex model (e.g., a deep neural network) for a given tabular classification task? Select all that apply.#

Options

Pick every one that applies.

Show answer

The correct advantages are interpretability/explainability and lower computational cost (faster training, fewer resources). Simpler models do not inherently avoid underfitting by having more data, and they certainly do not always achieve higher accuracy — that depends on the dataset and task complexity.

Why:

Simpler models like logistic regression are more interpretable (a) and are cheaper to train and deploy (c). Option (b) is incorrect because underfitting is not primarily a data-quantity issue — simpler models may underfit because their hypothesis class is too restricted, not because they lack data. Option (d) is incorrect because simpler models do not always outperform complex models; the best choice depends on the data and problem complexity.

Machine Learning/data-preparation/feature-engineering

Min-max scaling rescales features to a [0, 1] range using the formula: (x - min) / (max - min). Trace the following Python code that applies min-max scaling to a small list of values. What is the exact output printed?#

X = [0, 10, 20]
min_val = min(X)
max_val = max(X)
X_scaled = [(x - min_val) / (max_val - min_val) for x in X]
print(X_scaled)
Show answer
[0.0, 0.5, 1.0]
Why:

The list X = [0, 10, 20] is given explicitly in the code. min_val = min(X) evaluates to 0, and max_val = max(X) evaluates to 20. Each element is then transformed by (x - min_val) / (max_val - min_val): (0 - 0) / (20 - 0) = 0.0, (10 - 0) / (20 - 0) = 0.5, (20 - 0) / (20 - 0) = 1.0. The resulting list is [0.0, 0.5, 1.0], which Python prints as [0.0, 0.5, 1.0].

Machine Learning/data-preparation/feature-engineering

Trace the following Python code step by step. The mapping dictionary is built via enumerate, so categories[0] maps to index 0, categories[1] to index 1, etc. What is the exact output of the print statement?#

categories = ['cat', 'dog', 'fish']
data = ['dog', 'cat', 'fish', 'dog']
mapping = {cat: i for i, cat in enumerate(categories)}
one_hot = []
for item in data:
    vector = [0] * len(categories)
    vector[mapping[item]] = 1
    one_hot.append(vector)
print(one_hot)
Show answer
[[0, 1, 0], [1, 0, 0], [0, 0, 1], [0, 1, 0]]
Why:

The mapping is built deterministically by enumerate: {'cat': 0, 'dog': 1, 'fish': 2}. Each data item produces a 3-element vector with a 1 at the mapped index. 'dog' → [0,1,0], 'cat' → [1,0,0], 'fish' → [0,0,1], 'dog' → [0,1,0]. The printed output is [[0, 1, 0], [1, 0, 0], [0, 0, 1], [0, 1, 0]].

Machine Learning/data-preparation/train-val-test-split

In a standard three-way data split, the model is fit on the training set, hyperparameters are tuned using the _____ set, and the test set is reserved for final evaluation.#

Show answer

In a standard three-way data split, the model is fit on the training set, hyperparameters are tuned using the validation set, and the test set is reserved for final evaluation.

Why:

Hyperparameter tuning and model selection are performed against the validation set so that the test set remains untouched for an unbiased final performance estimate.

Machine Learning/data-preparation/train-val-test-split

After a model is selected and all tuning is complete, the _____ set is used ideally only once to estimate the model's generalization performance on unseen data.#

Show answer

After a model is selected and all tuning is complete, the test set is used ideally only once to estimate the model's generalization performance on unseen data.

Why:

The test set is kept unseen until the very end; using it repeatedly risks overfitting to it and would inflate the reported generalization performance.

Machine Learning/model-evaluation/bias-variance-tradeoff

A linear regression model has high training error and high test error, both similar in magnitude. What does this pattern indicate?#

Options

Show answer

High and similar train/test error indicates high bias — the linear model's assumptions are too simple to capture the real relationship, so it performs poorly even on data it has already seen. That's underfitting. High variance (overfitting) looks the opposite: low training error but much higher test error, because the model fit noise specific to the training set. Data leakage instead shows up as suspiciously good test performance, not high error on both sides.

Why:

High bias means the model's assumptions (here, linearity) are too simplistic to capture the real relationship in the data, so it performs poorly even on data it has already seen — that's underfitting, and it shows up as high error on both train and test that are close in magnitude. High variance (overfitting) looks the opposite: low training error but much higher test error, because the model fit noise specific to the training set that doesn't generalize. Similar train/test error alone doesn't mean 'calibrated' — if both are similarly high, that's still a problem, just a different one (bias, not variance) than similar-and-low error would indicate. Data leakage typically shows up as suspiciously good test performance, the opposite of this scenario.

Machine Learning/model-evaluation/evaluation-metrics

What does the F1 score represent, and when would you reach for it instead of reporting precision and recall separately?#

Options

Show answer

The F1 score is the harmonic mean of precision and recall, 2 × (precision × recall) / (precision + recall). Unlike an arithmetic mean, the harmonic mean penalizes a large imbalance between the two — precision 1.0 with recall 0.0 gets an arithmetic mean of 0.5 but an F1 of 0, correctly reflecting a useless model. Reach for it when you have no strong reason to weight false positives differently from false negatives; when you do, report precision and recall separately instead, since F1 alone hides that asymmetry.

Why:

F1 = 2 × (precision × recall) / (precision + recall) — the harmonic mean, which (unlike an arithmetic mean) penalizes a large imbalance between the two: a model with precision 1.0 and recall 0.0 gets an arithmetic mean of 0.5 but an F1 of 0, correctly reflecting that it's useless. It's the right single-number summary when you don't have a strong reason to weight false positives differently from false negatives; when you do (like the disease-screening case, where recall matters far more), reporting F1 alone hides that asymmetry and you should report precision and recall separately, or use a weighted variant like F-beta. F1 is a classification metric with no direct regression analogue.

Machine Learning/model-evaluation/bias-variance-tradeoff

A model with high bias is generally described as underfitting the data.#

Options

Show answer

True. High bias means a model's assumptions are too simple to capture the real relationship in the data, so it performs poorly even on the training set — that's underfitting by definition. It's the opposite failure mode from high variance (overfitting), where a model fits the training data closely but fails to generalize.

Why:

True. Bias measures the error introduced by a model's simplifying assumptions being too far from the true relationship — a high-bias model is too simple to capture the pattern in the data, so it performs poorly even on the training set it was fit to. That's the definition of underfitting. This is the opposite failure mode from high variance (overfitting), where the model is complex enough to fit training data very closely but fails to generalize to new data.

Machine Learning/data-preparation/train-val-test-split

Order the standard steps of training and evaluating a supervised model so the reported performance is a trustworthy estimate of real-world generalization.#

Put these in order

Show answer

A trustworthy supervised-learning workflow splits the data into train, validation, and test sets before any fitting, trains candidate models on the training set, tunes hyperparameters and picks a model using validation-set performance, and evaluates the final chosen model exactly once on the held-out test set. Touching the test set only once at the end is what keeps it a genuine estimate of real-world generalization — using it repeatedly during tuning turns it into a second validation set and overstates real performance.

Why:

The order matters because each set has exactly one job: the split must happen before any fitting so no set's information leaks into another; the training set is what parameters are learned from; the validation set is what model/hyperparameter decisions are made against, since using it for those decisions repeatedly (unlike training) is expected and intended; and the test set is touched exactly once, at the very end, specifically because repeatedly checking it and adjusting the model in response would turn it into a second validation set in disguise — an optimistic, no-longer-trustworthy estimate of how the model performs on genuinely unseen data. Reversing steps (e.g., peeking at test performance during tuning) is a common, subtle way real-world offline metrics end up overstating what the model will actually do in production.

Machine Learning/data-preparation/data-leakage

What is target leakage in the context of train/test split during data preparation, and how do you prevent it when applying a scaler (e.g., StandardScaler)?#

Show answer

Fit the scaler (or any transformer) on the training set only, then use its learned parameters to transform both training and test data. If you fit on the combined data, the scaler's mean/std incorporate test-set information, which leaks statistics about the test distribution into training and yields overoptimistic evaluation.

Why:

Target (or data) leakage occurs when information from outside the training set — most commonly the test set — influences the training process. When preprocessing with a scaler, fitting on the full dataset means the computed mean and standard deviation include test-set values, giving the model indirect knowledge of the test distribution. The fix is to fit the transformer on the training split only and then apply (transform) it to both splits using those learned parameters. In a pipeline, this is typically handled by fitting the entire pipeline on training data only.

Machine Learning/algorithm-tradeoffs/model-selection-tradeoffs

You are selecting a model for a supervised regression task. You currently have a simple linear regression model that produces a high error on both the training set and the held-out validation set. You are considering switching to a more flexible model (e.g., a deep decision tree or a high-degree polynomial model). Which of the following statements are correct about this situation?#

Options

Pick every one that applies.

Show answer

The correct statements are that the linear model is likely underfitting (high bias) and that a more flexible model may reduce training error but increase validation error through overfitting. When both training and validation error are high, the model lacks capacity to capture the underlying pattern — a hallmark of high bias. A more flexible model can fix this, but too much flexibility risks high variance, where training error drops while validation error climbs.

Why:

When a model has high error on both training and validation sets, it is typically underfitting — it lacks the capacity to capture the underlying pattern, which corresponds to high bias (option a is correct). Switching to a more flexible model can reduce this bias and lower training error, but if the model becomes too complex it may memorize noise, leading to overfitting: training error drops while validation error can rise due to high variance (option c is correct). Option b is wrong because increased flexibility does not guarantee lower validation error — it can worsen it through overfitting. Option d is wrong because high error on both training and validation sets indicates high bias (underfitting), not high variance; high variance would manifest as low training error but high validation error.

Machine Learning/model-evaluation/evaluation-metrics

You're building a screening model for a rare, serious disease, where missing a true case is far worse than a false alarm that gets ruled out by a follow-up test. Which metric should you prioritize optimizing, and why?#

Options

Show answer

Recall is the right metric here — it measures the fraction of true positive cases the model catches, and maximizing it minimizes the missed-disease-case error that's catastrophic in this scenario. Precision matters more when a false positive is the costly error, which is the opposite priority to a rare-disease screen where a false positive only triggers a cheap follow-up test. Accuracy is a poor fit for rare diseases specifically, since predicting 'negative' for everyone can still score high while catching zero true cases.

Why:

Recall directly measures the fraction of true positive cases the model successfully identifies — maximizing it minimizes false negatives, which is exactly the error that's catastrophic here (a missed disease case with no follow-up). Precision instead measures how trustworthy a positive prediction is, which matters more when a false positive is the costly error (e.g., an expensive irreversible action taken on a false alarm) — the opposite priority from this scenario, where a false positive just triggers a cheap follow-up test. Accuracy is a poor fit for rare-disease screening because the disease is rare: a model that predicts 'negative' for everyone can still score high accuracy while catching zero true cases. Precision and recall usually trade off against each other as the classification threshold moves, not move together — raising recall (lowering the threshold to catch more positives) typically lowers precision (more false positives slip through).

Machine Learning/overfitting-regularization/overfitting-underfitting

A model has near-zero training error but much higher validation error — classic overfitting. Which of these are legitimate ways to address it? Select all that apply.#

Options

Pick every one that applies.

Show answer

Regularization, collecting more training data, reducing model complexity, and cross-validation with early stopping are all legitimate fixes for overfitting — they either constrain the model's capacity to memorize noise, reduce the noise-to-signal ratio it can overfit to, or halt training once generalization starts to degrade. Evaluating only on the training set isn't a fix at all: it discards the diagnostic signal that revealed the problem, so a badly overfit model can go undetected until it fails in production.

Why:

Regularization (a), more data (b), reduced complexity (c), and cross-validation with early stopping (e) are all standard, legitimate levers against overfitting: they either constrain the model's capacity to memorize noise, give it less noise-to-signal ratio to overfit to, or stop training at the point generalization starts to degrade. Option d isn't a fix at all — it's discarding the diagnostic signal that revealed the problem in the first place; a model that's never evaluated on held-out data can be badly overfit without anyone finding out until it fails in production.

Machine Learning/model-evaluation/evaluation-metrics

On a dataset where 99% of examples belong to one class, a model that always predicts that majority class can still achieve 99% accuracy while being useless for the minority class.#

Options

Show answer

True. On a 99%-majority-class dataset, a model that always predicts the majority class achieves 99% accuracy while catching zero instances of the minority class. This is why accuracy alone is misleading on imbalanced data, and why metrics like precision, recall, F1, or AUC-ROC — which reflect performance on the minority class specifically — are the preferred metrics in that scenario instead.

Why:

True. Accuracy just measures the fraction of all predictions that are correct, and on heavily imbalanced data, predicting the majority class every time trivially hits an accuracy equal to the majority class's share of the data — 99% here — while catching zero instances of the minority class (0% recall on it). This is exactly why accuracy alone is a misleading metric on imbalanced datasets, and why metrics like precision, recall, F1, or AUC-ROC (which account for how the model performs on the minority class specifically) are preferred for that scenario.

Machine Learning/model-evaluation/evaluation-metrics

Explain precision and recall in your own words — what each measures and how they trade off against each other as you move a classifier's decision threshold.#

Show answer

Precision is TP / (TP + FP) — of everything the model labeled positive, what fraction was actually positive. It answers 'when the model says yes, can I trust it?' Recall is TP / (TP + FN) — of everything that was actually positive, what fraction did the model catch. It answers 'of the real positives out there, how many did the model find?' Moving the decision threshold trades one against the other: lowering the threshold makes the model label more things positive, which typically increases recall (catching more true positives) but decreases precision (also catching more false positives along with them); raising the threshold does the reverse — fewer, more confident positive predictions, so precision goes up but recall goes down as some true positives fall below the now-stricter bar. The right point on that tradeoff curve depends entirely on which error — a false positive or a false negative — is more costly for the specific problem.

Why:

This tests whether the definitions are actually understood, not memorized as formulas: precision is about trustworthiness of a positive prediction, recall is about coverage of the real positives, and they trade off as the classification threshold moves. A strong answer explains the threshold mechanism specifically (why lowering it raises recall and lowers precision), since that's the part that shows genuine understanding rather than recalled definitions, and connects the choice of operating point to which error type is costlier for the actual problem.

Machine Learning/data-preparation/feature-engineering

Explain what feature engineering is and give a concrete example of a raw field that becomes more useful to a model after transformation, and why.#

Show answer

Feature engineering is transforming raw data into representations that make the underlying pattern easier for a model to learn, rather than feeding it unprocessed inputs and hoping the model figures out the structure itself. A concrete example: a raw timestamp field for a fraud-detection model is mostly useless to a linear model as-is (it's a huge, roughly-continuous number with no obvious relationship to fraud), but deriving hour_of_day, day_of_week, and is_weekend from it exposes patterns a model can actually use directly — fraud rates often differ meaningfully by time of day or day of week, and those derived features let even a simple model pick up on that signal instead of requiring it to somehow learn cyclical structure from a raw epoch integer. Good feature engineering often has a bigger impact on model performance than switching to a fancier algorithm, especially for tabular data with a simpler model.

Why:

The concept is straightforward, but a strong answer grounds it in a concrete before/after example rather than staying abstract — showing a raw field that's hard for a model to use directly, and a derived version that exposes the actual signal. The point about feature engineering often mattering more than algorithm choice (especially for tabular/non-deep-learning problems) is the workplace-relevant takeaway that separates someone who's applied this from someone reciting a definition.

Machine Learning/model-evaluation/evaluation-metrics

What does AUC-ROC measure, and what do 0.5 and 1.0 mean?#

Show answer

The ROC curve plots true positive rate against false positive rate as the classification threshold sweeps across all possible values; AUC-ROC is the area under that curve. It measures how well the model ranks positive examples above negative ones across every possible threshold, independent of any single threshold choice. AUC = 0.5 means the model ranks no better than random guessing; AUC = 1.0 means the model perfectly separates every positive from every negative at some threshold. It's a useful complement to a single precision/recall number because it summarizes performance across the whole range of possible operating points, not just the one you happened to pick.

Why:

AUC-ROC's threshold-independence is what makes it useful for comparing models before you've committed to an operating point, and its probabilistic interpretation — the probability a randomly chosen positive example is ranked above a randomly chosen negative one — is a common interview follow-up.

Machine Learning/data-preparation/train-val-test-split

You are building a binary classifier to predict customer churn for a SaaS product. Your dataset contains 500,000 rows of monthly customer snapshots: each row is (customer_id, month, features, churn_label). The same customer_id appears across multiple months (on average 10 rows per customer). A junior engineer proposes randomly shuffling all 500,000 rows and splitting 70/15/15 into train/validation/test. Identify the core problem with this approach, then design a correct train/validation/test split strategy. Specify exactly how you partition the data, why group structure matters, and how you would handle temporal ordering if the business also cares about training only on past data to predict future churn.#

Show answer

The core problem is group leakage: because each customer_id appears in ~10 rows, a random row-level split puts some snapshots of the same customer in train and others in test. The model can then learn customer-specific idiosyncrasies (or even memorize features that are nearly constant for a given customer) and appear to generalize when it is actually recognizing customers it has already seen, inflating test metrics. The correct approach is a group-aware split: partition the set of unique customer_ids into three disjoint groups (e.g., 70/15/15), then assign every row belonging to a customer to whichever split that customer's id was assigned to. This guarantees no customer spans more than one split. In scikit-learn this can be done with GroupShuffleSplit or by manually shuffling unique ids and slicing. If the business also needs the model to predict future churn from past data, I would additionally enforce temporal ordering: use the earliest N months for training, the next M months for validation, and the latest K months for testing — still at the customer-group level to prevent any single customer from appearing in multiple time-based splits. A practical combined strategy is a temporal split for train vs. holdout, with group-aware partitioning within each temporal window. Finally, because churn is typically rare (e.g., 2-5%), I would stratify each split by the churn_label — or at minimum verify that the positive-class rate is similar across all three splits — so that AUC and precision-recall metrics on validation and test are computed on a sufficient number of positive examples.

Why:

This question tests whether the candidate can identify group-level data leakage, design a group-aware split, reason about temporal ordering, and account for class imbalance — all core data-preparation skills at the mid-level.

Machine Learning/data-preparation/train-val-test-split

You are tasked with building an image-based defect-detection model for a manufacturing line. You have 20,000 labeled images collected over 6 months from 3 different factories (A, B, C). Defects are rare (~3% positive rate). The business requirement is that the model must generalize to a 4th factory (D) that will open in 2 months, for which you have zero labeled data today. Design a train/validation/test split strategy that (a) gives an honest estimate of generalization to a brand-new factory, and (b) avoids both optimistic and pessimistic bias. Explain what each split simulates, how you would use the three existing factories, and what metrics you would trust or distrust.#

Show answer

To honestly estimate generalization to an unseen factory, I would hold out one entire factory — say factory C — as the test set, never used during training or model selection. This simulates the deployment scenario: the model is evaluated on data from a distribution it has never seen, just as it will be for factory D. The remaining two factories (A and B) would be split into train and validation: I might use A for training and B for validation, or combine A+B and do a group-aware split if there is within-factory structure (e.g., different production lines). The validation set drives hyperparameter tuning, threshold selection, and model selection; the test set (factory C) is evaluated exactly once at the end to report the final generalization estimate. Because defects are rare (~3%), I would ensure each split has a proportionally similar positive rate (stratified by label within each factory's images), and I would apply any oversampling, undersampling, or class weighting only to the training set — never to validation or test, which must reflect the true production distribution. For metrics, I would distrust raw accuracy (since a model that predicts 'no defect' always gets 97% accuracy) and instead rely on precision-recall AUC, F1 at a chosen operating point, and per-factory confusion matrices. I would also acknowledge that a single held-out factory gives a high-variance estimate of generalization — n=1 factory. If compute permits, I would run leave-one-factory-out cross-validation across all three factories to get three estimates and their spread, which gives a more robust picture of how much performance varies across unseen factories.

Why:

This question tests whether the candidate can design a domain-aware split that simulates real deployment to an unseen location, handle class imbalance correctly across splits, and critically evaluate the reliability of the resulting generalization estimate.

Machine Learning/data-preparation/data-leakage

This pipeline reports a suspiciously strong test accuracy that doesn't hold up once the model ships. Which line causes the data leakage?#

1| scaler = StandardScaler()
2| X_scaled = scaler.fit_transform(X)
3|
4| X_train, X_test, y_train, y_test = train_test_split(
5|     X_scaled, y, test_size=0.2, random_state=42
6| )
7|
8| model = LogisticRegression()
9| model.fit(X_train, y_train)
10| print(model.score(X_test, y_test))

Options

Show answer

Line 2 — fit_transform computes the mean/std used for scaling across the FULL dataset, including what becomes the test set, so information about the test distribution leaks into how training data is scaled

Why:

StandardScaler.fit_transform on line 2 computes the mean and standard deviation used for scaling from the entire dataset X — before the train/test split even happens. That means the test set's own statistics influenced the scaling parameters applied to the training data, a subtle form of data leakage: the model is trained with information (aggregate statistics of the test set) that wouldn't be available at real prediction time. It inflates test performance because the test set is no longer a genuinely unseen distribution to the pipeline. The fix is to fit the scaler only on the training set (scaler.fit(X_train)), then use that already-fit scaler to .transform() (not re-fit) the test set — so the test set's statistics never influence anything learned from or applied to the training data. This exact bug (fitting any preprocessing step before splitting) is one of the most common real-world sources of an offline metric that doesn't hold up in production.

Machine Learning/data-preparation/data-leakage

A churn-prediction model scores 98% AUC in offline evaluation but performs no better than random once deployed for real, forward-looking predictions. Which line is the root cause?#

1| features = [
2|     'account_age_days',
3|     'monthly_spend',
4|     'support_tickets_last_30d',
5|     'days_since_cancellation_request',
6| ]
7| X = customers[features]
8| y = customers['churned']
9| model.fit(X_train, y_train)

Options

Show answer

Line 5 — days_since_cancellation_request is only populated for customers who already requested a cancellation, so it directly encodes the label being predicted and wouldn't exist at real prediction time

Why:

days_since_cancellation_request is populated specifically because a customer already initiated a cancellation — it's a near-direct proxy for (or downstream consequence of) the churn label itself, not information that exists at the point in time a real, forward-looking prediction would need to be made. This is target leakage: a feature that's only available because the outcome already happened (or is derived from data generated after the event you're trying to predict). Offline, the model looks excellent because this one feature is almost as good as the label; in production, making a genuinely forward-looking prediction about a customer who hasn't yet requested cancellation, that feature is absent or meaningless, and the model's real skill collapses to near-random. The fix is to audit every feature for whether it could plausibly be known at the actual moment of prediction, and drop anything (like this one) that's really just a restatement of the outcome.

Machine Learning/algorithm-tradeoffs/model-selection-tradeoffs

L1 regularization (Lasso) can drive some learned coefficients to exactly zero, producing a sparse model, whereas L2 regularization (Ridge) shrinks all coefficients toward zero but generally does not set any coefficient to exactly zero (assuming no exact collinearity degeneracies).#

Options

Show answer

True. L1 regularization can shrink coefficients to exactly zero because its diamond-shaped constraint region has corners on the axes, yielding sparse models. L2 regularization's circular constraint region touches the loss contour away from the axes, so it shrinks coefficients but rarely sets them to exactly zero. This geometric difference is the basis of L1-based feature selection.

Why:

The L1 penalty's diamond-shaped constraint region has corners on the axes, so the optimal solution frequently lands exactly on an axis where some coefficients are zero. The L2 penalty's circular constraint region is smooth and tangent to the loss contour almost everywhere except on axes, so coefficients are shrunk but not zeroed. This geometric difference is why L1 induces sparsity and L2 does not.

Machine Learning/data-preparation/feature-engineering

The function below imputes missing values and then splits the data into train/test sets. It contains a feature-engineering bug that causes data leakage. Which option correctly identifies the bug?#

from sklearn.imputer import SimpleImputer
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np

def preprocess(df, target_col):
    features = df.drop(columns=[target_col])
    target = df[target_col]
    
    imputer = SimpleImputer(strategy='mean')
    features_imputed = imputer.fit_transform(features)
    
    X_train, X_test, y_train, y_test = train_test_split(
        features_imputed, target, test_size=0.2, random_state=42)
    return X_train, X_test, y_train, y_test

Options

Show answer

Line 10: features_imputed = imputer.fit_transform(features) — the imputer is fit on the full dataset before the train/test split, leaking test-set statistics into training features.

Why:

Option (b) is correct. On line 10, imputer.fit_transform(features) computes column means from the entire dataset — including rows that will later become the test set — and uses those means to fill missing values. This leaks test-set distributional information into the training features. The correct approach is to split first, then call imputer.fit_transform(X_train) on the training data and imputer.transform(X_test) on the test data. Option (a) is wrong because dropping the target column from features is correct practice. Option (c) is wrong because a fixed random_state ensures reproducibility, not bias. Option (d) is wrong because mean imputation is a valid strategy; the issue is leakage, not the choice of statistic.

Machine Learning/algorithm-tradeoffs/model-selection-tradeoffs

In statistical model selection, AIC and BIC are both penalized-likelihood criteria, yet they optimize for fundamentally different asymptotic goals. Define the precise sense in which AIC is 'efficient' and BIC is 'consistent' as model selection criteria. Then identify the specific mathematical term (relative to sample size n) in each criterion's penalty that produces this divergence, and state the key assumption under which BIC's consistency guarantee holds but AIC's efficiency guarantee does not require.#

Show answer

AIC is asymptotically efficient: it selects the model that minimizes expected Kullback-Leibler divergence from the true data-generating process, achieving optimal out-of-sample prediction even when the true model is not among the candidates. BIC is model-selection consistent: when the true model is among the candidates, BIC selects it with probability approaching 1 as n → ∞. The divergence comes from the penalty terms: AIC penalizes by 2k (independent of n), while BIC penalizes by k·log(n). Because log(n) grows with n, BIC's penalty becomes increasingly severe, driving it toward parsimony and consistency. BIC's consistency guarantee requires the assumption that the true model is in the candidate set (the 'true model exists' assumption) plus standard regularity conditions; AIC makes no such assumption and instead optimizes for prediction.

Why:

AIC's penalty 2k is constant in n, so it targets predictive optimality (efficiency) regardless of whether the true model is in the candidate set. BIC's penalty k·log(n) grows with n, which makes it increasingly favor the simplest model that adequately fits, yielding consistency (selecting the true model with probability → 1) under the assumption that the true model is among the candidates. The log(n) term is the key driver of the difference.

Machine Learning/data-preparation/data-leakage

You are building a time-series forecasting pipeline (e.g., predicting daily sales from historical data). A common source of data leakage in time-series settings is look-ahead bias: the model or any preprocessing step "sees" future information that would not be available at prediction time. Below are four steps, each of which strictly depends on the completion of the previous one — reordering any adjacent pair introduces data leakage or renders the pipeline invalid. Place them in the correct temporal order to produce a leakage-free pipeline.#

Put these in order

Show answer

The correct order is: (1) chronologically split the data so all test timestamps are strictly future-dated relative to training data, (2) tune hyperparameters via rolling-origin cross-validation entirely within the training period, (3) retrain on the full training period with the best hyperparameters, and (4) score on the held-out future test set. Splitting first prevents look-ahead bias; CV on training-only data prevents test leakage; retraining after tuning ensures the deployed model uses selected hyperparameters; and final test evaluation must come last to keep the test set untouched until the very end.

Why:

The chronological split (c) must come first: without it, any downstream step could train on or tune against future data, introducing look-ahead bias. Cross-validation (d) strictly follows because it must operate only on the training period — and rolling-origin CV itself enforces temporal ordering within training, preventing leakage from future folds into past folds. Retraining (a) strictly follows CV because it uses the hyperparameters selected during tuning; retraining before tuning would mean the selected hyperparameters are irrelevant to the deployed model. Final scoring on the test set (b) strictly follows retraining because you need the finished model before you can evaluate it, and touching the test set earlier (e.g., for model selection or tuning) leaks test information into the training process. Each adjacent pair has a hard dependency: c→d (must split before tuning on training-only data), d→a (must select hyperparameters before final training), a→b (must have a trained model before scoring).

Related interview questions

The other 75 questions

This page shows 25. A free account opens the rest and marks your answers, which a page of answers can't do. Miss one and it returns a few days later, then a week after that, until you stop missing it.

Start free

Free · the whole bank · 100 graded answers per 30 days · written feedback and job-ad quizzes on the paid plan

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.