Home / Free AI tools / ML interview questions

Machine learning interview questions and answers

81 questions that come up in machine learning, data science and AI engineer interviews, with clear model answers. Each links to a free lesson that teaches the topic properly. Practise them as flashcards, then read the ones you missed.

Jump to: Fundamentals · Data and features · Evaluation · Linear models · Trees and ensembles · Other algorithms · Unsupervised learning · Deep learning · Transformers and LLMs · Production and MLOps · Statistics and probability

Fundamentals

BasicWhat is machine learning?

Building programs that learn a pattern from examples instead of following rules written by hand. You give the algorithm data (and, for supervised learning, the right answers), it fits a model, and the model makes predictions on new data it has not seen.

Learn this in the free course
BasicWhat is the difference between supervised, unsupervised and reinforcement learning?

Supervised learning learns from labelled examples (inputs with known answers), for example predicting house prices. Unsupervised learning finds structure in unlabelled data, such as clusters or a lower-dimensional view. Reinforcement learning learns by acting in an environment and receiving rewards.

Learn this in the free course
BasicWhat is the difference between classification and regression?

Classification predicts a category (spam or not spam, which of 10 digits). Regression predicts a number (a price, a temperature). Many algorithms have both versions, such as decision trees and k-nearest neighbours.

Learn this in the free course
BasicWhat is overfitting, and how do you prevent it?

Overfitting is when a model learns the noise in its training data, so it scores well on training data but badly on new data. Prevent it with more data, a simpler model, regularisation, early stopping, dropout (for neural networks), data augmentation and honest validation with cross-validation.

Learn this in the free course
IntermediateExplain the bias-variance trade-off.

Error on new data comes from bias (the model is too simple to capture the pattern, so it underfits) and variance (the model is so flexible it changes a lot with the training sample, so it overfits). Making a model more complex usually lowers bias and raises variance; the goal is the complexity with the lowest total error, found with validation data.

Learn this in the free course
BasicWhy do we split data into training, validation and test sets?

The training set fits the model, the validation set is used to choose settings and compare models, and the test set is used once at the end for an honest estimate of performance on new data. If you tune on the test set, its score becomes optimistic.

Learn this in the free course
IntermediateWhat is data leakage? Give an example.

Leakage is when information that will not be available at prediction time gets into training, so the model looks better than it really is. Examples: scaling with statistics from the whole dataset before splitting, a feature recorded after the outcome (such as "treatment given" when predicting diagnosis), or the same patient appearing in both training and test sets.

Learn this in the free course
IntermediateWalk me through how you would approach a new ML project.

Frame the problem first: who uses the prediction, for what decision, and how success is measured. Then get and audit the data, build a simple baseline, split the data the way the model will be used, iterate on features and models with cross-validation, test once on held-out data, check errors and fairness by group, then deploy with monitoring and a plan for retraining.

Learn this in the free course
BasicWhat is a baseline model and why do you need one?

A very simple model, such as predicting the average or the most common class, or a one-feature rule. It tells you whether your complex model is actually adding value. A 95% accurate model is not impressive if 95% of cases belong to one class.

Learn this in the free course
BasicWhat is the difference between a parameter and a hyperparameter?

Parameters are learned from data during training, such as the weights of a linear model. Hyperparameters are chosen before training and control how learning happens, such as the learning rate, the depth of a tree or k in k-nearest neighbours. They are tuned with validation data.

Learn this in the free course

Data and features

BasicHow do you handle missing values?

First find out why they are missing. Options: drop rows or columns (if few and random), impute with the mean, median or most frequent value, use model-based imputation, or add a "was missing" indicator because missingness can itself be informative. Fit the imputer on training data only.

Learn this in the free course
BasicWhy scale features, and which models need it?

Models that use distances or gradient descent (k-NN, SVM, linear and logistic regression with regularisation, neural networks, PCA) are affected by the units of each feature. Standardisation (subtract the mean, divide by the standard deviation) or min-max scaling puts features on comparable scales. Tree-based models do not need it.

