Machine learning interview questions and answers
Machine learning interview questions test whether you can choose a model, measure it honestly and explain its errors. Expect the bias-variance trade-off, overfitting and regularization, precision, recall and ROC-AUC, cross-validation and data leakage, class imbalance, trees versus linear models, and a short ML system design case. Interviewers reward answers that tie each choice to the data and to the cost of a wrong prediction, not definitions recited from memory.
By Evin JohnPublished 8 min read
What ML interview rounds look like
Classical machine learning is tested for data scientist, ML engineer, AI engineer and applied scientist roles, and for analysts moving into modeling. The theory overlaps across companies, but the weighting changes: product data science leans on metrics and experiments, ML engineering leans on pipelines and serving, research roles lean on math. Neural networks are covered in deep learning interview questions; this page stays with the fundamentals every one of those loops assumes.
- Concept screenRapid questions on overfitting, metrics, regularization and model choice. Short, correct answers with one example each work best.
- ML codingImplement a metric, logistic regression with gradient descent, or k-means in NumPy, or clean and model a dataset with pandas and scikit-learn.
- Applied case"We want to predict churn" or "rank these items". You frame the target, pick features and metrics, and say how you would validate.
- ML system designFor engineering roles: data pipelines, training cadence, serving, latency, monitoring and retraining for a model in production.
Machine learning fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Explain the bias-variance trade-off. | Core theory | Bias is error from a model too simple to capture the pattern; variance is error from a model that reacts to noise in its particular training set. More capacity lowers bias and raises variance, and the aim is the lowest total error on new data. |
| How do you know a model is overfitting? | Diagnosis | Training error keeps falling while validation error stalls or rises. Learning curves against training set size show whether more data or less capacity would help. |
| How do you reduce overfitting? | Remedies | More or better data, fewer or simpler features, regularization, early stopping, limits on tree depth or leaf size, and ensembling. Name the remedy that fits the model in question. |
| L1 versus L2 regularization? | Regularization | L1 adds the absolute size of weights and can push some exactly to zero, which selects features. L2 adds squared weights and shrinks them smoothly, which handles correlated features more gracefully. Elastic net mixes both. |
| Why split data into train, validation and test sets? | Methodology | Train fits parameters, validation picks hyperparameters and models, and test is touched once for an unbiased final estimate. Tuning on the test set turns it into another validation set. |
| Which models need feature scaling? | Preprocessing | Distance and gradient-based models do: k-NN, SVMs, k-means, PCA, and regularized linear models, whose penalty depends on scale. Tree-based models split on thresholds and do not care. |
| Supervised versus unsupervised learning? | Problem types | Supervised learning has labels to predict. Unsupervised learning finds structure without labels, such as clusters or a lower-dimensional representation. Self-supervised learning builds labels from the data itself. |
| Parametric versus non-parametric models? | Model families | Parametric models have a fixed number of parameters, like linear regression. Non-parametric ones grow with the data, like k-NN or a fully grown decision tree. |
| What is the curse of dimensionality? | Geometry | As dimensions grow, data becomes sparse and distances between points become similar, which hurts distance-based methods and demands more data. Feature selection and dimensionality reduction help. |
| Why use log loss rather than accuracy to train a classifier? | Loss functions | Log loss is smooth and rewards well-calibrated probabilities, so it can be optimized with gradients. Accuracy is a step function of the threshold and says nothing about confidence. |
Evaluation metric questions
Metric questions are where interviewers separate memorization from judgement. Know the definitions cold, then show you can pick a metric from the cost of each error type. A cancer screen and a spam filter want very different trade-offs.
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score
y_true = np.array([1, 0, 1, 1, 0, 0, 1, 0])
y_prob = np.array([0.9, 0.4, 0.35, 0.8, 0.1, 0.6, 0.7, 0.2])
def scores(y_true, y_prob, threshold=0.5):
y_pred = (y_prob >= threshold).astype(int)
tp = int(((y_pred == 1) & (y_true == 1)).sum())
fp = int(((y_pred == 1) & (y_true == 0)).sum())
fn = int(((y_pred == 0) & (y_true == 1)).sum())
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return precision, recall, f1
print(scores(y_true, y_prob)) # (0.75, 0.75, 0.75)
print(scores(y_true, y_prob, 0.3)) # (0.666..., 1.0, 0.8): lower threshold, higher recall
y_pred = (y_prob >= 0.5).astype(int) # same numbers from scikit-learn
print(precision_score(y_true, y_pred), recall_score(y_true, y_pred), f1_score(y_true, y_pred))- When do you prefer recall over precision? When missing a positive is costly, as in fraud alerts or disease screening, and a human can review false alarms. Prefer precision when each false positive costs real money or annoys users, as with blocking a legitimate payment.
- What does ROC-AUC measure? The probability that a random positive gets a higher score than a random negative. It ignores the threshold and is insensitive to class balance, which is both its strength and its weakness.
- ROC-AUC or PR-AUC on a rare-event problem? PR-AUC (average precision). With few positives, the false positive rate stays tiny even when most alerts are wrong, so ROC-AUC can look strong while precision is poor.
- Why is accuracy misleading on imbalanced data? A model that always predicts the majority class scores the majority share and finds nothing. Report a confusion matrix and class-aware metrics instead.
- MAE or RMSE for regression? RMSE squares errors, so large misses dominate; use it when big errors are much worse. MAE treats every unit of error the same and is easier to explain.
- What is calibration and why does it matter? A calibrated model's 0.8 means about 80 percent of such cases are positive. It matters whenever scores feed a decision rule, a price or a downstream model. Check it with a reliability curve, fix it with Platt scaling or isotonic regression.
- How do you pick a classification threshold? From costs and capacity: the expected cost of each error type, or how many alerts a review team can handle. Tune it on validation data, never on the test set.
Validation and data leakage questions
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=1000, weights=[0.9, 0.1], random_state=0)
# Leaky: the scaler sees every row, including the ones each fold will test on
# X_scaled = StandardScaler().fit_transform(X)
# cross_val_score(LogisticRegression(), X_scaled, y)
# Correct: the pipeline refits the scaler inside each training fold
model = make_pipeline(StandardScaler(), LogisticRegression(class_weight="balanced", max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="average_precision")
print(scores.mean().round(3), scores.std().round(3))| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is data leakage? Give two examples. | Leakage | Information at training time that will not exist at prediction time. Examples: a feature recorded after the outcome, scaling or imputing on the full dataset before splitting, or the same customer in both train and test. |
| Your model scores far better offline than in production. What do you check? | Debugging | Leakage first, then a mismatch between training and serving features, then a shift in the data since training. Compare feature distributions between the two. |
| k-fold, stratified, group or time series split? | CV schemes | Stratified keeps class ratios in each fold. Group k-fold keeps all rows of one user or patient in the same fold. Time series splits always train on the past and test on the future. |
| Why not shuffle time series before splitting? | Temporal order | Shuffling lets the model learn from the future, so the score overstates what it can do on next week's data. |
| What is nested cross-validation? | Tuning | An inner loop tunes hyperparameters and an outer loop estimates performance, so the reported score is not biased by the tuning itself. |
| How do you encode a high-cardinality category such as city? | Encoding | One-hot can explode in width. Target encoding works well but must be computed out of fold, or it leaks the label. Hashing or learned embeddings are other options. |
Model questions: linear models, trees and boosting
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Decision trees or linear models: when would you pick each? | Model choice | Linear models suit roughly additive effects, need scaling and engineered interactions, and are easy to explain. Trees handle nonlinearity, interactions and mixed feature types without scaling, but a single tree overfits easily. |
| Random forest versus gradient boosting? | Ensembles | A random forest averages many deep trees trained on bootstrap samples and random feature subsets, which reduces variance. Gradient boosting adds shallow trees one at a time, each fitting the errors of the ensemble so far, which reduces bias and needs more careful tuning. |
| Which gradient boosting hyperparameters matter most? | Tuning | Learning rate and number of trees together (with early stopping), tree depth or leaves, minimum samples per leaf, row and column subsampling, and regularization terms. |
| How does logistic regression produce a probability? | Linear models | It passes a linear score through the sigmoid and is trained by minimizing log loss. Coefficients are changes in log-odds per unit of the feature. |
| What does feature importance from a tree model tell you, and what does it hide? | Interpretability | Impurity-based importance favors high-cardinality features and says nothing about direction. Permutation importance or SHAP values on held-out data are more trustworthy. |
| How does k-means work and what are its limits? | Clustering | It alternates assigning points to the nearest centroid and recomputing centroids. You choose k, it assumes roughly round clusters of similar size, and it is sensitive to scale and starting points. |
| What does PCA do? | Dimensionality reduction | It finds orthogonal directions of maximum variance and projects onto the top ones. It needs scaled features and makes the new axes harder to interpret. |
| When is naive Bayes a good choice? | Baselines | As a fast baseline for text and other high-dimensional sparse data, where the independence assumption is wrong but the ranking it produces is still useful. |
Class imbalance and feature engineering questions
- How do you handle a 1-in-1,000 positive class? Start with the right metric (PR-AUC, recall at a fixed precision). Then try class weights, resampling the training set only, and threshold tuning. Collecting more positives often beats any trick.
- What is the risk with oversampling methods such as SMOTE? Applied before the split, synthetic points leak into validation. Even applied correctly, they can blur class boundaries, so compare against plain class weights.
- What features would you build for a churn model? Recency and frequency of use, trends over the last weeks rather than lifetime totals, support contacts, plan changes and billing failures, all computed as of a cutoff date before the label window.
- How do you handle missing values in features? Ask why they are missing. Impute with a statistic fitted on training data, add a was-missing flag when missingness is informative, or use a model that handles gaps natively.
- How do you know a new feature helped? Compare cross-validated scores with and without it, check the gain is larger than the fold-to-fold noise, and confirm it will exist at prediction time.
ML system design and senior questions
For ML engineering and senior data science roles, at least one round looks like system design with a model inside. The general structure is in the system design interview guides; the ML-specific parts are below.
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Design a model to rank items in a user's feed. | Framing | Define the label (click, long view, purchase), the candidate generation and ranking stages, offline metrics such as NDCG, and the online experiment that decides launch. |
| Offline metrics improved but the A/B test was flat. Why? | Offline versus online | The offline metric may not track the business goal, the test may lack power, serving features may differ from training ones, or the gain sits in a segment the test did not reach. |
| Batch or real-time predictions? | Serving | Batch suits predictions that can be precomputed daily, such as a churn list. Real-time suits inputs only known at request time, at the cost of latency budgets and a feature store or online lookups. |
| How do you monitor a model in production? | Operations | Input feature distributions, prediction distributions, data freshness and pipeline failures right away; actual performance once labels arrive, which can take weeks. |
| When do you retrain? | Lifecycle | On a schedule that matches how fast the data shifts, or when monitoring shows drift or a drop in performance. Every retrain is validated against the current model before it replaces it. |
| How would you explain a model's decision to a non-technical stakeholder? | Communication | Lead with the few features that drove this prediction, in their units, and with how often the model is right for cases like this one. Avoid jargon such as log-odds. |
Fictional example
- Interviewer
- A teammate says the new fraud model is highly accurate on the test set. What do you ask before agreeing?
- Candidate
- Fraud is rare, so accuracy mostly measures how well the model recognizes normal transactions. I would ask for precision and recall at the threshold we would actually use, and the PR curve. Then I would check the split: was it by time, with training data strictly before test data, and were features like chargeback flags only available after the fact? I would also ask how many alerts per day this threshold creates and whether the review team can handle them. If recall at an acceptable alert volume beats the current rules engine on recent data, I would support a shadow launch before it blocks anything.
A two-week machine learning practice plan
- Days 1 to 3: write one-minute spoken answers for bias and variance, overfitting, L1 and L2, and each metric above. Record and trim them.
- Days 4 and 5: implement logistic regression with gradient descent and k-means in NumPy, then check them against scikit-learn.
- Days 6 to 8: take a tabular dataset end to end: a baseline, a pipeline with cross-validation, a gradient boosting model and an error analysis by segment.
- Days 9 and 10: plant a leak on purpose (a post-outcome feature, scaling before the split) and watch the score jump, so you can describe the symptom from experience.
- Days 11 to 14: two ML case studies out loud, one ranking and one classification, each covering framing, data, metrics, serving and monitoring.
Related reading: Pandas and NumPy interview questions for the data wrangling part of ML coding rounds, NLP interview questions for text and language models, data scientist interview questions for statistics and experiments, and AI engineer interview questions for building on top of large models.
Most ML answers go wrong in the explanation, not the math: a candidate knows PR-AUC but forgets to say why it suits the problem. Natively, an AI interview assistant for Mac and Windows, transcribes a practice round on your computer so you can check whether each answer tied the metric to the cost of errors. It can also draft answer suggestions while you practice, read a coding prompt or a confusing plot from a screenshot, and with Pro or the free trial use your résumé and the job description you add. The transcript and notes remain for you to review afterwards.
Questions people ask
What machine learning questions are asked in interviews?
The bias-variance trade-off, overfitting and regularization, precision, recall, F1 and ROC-AUC, cross-validation and data leakage, class imbalance, linear models versus trees, gradient boosting, feature engineering and, for senior roles, ML system design.
How do I explain the bias-variance trade-off in an interview?
Say that bias is error from a model too simple for the pattern and variance is error from a model that fits noise in its training data, then give one example of each and how you would detect it with learning curves.
Which metric should I use for an imbalanced classification problem?
Usually precision-recall AUC or recall at a fixed precision, plus a confusion matrix at the chosen threshold. Accuracy and often ROC-AUC look good on rare-event problems even when most alerts are wrong.
Do machine learning interviews include coding?
Often. Common tasks are implementing a metric, logistic regression or k-means in NumPy, or building a scikit-learn pipeline with proper cross-validation on a small dataset.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
