Skip to content
  1. Home
  2. Interview Questions
  3. Machine Learning
AI, ML & Blockchain

Machine Learning Interview Questions and Answers (2026)

Industry-standard machine learning interview questions for data scientists and ML engineers — supervised and unsupervised learning, the bias-variance trade-off, regularisation, evaluation metrics, feature engineering, ensembles and gradient boosting, neural networks, MLOps, drift and ML system design, with Python, NumPy and scikit-learn code.

Updated November 2026 Reviewed by Abhishek Kumar 61 min read
51Questions
15Freshers
16Intermediate
14Experienced

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 questions

Start here if you are a fresher or switching to Machine Learning. These fundamentals are asked in almost every first-round and campus interview.

BeginnerMachine Learning
Quick answerIn traditional programming, a developer writes explicit rules: rules + data → output. In machine learning, an algorithm learns the rules from examples: data + expected outputs → model, and the trained model then makes predictions on new data. ML suits problems where the rules are too complex to write by hand (spam detection, image recognition) or change over time (fraud patterns, demand).

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?

BeginnerMachine 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?

BeginnerMachine Learning
Quick answerClassification predicts a discrete category (fraud or legitimate, which product category); outputs are labels or class probabilities and are evaluated with accuracy, precision, recall, F1 and ROC-AUC. Regression predicts a continuous number (price, delivery time) and is evaluated with MAE, RMSE and R². Some algorithms do both (decision trees, gradient boosting, neural networks). Logistic regression, despite its name, is a classification algorithm.
BeginnerMachine Learning
Quick answerFeatures are the input variables the model uses (age, income, number of past purchases); the label (target) is what the model predicts (will the customer churn?). Training data is the set of examples used to fit the model. The quality and relevance of features usually matter more than the choice of algorithm.
BeginnerMachine Learning
  • 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.

Common mistakes
  • Tuning hyperparameters on the test set. The reported score then overestimates real-world performance.
BeginnerMachine Learning
Quick answerOverfitting happens when a model learns noise and quirks of the training data instead of general patterns: training performance is high but validation performance is poor. Prevention:
  • 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.

BeginnerMachine Learning
Quick answerPrediction error can be decomposed into bias² + variance + irreducible noise.
  • 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?

BeginnerMachine Learning
Quick answerk-fold cross-validation splits the data into k folds; the model trains on k−1 folds and validates on the remaining one, rotating k times, and the scores are averaged. It gives a more reliable performance estimate than a single split, especially with limited data. Variants: stratified k-fold (keeps class proportions for classification), group k-fold (keeps all rows from the same user or patient together to avoid leakage) and time-series split (always validates on later data).
Python
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?

BeginnerMachine Learning
Quick answerParameters are learned from the data during training — the weights of a linear model or a neural network, or the split thresholds of a tree. Hyperparameters are set before training and control the learning process — learning rate, tree depth, number of trees, regularisation strength, k in k-NN. Hyperparameters are tuned with grid search, random search or Bayesian optimisation (for example Optuna), using cross-validation.

How interviewers ask it“How does linear regression work under the hood? Take me through it step by step.”

How does linear regression work?

BeginnerMachine Learning
Quick answerLinear regression models the target as a weighted sum of features: ŷ = w₀ + w₁x₁ + … + wₙxₙ. It finds the weights that minimise the mean squared error, either with the closed-form normal equation or with gradient descent. Key assumptions: a linear relationship, independent errors, constant error variance (homoscedasticity), normally distributed residuals (for inference) and no strong multicollinearity. Coefficients are interpretable as the change in the target per unit change in a feature, holding others constant.

How interviewers ask it“How does logistic regression work under the hood? Take me through it step by step.”

How does logistic regression work?

BeginnerMachine Learning
Quick answerLogistic regression is a classification algorithm. It computes a linear score z = w·x + b and passes it through the sigmoid function σ(z) = 1 / (1 + e⁻ᶻ) to get a probability between 0 and 1. It is trained by minimising log loss (binary cross-entropy). A threshold (0.5 by default, but tuned for the business case) turns probabilities into classes. It is fast, interpretable (coefficients are log-odds) and a strong baseline; softmax extends it to multiple classes.

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?