Learn this in the free course
BasicHow do you encode categorical variables?

One-hot encoding creates a 0/1 column per category and suits most models. Ordinal encoding (1, 2, 3) only makes sense if categories have a natural order. For many categories, use target encoding (with cross-fitting to avoid leakage), hashing or learned embeddings.

Learn this in the free course
IntermediateWhat is feature engineering? Give examples.

Creating inputs that make the pattern easier to learn: ratios (debt to income), dates broken into day of week and hour, counts and averages over time windows, text turned into TF-IDF or embeddings, and interactions between features. Good features often matter more than the choice of algorithm.

Learn this in the free course
IntermediateHow do you deal with an imbalanced dataset?

Use metrics that reflect the minority class (precision, recall, F1, PR-AUC) instead of accuracy, use stratified splits, set class weights in the model, try resampling (oversampling the minority or undersampling the majority) inside cross-validation only, and choose the decision threshold from the real costs of each kind of error.

Learn this in the free course
BasicHow do you detect and handle outliers?

Look at plots and summary statistics, and use rules such as values more than 1.5 × IQR outside the quartiles or very large z-scores. Then decide whether they are errors (fix or remove) or real extreme cases (keep them, and consider robust models, transforms such as log, or capping).

Learn this in the free course
IntermediateWhat is the curse of dimensionality?

As the number of features grows, the space becomes so large that data points are far apart and distances become less meaningful. Models need far more data to generalise, and distance-based methods like k-NN degrade. Feature selection and dimensionality reduction help.

Learn this in the free course

Evaluation

BasicExplain precision and recall.

Precision is the share of predicted positives that are really positive: of the emails flagged as spam, how many were spam. Recall is the share of real positives that were found: of all spam emails, how many were caught. Raising the threshold usually increases precision and lowers recall.

Learn this in the free course
BasicWhen is accuracy a bad metric?

When classes are imbalanced or errors have different costs. If 1% of transactions are fraud, a model that always says "not fraud" is 99% accurate and useless. Use recall, precision, F1, PR-AUC or a cost-based metric instead.

Learn this in the free course
IntermediateWhat does ROC-AUC measure?

The probability that the model ranks a random positive example above a random negative one, across all thresholds. 0.5 is random and 1.0 is perfect ranking. It ignores calibration and can look good on very imbalanced data, where PR-AUC is often more informative.

Learn this in the free course
BasicWhat is the F1 score?

The harmonic mean of precision and recall: 2PR / (P + R). It is high only when both are high, so it is useful when you care about both and classes are imbalanced.

Learn this in the free course
BasicWhat is a confusion matrix?

A table of predicted against actual classes. For two classes it counts true positives, false positives, true negatives and false negatives, from which accuracy, precision, recall and specificity are calculated.

Learn this in the free course
IntermediateWhat is k-fold cross-validation and when would you not use plain k-fold?

The data is split into k parts; the model is trained k times, each time validating on a different part, and the scores are averaged. Do not use plain random k-fold for time series (use forward-chaining splits) or when rows are grouped, such as several visits per patient (use group k-fold so a group is never in both).

Learn this in the free course
BasicWhich regression metrics do you know, and how do they differ?

MAE (mean absolute error) is in the target's units and treats all errors linearly. RMSE squares errors first, so it punishes large errors more. R² is the share of variance explained, compared with predicting the mean. MAPE gives percentage errors but breaks near zero.

Learn this in the free course
AdvancedWhat is model calibration and why does it matter?

A model is calibrated when its predicted probabilities match reality: of cases given 0.8, about 80% are positive. It matters when probabilities drive decisions, such as risk thresholds or expected costs. Check it with a reliability plot and fix it with Platt scaling or isotonic regression on held-out data.

Learn this in the free course

Linear models

BasicWhat are the assumptions of linear regression?

A linear relationship between features and target, independent errors, constant variance of errors (homoscedasticity), and roughly normal errors for valid confidence intervals. Strongly correlated features (multicollinearity) make individual coefficients unstable.

