Skip to content

Hard Machine Learning Interview Questions

45 hard questions with answers. Design, trade-off and deep-dive questions asked for senior roles and at top product companies.

Topics in the hard set

Model Evaluation and Tuning: 9 Decision Trees and Ensembles: 7 Clustering and Dimensionality Reduction: 7 MLOps and Deployment: 6 Regression Models: 5 Classification Models: 5 ML Fundamentals: 3 Data Preprocessing and Feature Engineering: 3
Solved — hardStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the no free lunch theorem and what does it mean in practice?

Save to ▾
Show answer
It states that no single algorithm is best for every problem when averaged over all possible problems. In practice it means you should try several model families, start with a simple baseline, and choose based on validation results for your data. For tabular data gradient boosting often wins, but a logistic regression may be preferred if interpretability matters more.
02

What is the difference between a generative and a discriminative model?

Save to ▾
Show answer
A discriminative model learns the decision boundary or P(y|x) directly, such as logistic regression or SVM. A generative model learns how data is produced, P(x|y) and P(y), and can generate new samples, such as Naive Bayes or Gaussian mixture models. Discriminative models usually give better accuracy with enough data, while generative models handle missing data and small samples better.
03

Your training loss is not decreasing at all. What could be wrong?

Save to ▾
Show answer
Common causes are a learning rate that is too high or too low, unscaled features, a bug in labels or feature alignment, wrong loss for the task, or data that has been shuffled away from its labels. I would try overfitting a tiny subset first; if the model cannot even fit 50 rows, there is a bug. Then check scaling, learning rate and gradient values.
04

What is target encoding and how do you avoid leakage with it?

Save to ▾
Show answer
Target encoding replaces each category with the mean target value for that category, which works well for high-cardinality features. It leaks if computed on the full data because each row sees its own label. Avoid this by computing encodings out-of-fold within cross-validation and adding smoothing toward the global mean for rare categories. scikit-learn 1.3+ has TargetEncoder with built-in cross-fitting.
05

New categories appear in production that were not in training data. How do you handle it?

Save to ▾
Show answer
Make the encoder tolerant: OneHotEncoder with handle_unknown='ignore' or infrequent_if_exist, or map unseen values to an 'Other' bucket. Monitor the share of unseen categories as a drift signal. If new categories become common, such as a new city launch, retrain with fresh data. Tests in the inference pipeline should include unseen values so the service never crashes.
06

Why does L1 regularisation produce sparse models while L2 does not?

Save to ▾
Show answer
The L1 constraint region is a diamond with corners on the axes, so the optimal point often lands on a corner where some coefficients are exactly zero. The L2 region is a circle with no corners, so coefficients shrink smoothly but stay non-zero. In gradient terms, L1 applies a constant push toward zero regardless of size, while L2's push becomes tiny as weights get small.
07

When would you use Huber or quantile regression instead of OLS?

Save to ▾
Show answer
Huber regression uses squared loss for small errors and absolute loss for large ones, so it resists outliers while staying smooth. Quantile regression predicts a chosen percentile, such as the 90th percentile of delivery time, which is useful for setting safe promises or prediction intervals. Gradient boosting libraries support both losses for non-linear versions.
08

Lasso dropped a feature the business considers very important. How do you handle it?

Save to ▾
Show answer
Lasso often keeps only one of a group of correlated features, so the dropped feature may be redundant rather than useless. I would check correlations, try Elastic Net which keeps correlated groups, and compare cross-validated performance with the feature forced in. I would explain the trade-off clearly; if the accuracy difference is small, keeping the feature for trust and interpretability is reasonable.
09

You need prediction intervals, not just point estimates, for delivery time. How?

Save to ▾
Show answer
Options are quantile regression, training separate models for the 10th and 90th percentiles with GradientBoostingRegressor(loss='quantile') or LightGBM; conformal prediction, which wraps any model and gives intervals with guaranteed coverage; or bootstrapping. I would check calibration: about 80 percent of actual values should fall within an 80 percent interval on a holdout set.
10

How do you create lag and rolling features for a sales forecasting model in pandas?

Save to ▾
Show answer
Sort by item and date, then shift so features use only past values. df = df.sort_values(['item', 'date']) g = df.groupby('item')['sales'] df['lag_7'] = g.shift(7) df['roll_mean_28'] = g.transform(lambda s: s.shift(1).rolling(28).mean()) The shift before rolling prevents the current day's sales from leaking into its own feature.
11

What is the kernel trick?

Save to ▾
Show answer
The kernel trick computes dot products of data in a high-dimensional feature space without explicitly transforming the data, using a kernel function such as RBF, exp(-gamma times squared distance). This lets linear algorithms like SVM learn non-linear boundaries efficiently. In RBF SVMs, larger gamma makes each point's influence more local, which can lead to overfitting.
12

