Home / Free AI tools / ML interview questions
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
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 courseSupervised 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 courseClassification 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 courseOverfitting 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 courseError 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 courseThe 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 courseLeakage 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 courseFrame 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 courseA 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 courseParameters 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 courseFirst 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 courseModels 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 courseOne-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 courseCreating 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 courseUse 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 courseLook 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 courseAs 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 coursePrecision 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 courseWhen 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 courseThe 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 courseThe 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 courseA 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 courseThe 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 courseMAE (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 courseA 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 courseA 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 courseIt 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 courseBoth 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 courseStart 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 courseBatch 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 courseToo 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 courseAt 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 courseBagging 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 courseEach 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 courseThe 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 courseImpurity-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 courseTo 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 courseFind 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 courseMany 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 courseIt 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 courseYou 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 courseChoose 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 courseLook 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 courseIt 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 courseDefine 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 courseThe 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 courseWithout 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 courseIn 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 courseDuring 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 courseIt 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 courseAdam 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 courseConvolution 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 courseStarting 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 courseTry 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 courseSimple 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 courseEach 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 courseAttention 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 courseAttention 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 courseSplitting 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 courseIt 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 courseIt 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 courseVectors 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 courseBefore 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 coursePrompting 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 courseLow-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 coursePre-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 courseFluent 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 courseBuild 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 courseAn 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 courseText 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 courseAn 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 courseSave 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 courseData 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 courseRandomly 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 courseLeakage 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 courseThe 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 courseA 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 courseP(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 courseChoosing 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 courseIt 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 courseCorrelation 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