Learn this in the free course
BasicWhy is logistic regression a classification method if it has "regression" in its name?

It models the log-odds of the positive class as a linear function of the features, then passes that through the sigmoid function to get a probability between 0 and 1. A threshold on that probability turns it into a class.

Learn this in the free course
IntermediateWhat is the difference between L1 and L2 regularisation?

Both add a penalty on weight size to the loss. L1 (lasso) adds the sum of absolute weights and pushes some weights exactly to zero, so it also selects features. L2 (ridge) adds the sum of squared weights and shrinks all weights smoothly, which helps with correlated features. Elastic net combines them.

Learn this in the free course
BasicHow does gradient descent work?

Start with some parameters, compute the gradient of the loss (the direction in which the loss rises fastest), and take a small step in the opposite direction. Repeat until the loss stops falling. The step size is the learning rate.

Learn this in the free course
IntermediateWhat is the difference between batch, stochastic and mini-batch gradient descent?

Batch uses all the data for each step: accurate but slow. Stochastic uses one example per step: fast and noisy. Mini-batch uses a small batch such as 32–512 examples, balancing speed, noise and efficient use of GPUs, and is the standard choice.

Learn this in the free course
BasicWhat happens if the learning rate is too high or too low?

Too high and the steps overshoot the minimum, so the loss bounces around or explodes. Too low and training is very slow and can stall. Learning-rate schedules and adaptive optimisers like Adam help.

Learn this in the free course

Trees and ensembles

BasicHow does a decision tree decide where to split?

At each node it tries candidate splits on each feature and picks the one that makes the child nodes purest: the largest drop in Gini impurity or entropy for classification, or in squared error for regression. It repeats until a stopping rule such as maximum depth.

Learn this in the free course
BasicWhat is the difference between bagging and boosting?

Bagging trains many models independently on bootstrap samples and averages them, which reduces variance (random forests). Boosting trains models one after another, each focusing on the errors of the ones before, which reduces bias (gradient boosting, XGBoost, LightGBM).

Learn this in the free course
IntermediateWhy does a random forest usually beat a single decision tree?

Each tree is trained on a bootstrap sample and considers a random subset of features at each split, so the trees make different errors. Averaging many decorrelated trees keeps their low bias but greatly reduces variance.

Learn this in the free course
IntermediateWhat are the key hyperparameters of gradient boosting?

The number of trees, the learning rate (smaller needs more trees but generalises better), tree depth or number of leaves, the minimum samples per leaf, row and column subsampling, and regularisation terms. Use early stopping on a validation set to choose the number of trees.

Learn this in the free course
IntermediateHow do tree models measure feature importance, and what are the pitfalls?

Impurity-based importance adds up how much each feature reduced impurity. It favours features with many unique values and is computed on training data. Permutation importance on validation data, or SHAP values, are more reliable. Correlated features share importance, so neither may look important alone.

Learn this in the free course

Other algorithms

BasicHow does k-nearest neighbours work?

To predict a new point, find the k closest training points by a distance measure and take a majority vote (classification) or the average (regression). There is no training step, but prediction is slow on large data, and features must be scaled.

Learn this in the free course
IntermediateWhat is the idea behind support vector machines?

Find the boundary that separates the classes with the widest possible margin. Only the points closest to the boundary (the support vectors) define it. The C parameter trades margin width against training errors, and kernels let it draw non-linear boundaries.

Learn this in the free course
AdvancedWhat is the kernel trick?

Many algorithms only need dot products between points. A kernel function computes the dot product as if the points had been mapped into a higher-dimensional space, without computing that mapping. This lets a linear method such as an SVM learn non-linear boundaries cheaply.

Learn this in the free course
IntermediateWhy is Naive Bayes called "naive"?

It assumes every feature is independent of the others given the class, which is rarely true. Even so, it works well for text classification and as a fast baseline, because it only needs the class to be ranked correctly, not the probabilities to be exact.

Learn this in the free course
IntermediateHow is evaluating a time-series model different?

You must never train on the future. Use time-ordered splits such as a walk-forward backtest, build features only from past values, and compare against naive baselines such as "same as last week". Random cross-validation leaks future information.

Learn this in the free course

Unsupervised learning

BasicHow does k-means work?

Choose k starting centres, assign each point to its nearest centre, move each centre to the mean of its points, and repeat until assignments stop changing. It assumes roughly round clusters of similar size, needs scaled features, and k must be chosen.

Learn this in the free course
IntermediateHow do you choose the number of clusters?

Look at the elbow in within-cluster error, the silhouette score, the stability of clusters across resamples, and above all whether the clusters are useful and interpretable for the business question. There is rarely one correct k.

Learn this in the free course
IntermediateWhat does PCA do?

It finds new axes (principal components) that are combinations of the original features, ordered by how much variance they capture, and lets you keep only the first few. It is used to compress data, remove correlated features, speed up models and visualise data in 2D. Scale the features first.

Learn this in the free course
IntermediateHow would you build an anomaly detection system?

Define what counts as an anomaly and how alerts will be used. Start with simple statistical rules, then try methods such as isolation forest, local outlier factor or reconstruction error from an autoencoder. Evaluate on any labelled incidents you have, and tune the threshold to an alert volume people can act on.

Learn this in the free course

Deep learning

BasicWhat is backpropagation?

The algorithm that computes the gradient of the loss with respect to every weight in a neural network. It applies the chain rule layer by layer from the output back to the input, reusing intermediate results so the cost is about the same as one forward pass.

Learn this in the free course
BasicWhy do neural networks need non-linear activation functions?

Without them, stacking layers is still just one linear function, so depth adds nothing. Non-linear activations like ReLU let networks represent complex, curved functions.

Learn this in the free course
IntermediateWhat are vanishing and exploding gradients, and how are they fixed?

In deep networks, gradients are multiplied through many layers and can shrink towards zero (early layers stop learning) or blow up (training diverges). Fixes include ReLU-type activations, careful initialisation (He, Xavier), normalisation layers, residual connections, gradient clipping and LSTMs or GRUs for sequences.

Learn this in the free course
IntermediateHow does dropout work?

During training, each unit is switched off at random with some probability, so the network cannot rely on any one unit and learns more robust features. At test time all units are used (with activations scaled to match). It acts like averaging many smaller networks.

Learn this in the free course
IntermediateWhat does batch normalisation do?

It normalises each layer's inputs over the mini-batch to zero mean and unit variance, then applies a learned scale and shift. It makes training faster and more stable and allows higher learning rates. Transformers usually use layer normalisation instead, which normalises over features rather than the batch.

Learn this in the free course
IntermediateHow does Adam differ from plain SGD?

Adam keeps a running average of past gradients (momentum) and of their squares, and gives each parameter its own step size. It usually trains faster with little tuning. SGD with momentum and a good schedule can generalise slightly better in some vision tasks. AdamW, which decouples weight decay, is the common default.

Learn this in the free course
BasicWhy do CNNs work well for images?

Convolution layers slide small filters across the image, so the same feature detector (an edge, a texture) is reused everywhere, which needs far fewer weights than a fully connected layer. Stacked layers build up from edges to parts to objects, and pooling or striding adds some tolerance to position.

Learn this in the free course
BasicWhat is transfer learning?

Starting from a model pre-trained on a large dataset and adapting it to your task, either by training only a new final layer or by fine-tuning some or all layers with a small learning rate. It gives strong results with far less data and compute.

Learn this in the free course
IntermediateYour training loss is not going down. What do you check?

Try to overfit a tiny batch first: if it cannot, there is a bug. Then check the data and labels, the loss function and output layer match the task, the learning rate (often too high or too low), that gradients flow (no detached tensors, sensible magnitudes), input normalisation, and that you call zero_grad each step.

Learn this in the free course
IntermediateWhat problem do LSTMs solve compared with simple RNNs?

Simple RNNs struggle to keep information over long sequences because gradients vanish through time. LSTMs add a cell state with gates that decide what to keep, forget and output, which lets information and gradients flow over many steps.

Learn this in the free course

Transformers and LLMs

IntermediateExplain self-attention.

Each token makes a query, key and value vector. A token's output is a weighted average of all tokens' values, where the weights come from a softmax of the dot products between its query and every key (scaled by the square root of the key size). This lets every token gather information from any other token directly.

Learn this in the free course
IntermediateWhy did transformers replace RNNs for language?

Attention connects any two positions in one step, so long-range relationships are easier to learn, and the whole sequence is processed in parallel instead of token by token, which makes training on huge datasets on GPUs practical.

Learn this in the free course
IntermediateWhy do transformers need positional encodings?

Attention on its own treats the input as an unordered set, so "dog bites man" and "man bites dog" would look the same. Positional encodings (fixed sinusoids, learned vectors, or rotary embeddings in most modern LLMs) add information about each token's position.

Learn this in the free course
BasicWhat is tokenisation in LLMs?

Splitting text into the units the model reads: usually sub-word pieces learned with byte-pair encoding or similar, so common words are one token and rare words are split into parts. Costs, context limits and some odd behaviours (such as miscounting letters) come from tokenisation.

Learn this in the free course
BasicHow does an LLM generate text?

It predicts a probability for every possible next token, picks one (by sampling with settings such as temperature and top-p, or taking the most likely), adds it to the input and repeats. Each new token is predicted from everything before it.

Learn this in the free course
BasicWhat does temperature do?

It divides the scores before the softmax. Low temperature makes the most likely tokens even more likely, giving focused, repeatable output. High temperature flattens the distribution, giving more varied and creative but less reliable output.

Learn this in the free course
BasicWhat are embeddings?

Vectors of numbers that represent words, sentences, images or other items so that similar meanings are close together. They let you measure similarity with cosine similarity, and power semantic search, clustering, recommendations and RAG.

Learn this in the free course
IntermediateWhat is retrieval-augmented generation (RAG), and why use it?

Before answering, the app searches a document collection (usually with embeddings, often combined with keyword search), puts the best passages into the prompt, and asks the model to answer from them with citations. It gives the model up-to-date and private knowledge, and reduces made-up answers, without retraining.

Learn this in the free course
IntermediateWhen would you fine-tune an LLM instead of using prompting or RAG?

Prompting first; RAG when the model needs knowledge it lacks or that changes; fine-tuning when you need a consistent behaviour, format or style that prompting cannot reliably produce, or to make a small model do one narrow task well. Fine-tuning is poor at adding facts that change.

Learn this in the free course
AdvancedWhat is LoRA?

Low-Rank Adaptation freezes the pre-trained weights and learns small low-rank matrices that are added to some weight matrices. It trains a tiny fraction of the parameters, needs far less memory, and the adapters can be swapped or merged. QLoRA does the same on a 4-bit quantised base model.

Learn this in the free course
AdvancedHow are chat models trained after pre-training?

Pre-training on large text teaches next-token prediction. Supervised fine-tuning on instruction and answer examples teaches the assistant format. Preference training (RLHF, DPO and related methods) uses human or AI judgements of which answer is better to make responses more helpful and safer.

Learn this in the free course
IntermediateWhat are hallucinations and how do you reduce them?

Fluent but false statements, because the model generates likely text rather than looking facts up. Reduce them with RAG and instructions to answer only from sources and cite them, allowing "I don't know", lower temperature, checking outputs against sources, and evaluating with test sets.

Learn this in the free course
IntermediateHow do you evaluate an LLM application?

Build a test set of realistic inputs with expected answers or criteria. Use exact checks where possible, rubric-based scoring by people or an LLM judge (checked against human labels), and separate retrieval metrics (recall@k) from answer quality (faithfulness to sources). Track cost and latency, and rerun the set on every change.

