Key takeaways
- 51 Machine Learning interview questions, grouped by level: freshers, intermediate, experienced and coding.
- Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
- Use the filter bar to practise only the level you are interviewing for, then test yourself with the free Machine Learning quiz.
What is Machine Learning, and why do interviewers ask about it?
Machine learning (ML) is the branch of artificial intelligence in which systems learn patterns from data instead of following hand-written rules. It powers recommendations, fraud detection, search ranking, forecasting, medical imaging and the foundation models behind generative AI.
These machine learning interview questions cover what data scientists and ML engineers are asked in 2026 — core concepts (supervised vs unsupervised learning, the bias-variance trade-off, overfitting and regularisation), algorithms (linear and logistic regression, decision trees, random forests, gradient boosting, SVM, k-means), evaluation metrics, feature engineering, neural network basics and MLOps for production, with Python and scikit-learn code.
Why companies hire for Machine Learning
- ML engineer and data scientist roles remain among the most in-demand in tech
- Every AI and GenAI role still tests ML fundamentals
- Interviewers probe trade-offs, metrics and production thinking, not just definitions
- Covers the theory and the scikit-learn code asked in coding rounds
Basic Machine Learning Interview Questions for Freshers
15 questionsStart here if you are a fresher or switching to Machine Learning. These fundamentals are asked in almost every first-round and campus interview.
How interviewers ask it“Let's start with the basics — how would you explain the types of machine learning?”
What are the types of machine learning?
- Supervised learning: learn from labelled examples (input → known output). Classification (spam or not) and regression (house price).
- Unsupervised learning: find structure in unlabelled data. Clustering, dimensionality reduction, anomaly detection.
- Semi-supervised learning: a small labelled set plus a large unlabelled set.
- Self-supervised learning: labels come from the data itself (predicting the next word or masked pixels) — how foundation models and LLMs are pre-trained.
- Reinforcement learning: an agent learns by trial and error from rewards (game playing, robotics, RLHF for LLMs).
How interviewers ask it“Can you compare classification and regression? Where do people usually confuse them?”
What is the difference between classification and regression?
- Training set: fits the model's parameters
- Validation set: tunes hyperparameters and selects models
- Test set: gives an unbiased final estimate of performance on unseen data — used once, at the end
A typical split is 70/15/15 or 80/10/10. For time-series data, split by time (train on the past, test on the future) so the model never sees the future during training.
- Tuning hyperparameters on the test set. The reported score then overestimates real-world performance.
- More (or augmented) training data
- A simpler model or fewer features
- Regularisation (L1/L2, dropout, weight decay)
- Cross-validation for honest model selection
- Early stopping for iterative models
- Ensembles (bagging), and pruning or depth limits for trees
Underfitting is the opposite: the model is too simple to capture the pattern, so both training and validation errors are high.
How interviewers ask it“Explain the bias-variance trade-off, ideally with an example from a project you've worked on.”
Explain the bias-variance trade-off.
- High bias: the model is too simple and makes systematic errors (underfitting) — for example a linear model on curved data
- High variance: the model is too sensitive to the particular training sample (overfitting) — for example a very deep decision tree
Increasing model complexity reduces bias but increases variance. The goal is the complexity that minimises total error on unseen data, found through validation curves and cross-validation. Bagging mainly reduces variance; boosting mainly reduces bias.
How interviewers ask it“Let's start with the basics — how would you explain cross-validation?”
What is cross-validation?
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.ensemble import RandomForestClassifier
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(RandomForestClassifier(random_state=42), X, y, cv=cv, scoring="f1")
print(scores.mean(), scores.std())How interviewers ask it“How are parameters different from hyperparameters, and when does the difference matter in practice?”
What is the difference between parameters and hyperparameters?
How interviewers ask it“How does linear regression work under the hood? Take me through it step by step.”
How does linear regression work?
How interviewers ask it“How does logistic regression work under the hood? Take me through it step by step.”
How does logistic regression work?
How interviewers ask it“How does a decision tree work under the hood? Take me through it step by step.”
How does a decision tree work?
How interviewers ask it“In simple words, what is k-nearest neighbours (k-NN)? Explain it like you would to a new teammate.”
What is k-nearest neighbours (k-NN)?
How interviewers ask it“Let's start with the basics — how would you explain k-means clustering?”
What is k-means clustering?
Intermediate Machine Learning Interview Questions
16 questionsQuestions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with Machine Learning.
- Precision = TP / (TP + FP): of everything predicted positive, how much was right. Matters when false positives are costly (flagging legitimate transactions as fraud, spam filters hiding real email).
- Recall = TP / (TP + FN): of all actual positives, how many we caught. Matters when false negatives are costly (missing cancer, missing fraud).
- F1 = 2·P·R / (P + R): the harmonic mean, useful when you need a balance and classes are imbalanced.
Moving the decision threshold trades precision against recall; choose it based on business costs.
- Using the right metrics (precision, recall, F1, PR-AUC, cost-based metrics)
- Class weights (
class_weight="balanced") or a weighted loss - Resampling: undersample the majority class, oversample the minority, or use SMOTE — on the training folds only
- Tuning the decision threshold
- Collecting more minority-class examples, or framing the problem as anomaly detection
- MAE (mean absolute error): average absolute error, in the target's units; robust to outliers
- MSE / RMSE: penalise large errors more; RMSE is in the target's units
- R²: proportion of variance explained (1 is perfect; it can be negative for bad models)
- MAPE / sMAPE: percentage errors, popular in forecasting but unstable near zero
Choose the metric that matches the business cost — for example, if under-forecasting stock is worse than over-forecasting, use an asymmetric (quantile) loss.
- L1 (Lasso): penalty λ·Σ|w|. Drives some weights exactly to zero, performing feature selection.
- L2 (Ridge): penalty λ·Σw². Shrinks all weights smoothly towards zero; handles multicollinearity well.
- Elastic Net: combines both.
λ (or alpha, or C = 1/λ in scikit-learn's logistic regression) is tuned by cross-validation. Scale features first so that the penalty treats them fairly.
- Batch: uses the full dataset per step — stable but slow and memory-heavy
- Stochastic (SGD): one example per step — noisy but fast, and the noise can help escape poor regions
- Mini-batch: small batches (32–1024) — the standard in deep learning, efficient on GPUs
Optimisers such as Momentum, RMSProp and Adam/AdamW adapt the step size. Too high a learning rate diverges; too low converges slowly — learning-rate schedules and warm-up help.
XGBoost, LightGBM and CatBoost are optimised implementations with regularisation, handling of missing values, histogram-based splits and early stopping; LightGBM grows trees leaf-wise for speed, and CatBoost handles categorical features natively. Compared with random forests (parallel, independent trees), boosting needs more careful tuning (learning rate, depth, number of trees) and can overfit noisy data.
How interviewers ask it“How would you explain a support vector machine (SVM) to a junior engineer, and what do people most often get wrong?”
What is a support vector machine (SVM)?
How interviewers ask it“Suppose you need to handle missing data — how do you approach it, and what can go wrong?”
How do you handle missing data?
- Drop rows or columns (only if little data is lost and the missingness is random)
- Impute with the mean, median or mode; with a constant plus a "was missing" indicator feature; with k-NN or iterative (model-based) imputation; or with forward-fill for time series
- Use models that handle missing values natively (XGBoost, LightGBM)
Fit imputers inside a pipeline on the training data only.
How interviewers ask it“How would you encode categorical variables? Walk me through your approach.”
How do you encode categorical variables?
- One-hot encoding: for low-cardinality nominal features (colour, city with few values)
- Ordinal encoding: for ordered categories (low < medium < high)
- Target (mean) encoding: for high-cardinality features (product ID), computed out-of-fold with smoothing to avoid leakage
- Frequency encoding, hashing, or learned embeddings (deep learning) for very high cardinality
- Native categorical support in CatBoost and LightGBM
- Bagging: train models in parallel on bootstrap samples and average them — reduces variance (random forest)
- Boosting: train models sequentially, each correcting the previous errors — reduces bias (AdaBoost, gradient boosting)
- Stacking: feed the out-of-fold predictions of diverse base models into a meta-model that learns how to combine them
How interviewers ask it“Suppose you need to interpret and explain a machine learning model — how do you approach it, and what can go wrong?”
How do you interpret and explain a machine learning model?
- Global: feature importances (impurity-based or permutation importance), partial dependence plots, coefficients for linear models
- Local: SHAP values (consistent, additive attributions for each prediction) and LIME
- Inherently interpretable models (linear models, small trees, GAMs) when regulations require clear explanations — for example credit decisions
Explanations show correlations the model learned, not causation, and should be checked with domain experts.
Advanced Machine Learning Interview Questions for Experienced Developers
14 questionsSenior-level Machine Learning questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.
- Forward pass: compute predictions
- Loss: measure the error (cross-entropy, MSE)
- Backpropagation: use the chain rule to compute the gradient of the loss with respect to every weight, layer by layer from output to input
- Update: an optimiser (SGD, Adam/AdamW) adjusts the weights
Without non-linear activations, any number of layers would collapse into a single linear model.
- CNNs (convolutional neural networks): learn local spatial patterns with shared filters — image classification, object detection, segmentation and some audio tasks
- RNNs/LSTMs/GRUs: process sequences step by step with hidden state — older NLP and time-series models, now largely replaced
- Transformers: use self-attention to relate every token to every other token in parallel — the architecture behind LLMs (GPT, Claude, Llama), BERT, vision transformers and multimodal models; they scale extremely well with data and compute
How interviewers ask it“Explain transfer learning and fine-tuning in detail — what should a new team member understand about it?”
What is transfer learning and fine-tuning?
- Data: ingestion, validation, versioning (DVC, Delta Lake) and a feature store for consistent training and serving features
- Training: reproducible pipelines with experiment tracking (MLflow, Weights & Biases)
- Evaluation: offline metrics, fairness and robustness checks
- Model registry and CI/CD: versioned models, automated tests and approvals
- Deployment: batch scoring, real-time APIs or edge, using shadow, canary or A/B releases
- Monitoring: data drift, prediction drift, model performance, latency and cost — with alerts and retraining triggers
How interviewers ask it“Can you compare batch and real-time (online) inference? Where do people usually confuse them?”
What is the difference between batch and real-time (online) inference?
How interviewers ask it“How would you design a recommendation system? Walk me through your approach.”
How would you design a recommendation system?
- Candidate generation: retrieve a few hundred items from millions, using collaborative filtering, two-tower embedding models with approximate nearest-neighbour search, plus popularity and content-based sources
- Ranking: a richer model (gradient boosting or a deep network) scores candidates using user, item and context features, optimising engagement or conversion
- Re-ranking: apply business rules, diversity, freshness and fairness constraints
- Feedback loop: log impressions and interactions for training; evaluate offline (recall@k, NDCG) and online (A/B tests on click-through, conversion, retention)
Handle cold start with content features and popularity, and watch for feedback-loop bias.
How interviewers ask it“How would you design a fraud detection system? Walk me through your approach.”
How would you design a fraud detection system?
- Real-time scoring during the transaction, within a strict latency budget (tens of milliseconds)
- Features: transaction amount and velocity (counts and sums over the last minutes, hours and days), device and location signals, merchant risk and graph features (shared cards, devices and accounts)
- Models: gradient boosting for tabular data, plus anomaly detection for new patterns and rules for known patterns
- Imbalance: class weights, PR-AUC, and a threshold chosen from the cost of fraud versus false declines
- Labels arrive late (chargebacks take weeks) — account for this in training and monitoring
- Concept drift: frequent retraining, monitoring and human review queues for borderline cases
How interviewers ask it“Suppose you need to deploy a machine learning model to production — how do you approach it, and what can go wrong?”
How do you deploy a machine learning model to production?
How interviewers ask it“Suppose you need to choose the right model for a problem — how do you approach it, and what can go wrong?”
How do you choose the right model for a problem?
Machine Learning Coding Interview Questions (Programs with Code)
6 questionsHands-on Machine Learning programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import f1_score
df = pd.read_csv("churn.csv")
X, y = df.drop(columns="churned"), df["churned"]
num = X.select_dtypes("number").columns
cat = X.select_dtypes(exclude="number").columns
pre = ColumnTransformer([
("num", Pipeline([("imp", SimpleImputer(strategy="median")), ("sc", StandardScaler())]), num),
("cat", Pipeline([("imp", SimpleImputer(strategy="most_frequent")),
("oh", OneHotEncoder(handle_unknown="ignore"))]), cat),
])
model = Pipeline([("pre", pre), ("clf", LogisticRegression(max_iter=1000, class_weight="balanced"))])
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
print("CV F1:", cross_val_score(model, X_tr, y_tr, cv=5, scoring="f1").mean())
model.fit(X_tr, y_tr)
print("Test F1:", f1_score(y_te, model.predict(X_te)))import numpy as np
def fit_linear_regression(X, y, lr=0.01, epochs=2000):
X = np.c_[np.ones(len(X)), X] # add bias column
w = np.zeros(X.shape[1])
n = len(y)
for _ in range(epochs):
y_hat = X @ w
grad = (2 / n) * X.T @ (y_hat - y) # dMSE/dw
w -= lr * grad
return w
X = np.random.rand(200, 1) * 10
y = 3 * X[:, 0] + 5 + np.random.randn(200)
print(fit_linear_regression(X, y)) # ≈ [5, 3]def precision_recall_f1(y_true, y_pred, positive=1):
tp = sum(t == positive and p == positive for t, p in zip(y_true, y_pred))
fp = sum(t != positive and p == positive for t, p in zip(y_true, y_pred))
fn = sum(t == positive and p != positive for t, p in zip(y_true, y_pred))
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(precision_recall_f1([1, 0, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1])) # (0.75, 0.75, 0.75)import numpy as np
def kmeans(X, k, iters=100, seed=0):
rng = np.random.default_rng(seed)
centroids = X[rng.choice(len(X), k, replace=False)]
for _ in range(iters):
dists = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=2)
labels = dists.argmin(axis=1)
new = np.array([X[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
for j in range(k)])
if np.allclose(new, centroids):
break
centroids = new
return labels, centroidsfrom sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import loguniform, randint
base = HistGradientBoostingClassifier(early_stopping=True, validation_fraction=0.1, random_state=42)
params = {
"learning_rate": loguniform(0.01, 0.3),
"max_depth": randint(3, 10),
"max_leaf_nodes": randint(15, 63),
"l2_regularization": loguniform(1e-4, 10),
"min_samples_leaf": randint(10, 100),
}
search = RandomizedSearchCV(base, params, n_iter=40, cv=5, scoring="average_precision",
n_jobs=-1, random_state=42)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)
print("hold-out PR-AUC:", search.score(X_test, y_test))# pip install fastapi uvicorn joblib
import joblib, pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI(title="churn-model", version="1.3.0")
model = joblib.load("churn_pipeline.joblib") # full sklearn Pipeline
class Customer(BaseModel):
tenure_months: int = Field(ge=0)
monthly_charges: float = Field(ge=0)
contract: str
support_tickets: int = Field(ge=0)
@app.post("/predict")
def predict(c: Customer):
proba = float(model.predict_proba(pd.DataFrame([c.model_dump()]))[0, 1])
return {"churn_probability": round(proba, 4), "will_churn": proba >= 0.35, "model_version": app.version}
# run: uvicorn serve:app --host 0.0.0.0 --port 8000Practise with the free Machine Learning quiz
Multiple-choice questions with instant feedback. Takes about 10 minutes and shows exactly which concepts to revise.
Start the Machine Learning quiz →