What is probability calibration and why does it matter?

Save to ▾
Show answer
A calibrated model's predicted probabilities match real frequencies: of cases scored 0.8, about 80 percent should be positive. It matters when scores drive decisions like credit limits or expected loss. Random forests and SVMs are often poorly calibrated. Fix it with CalibratedClassifierCV using Platt scaling (sigmoid) or isotonic regression, and check with a reliability curve or Brier score.
13

Your classifier works well overall but poorly for one customer segment. What do you do?

Save to ▾
Show answer
I would measure metrics per segment to confirm, then check if that segment is under-represented or has different feature distributions. Fixes include collecting more data, sample weighting, segment-specific features, or a separate model if the behaviour is truly different. If the segment relates to a protected attribute, I would also review fairness metrics and involve the compliance team.
14

A credit model's probability of 0.3 is used to set interest rates, but defaults in that band are 12 percent. What is wrong?

Save to ▾
Show answer
The model is poorly calibrated: it ranks customers but its probabilities are not reliable. Since pricing depends on actual probabilities, I would calibrate it with isotonic regression or Platt scaling on a held-out set and validate with a reliability curve and Brier score. I would also check whether the default rate has drifted since training, which would require retraining.
15

How do you apply SMOTE correctly without leakage?

Save to ▾
Show answer
Use an imbalanced-learn pipeline so oversampling happens only on training folds. from imblearn.pipeline import Pipeline from imblearn.over_sampling import SMOTE from sklearn.model_selection import cross_val_score pipe = Pipeline([('pre', pre), ('smote', SMOTE(random_state=42)), ('clf', LogisticRegression(max_iter=1000))]) print(cross_val_score(pipe, X, y, cv=5, scoring='average_precision').mean()) Applying SMOTE before splitting puts synthetic copies of test points into training.
16

Which hyperparameters matter most when tuning a gradient boosting model?

Save to ▾
Show answer
The key ones are learning_rate and number of trees, tuned together with early stopping; tree complexity through max_depth or num_leaves and min_child_samples; and randomness through subsample and colsample_bytree. Regularisation terms like lambda and alpha help on noisy data. A common approach is to fix a small learning rate such as 0.05, use early stopping for trees, then tune complexity.
17

Why can impurity-based feature importance be misleading?

Save to ▾
Show answer
Impurity-based importance is computed on training data and favours high-cardinality or continuous features, which offer more split points, even if they are noise. It also splits credit between correlated features. Permutation importance on validation data, which measures the score drop when a feature is shuffled, is more reliable, and SHAP values give consistent per-prediction attributions.
18

What is stacking and when is it worth it?

Save to ▾
Show answer
Stacking trains several diverse base models and then a meta-model on their out-of-fold predictions to combine them. It often gives a small accuracy gain, common in competitions. In production it adds complexity, latency and maintenance, so it is worth it only when the gain has clear business value. scikit-learn provides StackingClassifier and StackingRegressor.
19

Business users do not trust a gradient boosting model because it is a black box. How do you help?

Save to ▾
Show answer
I would use SHAP to show global drivers with a summary plot and explain individual decisions with waterfall plots, such as why one applicant got a high risk score. I would also check that the top drivers make business sense, add monotonic constraints where logic requires it, and share a few real case examples. If trust is still an issue, a scorecard model can serve as a transparent benchmark.
20

Your tree model predicts higher risk for customers with higher income, which is illogical. What do you do?

Save to ▾
Show answer
First check whether data supports it, perhaps due to confounding or a small segment. If the relationship should be one-directional for business or regulatory reasons, I would apply monotonic constraints, available in XGBoost, LightGBM and HistGradientBoosting, so risk can only decrease with income. Then compare validation metrics; usually the loss is small and the model becomes more trustworthy.
21

Explain a single prediction with SHAP for a tree model.

Save to ▾
Show answer
import shap explainer = shap.TreeExplainer(model) sv = explainer(X_val) shap.plots.waterfall(sv[0]) shap.plots.beeswarm(sv) The waterfall shows how each feature pushes one prediction up or down from the base value; the beeswarm shows global importance and direction. TreeExplainer is fast and exact for tree ensembles.
22

What is the difference between PCA and t-SNE or UMAP?

Save to ▾
Show answer
PCA is a linear method that preserves global variance, is fast, deterministic and can transform new data, so it is used for preprocessing. t-SNE and UMAP are non-linear methods that preserve local neighbourhoods, producing good 2D visualisations of clusters. t-SNE distances between clusters are not meaningful. UMAP is faster, keeps more global structure and can transform new points.
23

What is a Gaussian Mixture Model and how is it different from k-means?