Learn this in the free course
IntermediateWhat is an AI agent, and when should you not build one?

An agent lets the model choose its own steps in a loop: think, call a tool, read the result, decide what next. Do not build one when the steps are known in advance; a fixed workflow is cheaper, faster and easier to test. Agents need tool permissions kept to a minimum, budgets, logging and human approval for risky actions.

Learn this in the free course
IntermediateWhat is prompt injection?

Text that tries to override the app's instructions, either typed by a user or hidden in content the model reads, such as a web page or email. Defences: treat all retrieved content as untrusted, give tools least privilege, require confirmation for risky actions, keep secrets out of prompts, and filter and monitor outputs.

Learn this in the free course
IntermediateWhat is the Model Context Protocol (MCP)?

An open standard for connecting AI applications to tools and data. A server exposes tools (actions), resources (data to read) and prompts (templates); any MCP-compatible app, such as a chat app or coding assistant, can then use them without custom integration code for each pair.

Learn this in the free course

Production and MLOps

BasicHow would you deploy a machine learning model?

Save the whole pipeline (preprocessing and model) as one versioned artefact, wrap it in an API (for example FastAPI or Flask) with input validation, package it in a Docker image, add tests and CI, deploy it, and monitor inputs, predictions, latency and errors. Batch scoring on a schedule is often simpler when real-time predictions are not needed.

Learn this in the free course
IntermediateWhat is data drift and concept drift?

Data drift is when the inputs change (new customer types, a changed sensor). Concept drift is when the relationship between inputs and the target changes (behaviour after a policy change). Monitor input distributions and, when labels arrive, performance; retrain or roll back when drift hurts results.

Learn this in the free course
IntermediateHow would you A/B test a new model?

Randomly split traffic between the current and new model, decide the main metric and the sample size in advance, run long enough to cover weekly patterns, and check guardrail metrics. Use a statistical test or confidence interval on the difference, and avoid stopping early just because it looks good.

Learn this in the free course
BasicYour model is 95% accurate offline but users say it is bad. What could be wrong?

Leakage or a split that does not match real use, a metric that does not match the user's goal, training data that differs from live data, preprocessing that differs between training and serving, imbalanced classes hiding failures, or problems for specific groups that an overall score hides. Look at real errors.

Learn this in the free course

Statistics and probability

BasicWhat is a p-value?

The probability of seeing a result at least as extreme as the one observed if the null hypothesis were true. A small p-value suggests the data are unlikely under the null. It is not the probability that the null hypothesis is true, and it says nothing about how big or important the effect is.

Learn this in the free course
BasicWhat is a confidence interval?

A range built by a method that, over many repeated samples, contains the true value a stated share of the time (for example 95%). It shows both the estimate and its uncertainty, which is more useful than a yes/no significance test.

Learn this in the free course
IntermediateExplain Bayes' theorem with an example.

P(A|B) = P(B|A)·P(A) / P(B). If a disease affects 1 in 1,000 people and a test catches 99% of cases with a 5% false-positive rate, a positive result means only about a 2% chance of disease, because false positives from the large healthy group outnumber true positives.

Learn this in the free course
AdvancedWhat is maximum likelihood estimation?

Choosing the parameters that make the observed data most probable under the model. Minimising mean squared error is maximum likelihood with Gaussian noise, and minimising cross-entropy (log loss) is maximum likelihood for a classifier's predicted probabilities.

Learn this in the free course
IntermediateWhy is cross-entropy used as the loss for classification?

It is the negative log-likelihood of the true class under the model's predicted probabilities, so minimising it is maximum likelihood. It heavily penalises confident wrong answers, and with a softmax output its gradient is simple and well-behaved.

Learn this in the free course
IntermediateWhat is the difference between correlation and causation?

Correlation means two variables move together; causation means changing one changes the other. Correlation can come from a confounder, reverse causation or chance. Randomised experiments, or careful causal methods with stated assumptions, are needed to claim cause.

Learn this in the free course

How to answer well in an ML interview