Technology

Machine Learning Interview Questions and Answers

Machine learning interviews test theory, practical modelling and judgement. These machine learning interview questions cover supervised and unsupervised learning, overfitting and evaluation metrics for freshers, then bias-variance, regularisation, ensemble methods, feature engineering, imbalanced data and deploying models for experienced data scientists.

30 questions · Updated

Reading answers is not the same as saying them.Practise Machine Learning questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
Machine Learning Interview Questions with answers. Examples: What is the difference between supervised, unsupervised and reinforcement learning? What is overfitting, and how do you prevent it? Why do we split data into training, validation and test sets? Explain precision, recall, F1-score and ROC-AUC.
Machine Learning Interview Questions: 30 questions with model answers on this page.

Basic Machine Learning interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is the difference between supervised, unsupervised and reinforcement learning?

Answer flow · 3 steps
  1. Supervised learning trains on labelled data to predict an output, such as classification (spam or not) and regression (house prices).

  2. Unsupervised learning finds patterns in unlabelled data, such as clustering customers or reducing dimensions.

  3. Reinforcement learning trains an agent to take actions that maximise reward through trial and error, as in games or robotics.

2. What is overfitting, and how do you prevent it?

Answer flow · 3 steps
  1. Overfitting is when a model learns noise in the training data and performs well on it but poorly on new data.

  2. I prevent it with more training data, simpler models, regularisation (L1 or L2), cross-validation, early stopping, dropout in neural networks, pruning trees and feature selection.

  3. Underfitting is the opposite: the model is too simple to capture the pattern.

3. Why do we split data into training, validation and test sets?

Answer flow · 3 steps
  1. The training set is used to fit the model, the validation set to tune hyperparameters and choose models, and the test set is kept untouched until the end to estimate performance on new data.

  2. Using the test set for tuning leaks information and gives an over-optimistic result.

  3. K-fold cross-validation makes better use of small datasets.

4. What is the difference between linear and logistic regression?

Linear regression predicts a continuous number, such as a house price, by fitting a straight line (or plane) that minimises squared errors. Logistic regression is used for classification: it passes a linear combination of features through the sigmoid function to output a probability between 0 and 1, such as the chance a customer will churn, and is trained with log loss.

5. What is the difference between classification and regression?

Answer flow · 3 steps
  1. Classification predicts a category, such as spam or not spam, fraud or genuine, or which of several products a customer will buy.

  2. Regression predicts a continuous value, such as sales next month or delivery time.

  3. They use different metrics: accuracy, precision, recall and F1 for classification, and MAE, RMSE and R-squared for regression.

6. What is a confusion matrix?

Answer flow · 3 steps
  1. A confusion matrix is a table comparing predicted and actual classes.

  2. For binary classification it shows true positives, false positives, true negatives and false negatives.

  3. Metrics such as accuracy, precision, recall and specificity are calculated from it, and it shows which kind of mistake a model makes, which matters because false negatives and false positives usually have different costs.

7. How does k-nearest neighbours work?

k-NN stores the training data and, for a new point, finds the k closest points using a distance measure such as Euclidean distance, then predicts the majority class (classification) or the average value (regression). It is simple and has no training phase, but prediction is slow on large datasets, it needs feature scaling, and it performs poorly with many features.

8. How does a decision tree decide where to split?

Answer flow · 3 steps
  1. At each node it tries possible splits on each feature and picks the one that makes the child groups most pure, measured by Gini impurity or entropy (information gain) for classification, or variance reduction for regression.

  2. It repeats until a stopping rule, such as maximum depth or minimum samples per leaf.

  3. Trees are easy to interpret but overfit easily without limits or pruning.

9. How does k-means clustering work?

k-means picks k starting centres, assigns each point to the nearest centre, moves each centre to the average of its points, and repeats until assignments stop changing. It is fast and simple, but you must choose k (using the elbow method or silhouette score), it assumes roughly round clusters of similar size, it is sensitive to scaling and outliers, and k-means++ gives better starting centres.

10. What is feature scaling, and when do you need it?