Save to ▾
Show answer
A GMM assumes data comes from a mix of Gaussian distributions and fits their means, covariances and weights with the Expectation-Maximisation algorithm. Unlike k-means' hard assignments, GMM gives soft probabilities of belonging to each cluster and can model elliptical clusters of different sizes. You can choose the number of components using BIC or AIC.
24

How do you evaluate clustering when there are no labels?

Save to ▾
Show answer
Use internal metrics: silhouette score, Davies-Bouldin index (lower is better) and Calinski-Harabasz index (higher is better). Check stability by re-clustering on bootstrap samples. Most important is external usefulness: profile each cluster with key statistics and check whether business teams find the segments distinct and actionable, for example different response to a campaign.
25

You need to detect unusual transactions but have no fraud labels. What do you do?

Save to ▾
Show answer
I would start with unsupervised anomaly detection: Isolation Forest or Local Outlier Factor on features like amount relative to the customer's usual spend, time of day, new device and merchant risk. I would set the threshold based on what the review team can handle, collect investigator feedback as labels, and move to a supervised model once enough labelled cases exist.
26

The segments you built six months ago no longer match customer behaviour. What do you do?

Save to ▾
Show answer
I would measure drift by comparing feature distributions and segment sizes over time. Then refit clustering on recent data and map new clusters to old ones by centroid similarity so business names stay consistent. I would set up a quarterly refresh with stability checks and alert when segment sizes shift sharply, and explain any renamed or merged segments to stakeholders.
27

Run DBSCAN and count clusters and noise points.

Save to ▾
Show answer
from sklearn.cluster import DBSCAN import numpy as np db = DBSCAN(eps=0.5, min_samples=10).fit(Xs) labels = db.labels_ n_clusters = len(set(labels)) - (1 if -1 in labels else 0) print(n_clusters, 'clusters,', np.sum(labels == -1), 'noise') Pick eps from the knee of a sorted k-nearest-neighbour distance plot.
28

Your preprocessing works in notebooks but gives different results in production. Why?

Save to ▾
Show answer
Common causes are preprocessing written separately in two places, statistics like means recomputed on production data instead of using training values, different library versions, or different column order and data types. The fix is to save one fitted Pipeline with preprocessing and model together, pin versions, validate input schema, and test that the saved pipeline gives identical outputs on sample rows.
29

What is nested cross-validation and when do you need it?

Save to ▾
Show answer
Nested CV has an inner loop that tunes hyperparameters and an outer loop that evaluates the whole tuning process on unseen folds. It gives an unbiased performance estimate when you tune heavily on small data, because a normal CV score used both to tune and to report is optimistic. It is expensive, so it is mainly used for small datasets or research reporting.
30

How do you compare two models fairly?

Save to ▾
Show answer
Use the same data splits and folds, the same preprocessing inside pipelines and the same metric tied to the business goal. Look at the mean and standard deviation across folds, not one number, and use a paired test like a corrected t-test or bootstrap on the fold differences. Also compare cost factors: latency, memory, interpretability and maintenance.
31

What fairness checks would you run on a model that affects people?

Save to ▾
Show answer
Compare metrics across groups such as gender, age band or region: approval rate (demographic parity), true positive rate (equal opportunity) and false positive rate. Check calibration per group too. Remove or audit proxy features like pin code that may stand in for protected attributes. Document findings in a model card, and involve legal or compliance teams, especially for lending and hiring use cases.
32

Your cross-validation score is 0.85 but the test score is 0.70. What could explain it?

Save to ▾
Show answer
Possible causes: leakage inside CV, such as preprocessing or feature selection fit outside folds; repeated tuning that overfit the CV folds; a test set from a different time period or population; or duplicate entities across folds but not test. I would check pipeline structure, switch to time-based or group splits that match how test data differs, and compare feature distributions between the two sets.
33

An A/B test of a new recommendation model shows no significant uplift despite better offline metrics. What next?

Save to ▾
Show answer
I would check the test first: enough sample size and duration, correct randomisation, and no bugs in serving such as stale features. Then investigate whether offline metrics really reflect user value, for example optimising clicks rather than purchases, or popularity bias. Segment-level analysis may show gains in some groups. I would revise the offline metric to better match the online goal.
34

Tune LightGBM with Optuna.