BeginnerMachine Learning
Quick answerA decision tree splits the data recursively on the feature and threshold that best separate the target — measured by Gini impurity or entropy/information gain for classification, and variance reduction (MSE) for regression. Each leaf gives a prediction. Trees are interpretable, handle non-linear relationships and mixed feature types, and need no feature scaling, but a single deep tree overfits easily; control it with max_depth, min_samples_leaf and pruning, or use ensembles.

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)?

BeginnerMachine Learning
Quick answerk-NN is a lazy, instance-based algorithm: to predict, it finds the k closest training points (by Euclidean, Manhattan or cosine distance) and takes a majority vote (classification) or an average (regression). There is no real training phase, but prediction is slow on large datasets (approximate nearest-neighbour indexes help). Features must be scaled, k is chosen by cross-validation, and performance degrades in high dimensions (the curse of dimensionality).
BeginnerMachine Learning
Quick answerNaive Bayes applies Bayes' theorem to compute P(class | features), assuming the features are conditionally independent given the class — the "naive" assumption, which is rarely true but often works well in practice. It is very fast, works well with small data and high-dimensional sparse features, and is a classic baseline for text classification (spam filtering, sentiment) using Multinomial or Bernoulli variants.

How interviewers ask it“Let's start with the basics — how would you explain k-means clustering?”

What is k-means clustering?

BeginnerMachine Learning
Quick answerk-means groups data into k clusters: it initialises k centroids (k-means++ for better starts), assigns each point to its nearest centroid, recomputes each centroid as the mean of its points, and repeats until assignments stop changing. It minimises within-cluster sum of squares. Choose k with the elbow method or the silhouette score. Limitations: it assumes roughly spherical, similarly sized clusters, is sensitive to outliers and scale, and requires k in advance — alternatives include DBSCAN, hierarchical clustering and Gaussian mixture models.

Intermediate Machine Learning Interview Questions

16 questions

Questions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with Machine Learning.

IntermediateMachine Learning
Quick answerFrom the confusion matrix (TP, FP, FN, TN):
  • 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.

IntermediateMachine Learning
Quick answerThe ROC curve plots the true-positive rate (recall) against the false-positive rate across all thresholds; AUC summarises it as the probability that the model ranks a random positive above a random negative (0.5 = random, 1.0 = perfect). On highly imbalanced data (fraud at 0.1%), ROC-AUC can look excellent while precision is poor, so the precision-recall curve and PR-AUC (average precision) are more informative there.
IntermediateMachine Learning
Quick answerIf 99% of transactions are legitimate, a model that always predicts "legitimate" scores 99% accuracy but catches no fraud. Handle imbalance by:
  • 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
IntermediateMachine Learning
  • 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.

IntermediateMachine Learning
Quick answerRegularisation adds a penalty on model complexity to the loss function to reduce overfitting.
  • 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.

IntermediateMachine Learning
Quick answerGradient descent minimises the loss by repeatedly moving the parameters in the direction of the negative gradient: w ← w − η·∇L(w), where η is the learning rate.
  • 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.

IntermediateMachine Learning
Quick answerA random forest trains many decision trees on bootstrap samples of the data (bagging) and, at each split, considers only a random subset of features. Predictions are averaged (regression) or voted (classification). Because the trees are decorrelated, averaging them greatly reduces variance without much increase in bias. Random forests are robust, need little tuning, handle non-linearity and give feature importances and out-of-bag error estimates.
IntermediateMachine Learning
Quick answerGradient boosting builds trees sequentially: each new shallow tree fits the residual errors (gradients of the loss) of the current ensemble, and its contribution is scaled by a learning rate. It mainly reduces bias and is usually the most accurate approach for tabular data.

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)?

IntermediateMachine Learning
Quick answerAn SVM finds the hyperplane that separates the classes with the maximum margin; the points closest to it are the support vectors. The soft-margin parameter C trades margin width against misclassification. The kernel trick (RBF, polynomial) lets SVMs learn non-linear boundaries by implicitly mapping data into higher dimensions. SVMs work well on medium-sized, high-dimensional data (such as text) but scale poorly to very large datasets and need feature scaling.
IntermediateMachine Learning
Quick answerScaling puts features on comparable ranges. Standardisation (z-score: mean 0, standard deviation 1) and min-max normalisation (0–1) are the common methods; robust scaling uses the median and IQR to resist outliers. Scaling is needed for distance-based and gradient-based algorithms — k-NN, k-means, SVM, linear and logistic regression with regularisation, PCA and neural networks. Tree-based models don't need it. Always fit the scaler on the training data only.

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?