Answer flow · 5 steps
  1. Feature scaling puts features on comparable ranges.

  2. Normalisation (min-max scaling) maps values to 0 to 1; standardisation subtracts the mean and divides by the standard deviation.

  3. Algorithms based on distance or gradients, such as k-NN, k-means, SVM, linear models with regularisation and neural networks, need it.

  4. Tree-based models do not.

  5. The scaler must be fitted on training data only.

11. How do you handle missing values?

Answer flow · 3 steps
  1. First understand why data is missing.

  2. Options include dropping rows or columns when little data is lost, filling with the mean, median or most frequent value, using model-based imputation such as KNN or iterative imputers, adding an indicator column showing that a value was missing, or using models such as gradient boosting that handle missing values natively.

  3. Imputation must be fitted on training data only.

Intermediate Machine Learning interview questions

Applied problems, trade-offs and questions about your own projects.

12. Explain precision, recall, F1-score and ROC-AUC.

Answer flow · 4 steps
  1. Precision is the share of predicted positives that are correct; recall is the share of actual positives found.

  2. F1-score is their harmonic mean, useful when classes are imbalanced.

  3. ROC-AUC measures how well the model ranks positives above negatives across all thresholds.

  4. For fraud or disease detection I care most about recall, while for spam filters precision matters more.

13. What is the bias-variance trade-off?

Answer flow · 3 steps
  1. Bias is error from wrong assumptions, causing underfitting; variance is error from sensitivity to the training data, causing overfitting.

  2. Simple models have high bias and low variance; complex models have low bias and high variance.

  3. The goal is the right complexity that minimises total error on new data, using techniques like regularisation and ensembles.

14. What is the difference between L1 and L2 regularisation?

Answer flow · 4 steps
  1. Both add a penalty on model weights to the loss to reduce overfitting.

  2. L1 (Lasso) adds the sum of absolute weights and can shrink some weights to exactly zero, so it performs feature selection.

  3. L2 (Ridge) adds the sum of squared weights and shrinks weights smoothly without making them zero.

  4. Elastic Net combines both.

15. How do random forests and gradient boosting differ?

Answer flow · 3 steps
  1. Both are ensembles of decision trees.

  2. A random forest trains many deep trees independently on bootstrap samples and random feature subsets and averages them (bagging), which reduces variance and is robust with little tuning.

  3. Gradient boosting (XGBoost, LightGBM, CatBoost) trains shallow trees one after another, each correcting the previous errors, which often gives higher accuracy on tabular data but needs careful tuning.

16. What is k-fold cross-validation?

Answer flow · 3 steps
  1. The data is split into k folds; the model is trained k times, each time on k minus 1 folds and validated on the remaining fold, and the scores are averaged.

  2. This gives a more reliable estimate than a single split, especially for small datasets.

  3. Stratified k-fold keeps class proportions, group k-fold keeps related rows together, and time series need forward-chaining splits.

17. How do you tune hyperparameters?

Answer flow · 3 steps
  1. Hyperparameters, such as tree depth or learning rate, are set before training.

  2. Grid search tries every combination, random search samples combinations and is usually more efficient, and Bayesian optimisation tools such as Optuna choose promising values based on past results.

  3. Tuning is done with cross-validation on training data, and the test set is used only once at the end.

18. What is PCA?

Answer flow · 3 steps
  1. Principal Component Analysis reduces the number of features by finding new axes (principal components) that capture the most variance in the data, ordered from most to least important.

  2. It is used to speed up training, reduce noise, remove correlated features and visualise high-dimensional data in two dimensions.

  3. Data must be scaled first, and components are harder to interpret than original features.

19. How does an SVM work, and what is the kernel trick?

Answer flow · 3 steps
  1. A support vector machine finds the boundary that separates classes with the largest margin, defined by the closest points (support vectors), with a parameter C controlling how many errors are allowed.

  2. The kernel trick, using kernels such as RBF or polynomial, lets it find non-linear boundaries by implicitly mapping data into a higher-dimensional space.

  3. SVMs work well on medium-sized datasets but scale poorly to very large ones.

20. What is Naive Bayes, and why is it called naive?

Answer flow · 3 steps
  1. Naive Bayes applies Bayes' theorem to calculate the probability of each class given the features, and picks the most likely class.

  2. It is naive because it assumes all features are independent of each other given the class, which is rarely true.

  3. Even so, it is fast, needs little data and works well for text classification such as spam filtering.