Save to ▾
Show answer
import optuna from sklearn.model_selection import cross_val_score def objective(trial): p = {'num_leaves': trial.suggest_int('num_leaves', 15, 255), 'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.2, log=True), 'min_child_samples': trial.suggest_int('min_child_samples', 10, 200)} m = lgb.LGBMClassifier(n_estimators=500, **p) return cross_val_score(m, X, y, cv=5, scoring='roc_auc').mean() study = optuna.create_study(direction='maximize') study.optimize(objective, n_trials=50)
35

Get a bootstrap confidence interval for a test metric.

Save to ▾
Show answer
import numpy as np from sklearn.metrics import roc_auc_score rng = np.random.default_rng(0); scores = [] yt, pp = np.array(y_test), np.array(proba) for _ in range(1000): i = rng.integers(0, len(yt), len(yt)) if len(np.unique(yt[i])) == 2: scores.append(roc_auc_score(yt[i], pp[i])) print(np.percentile(scores, [2.5, 97.5]))
36

How do you handle pressure to report better model numbers than the data supports?

Save to ▾
Show answer
I explain the risk clearly: inflated numbers lead to bad decisions and lose trust when production results arrive. I present the honest metric with confidence intervals, and then offer a concrete plan to improve it, such as new data sources. In one case I showed that a 'better' number came from leakage, and leadership agreed to report the lower but reliable figure.
37

Explain the bias in AUC when classes are extremely imbalanced, with a numeric intuition.

Save to ▾
Show answer
With 100 fraud and 100,000 genuine cases, a false positive rate of 1 percent looks tiny on the ROC curve, but it means 1,000 false alerts versus at most 100 true ones, so precision is below 10 percent. ROC-AUC can be 0.97 while the model is impractical. Precision-recall curves expose this because precision directly depends on the count of false positives.
38

What is training-serving skew and how do you prevent it?

Save to ▾
Show answer
Training-serving skew is when features at prediction time are computed differently from features used in training, causing silent accuracy loss. Causes include separate code paths, different data sources, or time windows that use future data in training. Prevent it by sharing one feature-computation code path or a feature store, logging served features and comparing their distributions with training data.
39

Your real-time model API takes 400 ms but the requirement is under 50 ms. What do you do?

Save to ▾
Show answer
Profile first to see whether time goes to feature lookup, preprocessing or the model. Then cache or precompute features, load the model once at startup, reduce trees or features, use a faster library like LightGBM or ONNX Runtime, and batch requests if possible. Run several workers and keep the service close to its data store. Re-measure p95 and p99 latency, not just the average.
40

Labels for your loan model arrive only after 6 months. How do you monitor it meanwhile?

Save to ▾
Show answer
I would rely on proxy signals: input data drift with PSI, prediction score distribution, approval rates by segment, and early indicators like first missed payment at 30 or 60 days. Once enough early outcomes arrive, I would check performance on these. I would also set up a delayed evaluation job that computes full metrics as labels mature and compares them with the validation baseline.
41

Your model must run on a mobile app with no internet. What do you consider?

Save to ▾
Show answer
Model size, memory and latency on low-end phones become key. I would choose a compact model, reduce features, and convert it to a mobile format such as ONNX, TensorFlow Lite or Core ML, applying quantisation if needed. I would make sure all preprocessing is replicated on-device, test accuracy after conversion, and plan how model updates will ship with app releases.
42

Calculate the Population Stability Index for a feature.

Save to ▾
Show answer
import numpy as np def psi(expected, actual, bins=10): cuts = np.quantile(expected, np.linspace(0, 1, bins + 1)) cuts[0], cuts[-1] = -np.inf, np.inf e = np.histogram(expected, cuts)[0] / len(expected) + 1e-6 a = np.histogram(actual, cuts)[0] / len(actual) + 1e-6 return float(np.sum((a - e) * np.log(a / e))) Rule of thumb: below 0.1 stable, 0.1 to 0.25 moderate, above 0.25 significant drift.
43

What is a feature store and when is it needed?

Save to ▾
Show answer
A feature store is a system that defines, computes and serves features consistently for both training and real-time inference, with an offline store for historical data and an online store for low-latency lookup. It prevents training-serving skew and lets teams reuse features. It is worth it when many models share features or need real-time features; small teams can start with well-managed tables.
44

Your gradient boosting model performs worse on recent months than older ones. What do you check?

Save to ▾
Show answer
I would check for drift between periods in feature distributions and target rate, and confirm that the evaluation uses a time-based split. If behaviour has changed, I would train on a more recent window or weight recent data more, add features that capture the change, and set up a regular retraining schedule. Comparing SHAP importance across periods shows which relationships have shifted.
45

What is Local Outlier Factor and how does it differ from Isolation Forest?

Save to ▾
Show answer
Local Outlier Factor compares the local density of a point with the density of its neighbours; a point in a much sparser area than its neighbours gets a high outlier score. It catches local anomalies inside varied-density data but is distance-based, so it needs scaling and is slower on large data. Isolation Forest is tree-based, faster and scales better, but is less sensitive to local density differences.

Frequently asked questions

Who should practise hard Machine Learning questions?

Candidates targeting senior roles or top product companies, and anyone who finds the medium set easy.

How should I practise these?

Answer each question aloud before opening the answer, mark it as solved only when your answer matches the key idea, and save misses to Last-Minute Revision.

Other difficulty levels