IntermediateMachine Learning
Quick answerFirst understand why it is missing (completely at random, at random, or not at random). Options:
  • 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?

IntermediateMachine Learning
  • 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
IntermediateMachine Learning
Quick answerData leakage is when information that won't be available at prediction time leaks into training, producing unrealistically good validation scores that collapse in production. Examples: features computed using the target or future data, fitting scalers or imputers on the full dataset before splitting, duplicate users across train and test, and random splits on time-series data. Prevent it with pipelines (fit preprocessing inside each fold), time-based or group-based splits, and by checking every feature's availability at prediction time.
IntermediateMachine Learning
Quick answerPrincipal Component Analysis is an unsupervised linear technique that projects data onto the orthogonal directions (principal components) of maximum variance, computed from the eigenvectors of the covariance matrix (or via SVD). Uses: dimensionality reduction to speed up training and reduce noise, removing multicollinearity, and visualisation in 2D/3D. Scale the features first; components are harder to interpret than the original features. For non-linear visualisation, use t-SNE or UMAP.
IntermediateMachine Learning
Quick answerEnsembles combine several models for better performance than any single one.
  • 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?

IntermediateMachine Learning
  • 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 questions

Senior-level Machine Learning questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.

AdvancedMachine Learning
Quick answerA neural network stacks layers of weighted sums followed by non-linear activation functions (ReLU, GELU, sigmoid, tanh). Training repeats four steps:
  1. Forward pass: compute predictions
  2. Loss: measure the error (cross-entropy, MSE)
  3. Backpropagation: use the chain rule to compute the gradient of the loss with respect to every weight, layer by layer from output to input
  4. Update: an optimiser (SGD, Adam/AdamW) adjusts the weights

Without non-linear activations, any number of layers would collapse into a single linear model.

AdvancedMachine Learning
Quick answerIn deep networks, gradients multiplied through many layers can shrink towards zero (vanishing, so early layers stop learning) or grow uncontrollably (exploding, so training diverges). Solutions: ReLU-family activations, careful weight initialisation (He, Xavier), batch or layer normalisation, residual (skip) connections as in ResNets and transformers, gradient clipping (for exploding gradients), and gated architectures (LSTM/GRU) for recurrent networks.
AdvancedMachine Learning
  • 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?

AdvancedMachine Learning
Quick answerTransfer learning reuses a model pre-trained on a large dataset as the starting point for a new task, so you need far less labelled data and compute. Approaches: use the model as a frozen feature extractor and train a small head; fine-tune some or all layers with a low learning rate; or use parameter-efficient fine-tuning (LoRA, adapters) for large models. Examples: fine-tuning a vision model on medical images, or adapting an LLM to a company's support tone.
AdvancedMachine Learning
Quick answerDropout randomly zeroes a fraction of activations during training so the network can't rely on specific neurons — a strong regulariser that is turned off at inference. Batch normalisation normalises a layer's inputs over the mini-batch and then learns a scale and shift; it stabilises and speeds up training and allows higher learning rates. Transformers use layer normalisation, which normalises across features per example and doesn't depend on batch size.
AdvancedMachine Learning
Quick answerMLOps applies DevOps practices to machine learning so models can be built, deployed and maintained reliably. The lifecycle:
  1. Data: ingestion, validation, versioning (DVC, Delta Lake) and a feature store for consistent training and serving features
  2. Training: reproducible pipelines with experiment tracking (MLflow, Weights & Biases)
  3. Evaluation: offline metrics, fairness and robustness checks
  4. Model registry and CI/CD: versioned models, automated tests and approvals
  5. Deployment: batch scoring, real-time APIs or edge, using shadow, canary or A/B releases
  6. Monitoring: data drift, prediction drift, model performance, latency and cost — with alerts and retraining triggers
AdvancedMachine Learning
Quick answerData (covariate) drift: the distribution of input features changes (new user demographics, a new device type). Concept drift: the relationship between features and the target changes (fraudsters change tactics; buying behaviour shifts after a policy change). Detect drift by monitoring feature distributions (PSI, KL divergence, Kolmogorov–Smirnov tests), prediction distributions and — once labels arrive — actual performance metrics. Respond with investigation, retraining on recent data or redesigning features.

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?

AdvancedMachine Learning
Quick answerBatch inference scores large datasets on a schedule (nightly churn scores, weekly recommendations) — cheap, simple and easy to monitor, but predictions can be stale. Real-time inference serves predictions through a low-latency API at request time (fraud checks during payment, search ranking) — it needs fast feature retrieval (an online feature store), autoscaling, latency SLOs and careful handling of training-serving skew. Streaming inference processes events continuously (Kafka/Flink) in between.

How interviewers ask it“How would you design a recommendation system? Walk me through your approach.”

How would you design a recommendation system?

AdvancedMachine Learning
Quick answerA typical large-scale design uses stages:
  1. 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
  2. Ranking: a richer model (gradient boosting or a deep network) scores candidates using user, item and context features, optimising engagement or conversion
  3. Re-ranking: apply business rules, diversity, freshness and fairness constraints
  4. 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?

AdvancedMachine Learning
  • 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?

AdvancedMachine Learning
Quick answerPackage the model with its preprocessing (a single pipeline object or ONNX export), serve it behind an API (FastAPI, BentoML, TorchServe, Triton or a managed endpoint such as SageMaker or Vertex AI), containerise it with Docker and run it on Kubernetes or serverless infrastructure. Add input validation, versioning, logging of features and predictions, health checks and autoscaling. Release with shadow or canary deployment, compare with the current model, and keep a rollback path.

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?

AdvancedMachine Learning
Quick answerStart from the problem and constraints: data size and type (tabular, text, images), the need for interpretability, latency and cost budgets, and how much labelled data exists. Build a simple baseline first (a heuristic, logistic regression), then try stronger models — gradient boosting for tabular data, pre-trained deep models or foundation models for text, images and audio. Compare with cross-validation on the metric that reflects business value, and prefer the simplest model that meets the target.
AdvancedMachine Learning
Quick answerModels can reproduce or amplify biases present in historical data (for example in hiring or lending). Address it by auditing data representation, evaluating metrics by subgroup (demographic parity, equal opportunity, calibration across groups), removing or carefully handling proxy features, re-weighting or constrained training, human review for high-stakes decisions, documentation (model cards, datasheets) and compliance with regulations such as the EU AI Act.
AdvancedMachine Learning
Quick answerIn reinforcement learning, an agent interacts with an environment: it observes a state, takes an action, receives a reward and learns a policy that maximises long-term cumulative reward, balancing exploration and exploitation. Methods include value-based (Q-learning, DQN), policy-gradient (REINFORCE, PPO) and actor-critic algorithms. Uses: robotics and control, games, recommendation and ad bidding, and RLHF / RL from verifiable rewards to align and improve LLMs.

Machine Learning Coding Interview Questions (Programs with Code)

6 questions

Hands-on Machine Learning programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.

CodingMachine Learning
Quick answerA Pipeline with a ColumnTransformer keeps preprocessing inside each fold, preventing leakage, and produces one deployable object.
Python
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)))
CodingMachine Learning
Quick answerVectorised gradient descent on mean squared error.
Python
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]
CodingMachine Learning
Quick answerCount the confusion-matrix cells and apply the formulas, guarding against division by zero.
Python
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)
CodingMachine Learning
Quick answerAlternate assignment and centroid-update steps until the centroids stop moving.
Python
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, centroids
CodingMachine Learning
Quick answerSearch the important hyperparameters with cross-validation, then evaluate on a hold-out set.
Python
from 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))
CodingMachine Learning
Quick answerLoad the saved pipeline once at startup, validate inputs with Pydantic, and return predictions with probabilities.
Python
# 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 8000

Practise 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 →

Machine Learning interview FAQ

What topics are asked in a machine learning interview?
Supervised vs unsupervised learning, the bias-variance trade-off, overfitting and regularisation, core algorithms (regression, trees, ensembles, SVM, k-means), evaluation metrics (precision, recall, F1, ROC-AUC, RMSE), cross-validation, feature engineering, class imbalance, neural network basics and ML system design.
Which machine learning algorithms should I know for interviews?
Linear and logistic regression, decision trees, random forests, gradient boosting (XGBoost, LightGBM), k-nearest neighbours, Naive Bayes, SVM, k-means and PCA — plus neural networks for deep learning roles. Know how each works, its assumptions, when to use it and its main hyperparameters.
What is the difference between AI, machine learning and deep learning?
AI is the broad goal of making machines perform tasks that need intelligence. Machine learning is the approach of learning from data. Deep learning is a subset of ML that uses multi-layer neural networks and powers modern vision, speech and large language models.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.