21. How does gradient descent work?

Answer flow · 3 steps
  1. Gradient descent minimises a loss function by repeatedly moving the model's parameters a small step in the direction that reduces the loss most, given by the negative gradient.

  2. The learning rate controls the step size: too high diverges, too low is slow.

  3. Stochastic and mini-batch gradient descent use subsets of data per step, and optimisers such as Adam adapt the learning rate per parameter.

22. What is data leakage?

Answer flow · 3 steps
  1. Data leakage happens when information that would not be available at prediction time gets into training, giving excellent validation scores that fail in production.

  2. Examples are scaling or imputing using the whole dataset before splitting, features created from the target or from future events, and duplicate records across train and test sets.

  3. Using pipelines and time-based splits prevents most leakage.

High level Machine Learning interview questions

System design, deep internals, leadership and tough follow-ups.

23. How do you handle an imbalanced dataset?

Answer flow · 3 steps
  1. I use metrics that reflect the problem, such as precision, recall, F1 and PR-AUC, not accuracy.

  2. Then I try class weights in the model, resampling (undersampling the majority or oversampling the minority with SMOTE), collecting more minority examples, adjusting the decision threshold based on business costs, and algorithms that handle imbalance well, such as gradient boosting.

  3. Stratified splits keep class ratios consistent.

24. What is feature engineering, and give examples?

Answer flow · 3 steps
  1. Feature engineering creates inputs that make patterns easier for the model to learn, often improving results more than changing algorithms.

  2. Examples are extracting day of week and hour from timestamps, ratios such as debt to income, aggregations such as a customer's average order value, encoding categories with one-hot or target encoding, log-transforming skewed values, and text features with TF-IDF or embeddings.

  3. I avoid leaking future information.

25. How do you deploy and monitor a machine learning model?

Answer flow · 3 steps
  1. I package the model with its preprocessing in a pipeline, version it with a tool such as MLflow, and serve it through an API (FastAPI in a container) or batch jobs.

  2. In production I monitor latency and errors, input data drift, prediction distribution and actual performance once labels arrive, and set up retraining and rollback.

  3. A/B tests compare a new model with the old one before full rollout.

26. How do neural networks learn?

Answer flow · 3 steps
  1. A neural network has layers of neurons, each computing a weighted sum of inputs passed through a non-linear activation such as ReLU.

  2. In the forward pass it makes a prediction; the loss measures the error; backpropagation uses the chain rule to calculate how much each weight contributed to the error; and an optimiser updates the weights.

  3. This repeats over many batches and epochs.

27. What are transformers and attention?

A transformer is a neural network architecture built on self-attention, which lets each token in a sequence weigh how relevant every other token is when building its representation, capturing long-range context in parallel instead of step by step like RNNs. Transformers power large language models such as GPT and Claude, BERT-style encoders and vision transformers.

28. How do you explain a model's predictions?

Answer flow · 4 steps
  1. Global methods show which features matter overall, such as permutation importance or SHAP summary plots.

  2. Local methods explain individual predictions: SHAP values show each feature's contribution to one prediction, and LIME fits a simple model around one example.

  3. Partial dependence plots show how predictions change with a feature.

  4. Explanations are important for trust, debugging and regulated areas such as lending.

29. What is the curse of dimensionality?

As the number of features grows, data becomes sparse: points become far apart and distances lose meaning, so distance-based methods like k-NN work poorly, much more data is needed to cover the space, and models overfit more easily. Remedies are feature selection, dimensionality reduction such as PCA, regularisation, and domain knowledge to keep only useful features.

30. How do you choose a model for a new problem?

Answer flow · 3 steps
  1. Start from the business goal and the cost of each kind of error, then define a metric.

  2. Build a simple baseline first, such as predicting the average or a logistic regression, then try stronger models: gradient boosting for tabular data, convolutional networks or pre-trained models for images, and transformers for text.

  3. Weigh accuracy against interpretability, latency, data size, and the cost of training and maintaining the model.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a data scientist interview?

See all Data Scientist interview questions, covering Python, Pandas, NumPy, Statistics, Machine Learning and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields