Machine Learning interview questions
Models, metrics and the tradeoffs that decide whether a model survives contact with real data.
69 questions in this category.
The cards below cluster into the themes machine learning interviews keep circling back to: the bias-variance tradeoff and the regularization that moves it, picking metrics when the classes are imbalanced and reading them right, from sensitivity and specificity to calibration, log loss and ranking scores like NDCG, cross-validation and the leakage that quietly inflates it, ensembles from bagging to boosting, and the encoding choices that decide what a model ever gets to see.
Start with these
Learning paradigms7 questions
Interviews often open by checking the map of the field: supervised learning learns from labeled examples, unsupervised learning finds structure such as clusters without labels, data can arrive all at once or as a stream, and causal modeling asks what would change under an intervention.
- What is unsupervised learning?
- Machine learning on data without labels: the algorithm finds structure in the inputs alone, through clustering, dimensionality reduction or anomaly detection. Examples include k-means, PCA, DBSCAN, hierarchical clustering, Gaussian mixture models and isolation forest.
- What is supervised learning?
- Machine learning that learns from labeled data: examples paired with the correct output. Classification predicts a category and regression a number; common algorithms include linear and logistic regression, decision trees, random forests, gradient boosting, SVMs, k-nearest neighbors and neural networks.
- What is clustering?
- Clustering algorithms group objects such that similar feature points are put into the same groups (clusters).
- Is KNN a clustering algorithm?
- No. It is a supervised learning method that could be used for classification and regression problems.
- What is the difference between online and batch learning?
- Batch (offline) learning trains on the whole dataset at once and must be retrained to absorb new data. Online learning updates the model incrementally as each new example, or small group of examples, arrives.
- What is the main data structure used in causal modelling?
- Graphs! More specifically, directed acyclic graphs.
Linear models, SVMs and naive Bayes7 questions
Expect to defend the simple models before the fancy ones: why logistic regression counts as a linear model and whether it needs scaled features, what a perfectly collinear column does to a regression, which kernels an SVM uses, and what makes naive Bayes naive.
- Is logistic regression a linear model? Why?
- Logistic regression is considered a generalized linear model because the outcome always depends on the sum of the inputs and parameters.
- Is logistic regression useful for estimating continuous variables?
- No. Logistic regression models a categorical, usually binary, outcome: its output is the probability, between 0 and 1, that an example is in the positive class, not an estimate of a continuous target such as a price.
- Is standardization of features required before training a logistic regression?
- No — rescaling a feature just rescales its coefficient, so the predictions are unchanged. It still matters in practice: gradient descent converges far faster when features share a scale, and any L1 or L2 penalty is scale-dependent, so unscaled features get penalised unevenly.
- What happens to our linear regression if we have columns x, y and z, and z is the sum of x and y?
- The coefficients are no longer unique: z is a linear combination of x and y (perfect multicollinearity), so XᵀX is singular and infinitely many coefficient sets give the same fit. Predictions still work; drop z or use ridge regression.
- Name three types of kernels in SVM.
- Linear, polynomial and RBF (radial basis function), with sigmoid a fourth. A kernel computes inner products in a higher-dimensional space without ever building that space, so linear is the default for wide sparse text and RBF for low-dimensional, curved boundaries.
- Why is naive Bayes 'naive'?
- Because it assumes the features are independent of each other given the class, so an example's likelihood is simply the product of each feature's likelihood.
Trees and ensembles9 questions
Tree questions check what a split ignores, such as feature scaling, and how pruning keeps a tree from memorizing the training set. Ensemble questions come down to one contrast: bagging and random forests average independent trees to cut variance, while boosting fits trees in sequence, each correcting the last, mainly to cut bias.
- Explain the basic concept of random forest.
- An ensemble of many decision trees, each trained on a bootstrap sample of the rows and choosing each split from a random subset of features. It predicts by majority vote or by averaging the trees' outputs; it doesn't pick one best tree.
- What does "random" mean in the term random forest?
- Two sources of randomness: each tree is trained on a bootstrap sample of the rows, and each split considers only a random subset of the features, drawn afresh at every split. Averaging these decorrelated trees reduces variance.
- What is pruning in a decision tree?
- Removing sub-nodes that do not earn their keep, so a fully grown tree stops fitting noise. Pre-pruning caps growth up front with max depth or minimum samples per leaf; post-pruning grows the tree, then collapses branches whose removal does not hurt held-out error.
- Imagine you are applying a decision-tree-based model to a numerical dataset and you run an experiment where you scale the features. Which model would give better results, the original or the scaled one?
- They should give the same result because tree-based models are scale invariant.
- What is ensemble learning?
- Combining individual models together with the purpose of improving the predictive power of the model.
- What is bagging?
- Bootstrap aggregating: train the same model on many bootstrap samples of the data, drawn with replacement, and average or vote their predictions. It mainly cuts variance, which is why it suits deep, unstable trees.
- What is boosting when referring to machine learning algorithms?
- A family of ensemble methods that trains weak learners in sequence, each one focusing on the examples the previous ones got wrong, and combines them in a weighted vote or sum to form a strong learner. AdaBoost and gradient boosting are the best-known examples.
- What is the difference between boosting and bagging?
- Bagging trains models independently on bootstrap samples and averages or votes their predictions, which mainly reduces variance. Boosting trains weak learners one after another, each focusing on the errors of the ensemble so far, and combines them in a weighted sum, which mainly reduces bias.
- How is random forest different from gradient boosting algorithm?
- The fundamental difference is, random forest uses bagging technique to make predictions. GBM uses boosting techniques to make predictions.
Overfitting, bias and variance8 questions
Almost every machine learning interview reaches the bias-variance tradeoff. These cards cover how to spot overfitting and underfitting, what high bias and high variance mean, and which way model complexity and feature selection push each one.
- What is the bias-variance tradeoff?
- The tension between underfitting and overfitting. Expected squared error splits into bias² (a model too simple for the truth), variance (sensitivity to the training sample) and irreducible noise. More complexity lowers bias and raises variance, so you tune it to minimize the sum.
- What is overfitting?
- When a model performs very well on its training set but poorly on new data, such as a test set, because it has fit the noise and quirks of the training data instead of only the underlying pattern.
- Creating a model that matches the training data so closely that the model fails to make correct predictions on new data.
- Overfitting: the model has memorised noise particular to the training set, so training error keeps falling while validation error turns back up. The fixes matter as much as the name: more data, regularization, early stopping, a simpler model, and cross-validation to detect it.
- Producing a model with poor predictive ability because the model hasn't captured the complexity of the training data.
- Underfitting: high bias, a model too simple for the signal, so training and validation error are both high and close to each other. Add capacity or better features, weaken the regularization, or train longer. More data will not rescue a model that cannot fit what it already has.
- What is variance in the context of machine learning?
- Variance is the error that comes from a model's sensitivity to small fluctuations in the training set: trained on a different sample, a high-variance model makes noticeably different predictions. High variance can cause an algorithm to model the random noise in the training data, which is overfitting.
- Does feature selection tend to increase overfitting?
- No. It actually could help to reduce overfitting.
Regularization6 questions
Regularization questions are mostly about L1 versus L2: which penalty is lasso and which is ridge, why only L1 drives weights to exactly zero and so selects features, how elastic net combines the two, and why none of it helps a model that underfits. Early stopping, which regularizes without a penalty term, is here too.
- What is the process of adding tuning parameters to a model to induce smoothness in order to prevent overfitting?
- Regularization: a penalty on parameter size added to the loss, so the fit stays smooth rather than chasing every training point. L1 (lasso) zeroes weights outright and selects features, L2 (ridge) shrinks them all. Its strength is tuned on validation data, never training loss.
- What is the difference between L1 (Lasso) and L2 (Ridge) regularization?
- L1 (lasso) adds the sum of the weights' absolute values to the loss and drives some weights exactly to zero. L2 (ridge, also called weight decay) adds the sum of their squares and shrinks every weight without zeroing any.
- Can we use L1 regularization for feature selection?
- Yes, because the nature of L1 regularization will lead to sparse coefficients of features. Feature selection can be done by keeping only features with non-zero coefficients.
- What is Elastic net regularization?
- A regularization that adds both the L1 (lasso) and L2 (ridge) penalties to the loss, so one linear model gets both: L1 sets some weights to zero and L2 keeps that selection stable when features are correlated.
- Which regularization would you use if your model is underfitting?
- None: regularization fights overfitting, and adding it to an underfitting model makes things worse. If the model is already regularized, weaken or remove it, and add capacity or better features.
- What is early stopping?
- A method for regularization that involves ending model training before training loss finishes decreasing. In early stopping, you end model training when the loss on a validation dataset starts to increase.
Classification metrics13 questions
Start from the confusion matrix and the rest follows: precision, recall and F1 trade false positives against false negatives, ROC and precision-recall curves sweep the decision threshold, and log loss, the Brier score and calibration curves judge the predicted probabilities. Cohen's kappa and the Matthews correlation coefficient score 0 for a classifier no better than chance, so a skewed class balance flatters them less than accuracy.
- What is a confusion matrix?
- A table that shows how a classifier's predicted classes compare with the actual classes. For binary classification it is a 2x2 grid of true positives, false positives, true negatives and false negatives; with k classes it is a k × k grid with correct predictions on the diagonal.
- Should a confusion matrix be used for supervised or unsupervised learning problems?
- Supervised, specifically classification: it compares predicted classes with true labels.
- Accuracy, Precision, Recall, F1 score, ... are metrics to evaluate which types of models?
- Classification models.
- What is the difference between precision and recall?
- Precision is the share of predicted positives that are correct, TP / (TP + FP). Recall is the share of actual positives the model finds, TP / (TP + FN).
- What is the F1 score?
- The harmonic mean of precision and recall: F1 = 2 · precision · recall / (precision + recall). It runs from 0 to 1, where 1 is best, and accuracy plays no part in it.
- What is the difference between sensitivity and specificity?
- Sensitivity is the share of actual positives a test catches, TP / (TP + FN), the same as recall. Specificity is the share of actual negatives it correctly clears, TN / (TN + FP). Moving the decision threshold trades one for the other.
- What is the precision-recall curve?
- A precision-recall curve (or PR Curve) is a plot of the precision (y-axis) and the recall (x-axis) for different probability thresholds.
- What is log loss?
- The average negative log of the probability the model gave to the true class: −(1/N) Σ [yᵢ log pᵢ + (1 − yᵢ) log(1 − pᵢ)] for binary labels. It rewards confident correct predictions and punishes confident wrong ones heavily.
- What is the Brier score?
- The mean squared difference between predicted probabilities and actual outcomes coded as 0 or 1: (1/N) Σ (pᵢ − yᵢ)². Lower is better: 0 is perfect, and always predicting 0.5 scores 0.25.
- What does it mean for a classifier to be well calibrated?
- Its predicted probabilities match observed frequencies: of all the cases it scores 0.8, about 80% turn out positive. A calibration curve, or reliability diagram, plots the observed positive rate against the predicted probability; a calibrated model follows the diagonal.
- What is Cohen's kappa?
- A measure of agreement between two raters, or between a classifier and the truth, that corrects for agreement expected by chance: κ = (p_o − p_e) / (1 − p_e). A value of 1 is perfect agreement and 0 is what chance alone would give.
- What is the Matthews correlation coefficient?
- A single score for a binary classifier that uses all four cells of the confusion matrix: MCC = (TP·TN − FP·FN) / √((TP+FP)(TP+FN)(TN+FP)(TN+FN)). It runs from −1 to 1, with 0 for random guessing, and stays honest on imbalanced data.
Losses and regression metrics7 questions
Regression models are scored with errors like MSE, MAE and R-squared, or with percentage errors such as MAPE and WAPE when series differ in scale. The loss you train on can differ from the metric you report: Huber loss resists outliers, pinball loss predicts a quantile, and hinge loss trains support vector machines. NDCG scores a ranked list.
- Mean Squared Error, Root Mean Squared Error, Mean Absolute Error, R-squared are metrics for evaluation which type of models?
- Regression models.
- What is MAPE?
- Mean absolute percentage error: the average of |actual − forecast| / |actual|, as a percentage. It is easy to explain, but it is undefined when an actual value is 0, explodes near 0, and penalizes over-forecasts more than under-forecasts.
- What is WAPE?
- Weighted absolute percentage error: total absolute error divided by total actual volume, Σ|actual − forecast| / Σ|actual|. Unlike MAPE it doesn't blow up on small or zero actuals, because each error counts in proportion to volume.
- What is Huber loss?
- A regression loss that is squared for small errors and linear for large ones, with a threshold δ between the two. It behaves like squared error near zero and like absolute error for outliers, so a few extreme points can't dominate the fit.
- What is pinball loss?
- The loss used to predict a quantile instead of a mean: for quantile τ, an under-prediction costs τ × error and an over-prediction costs (1 − τ) × error. Minimizing it with τ = 0.9 gives a forecast that actual values fall below 90% of the time.
- What is hinge loss?
- The loss behind support vector machines: max(0, 1 − y·f(x)) with labels y = ±1 and raw score f(x). It is zero for points on the correct side of the margin and grows linearly as a point moves into the margin or past the boundary.
- What is NDCG?
- Normalized discounted cumulative gain, a ranking metric: add up each result's relevance, discounted by the log of its position, then divide by the same sum for the ideal ordering. It runs from 0 to 1 and rewards putting the most relevant items at the top.
Features, data and validation12 questions
A model only sees what its features give it. These cards cover encoding categorical values (one-hot, count and target encoding), bucketing, dense versus sparse features, turning text into features with bag of words and TF-IDF, rebalancing classes, and the leakage traps in building a vocabulary and cross-validating a time series.
- What is one hot encoding?
- Encoding a categorical feature as one binary column per category: each row gets a 1 in the column for its own category and 0 in all the others, so every encoded vector is sparse with exactly one 1.
- What is count encoding?
- Count encoding replaces each categorical value with the number of times it appears in the dataset.
- What is target encoding?
- Target encoding replaces a categorical value with the average value of the target for that value of the feature.
- Explain what bucketing is.
- Converting a (usually continuous) feature into multiple binary features called buckets or bins, typically based on value range.
- What is the difference between a dense and a sparse feature?
- A dense feature is one in which most values are non-zero in contrast with a sparse one where most values are zeros or empty.
- What is bag of words?
- Bag of Words is a representation of text that describes the occurrence of words within a document.
- What is TF-IDF?
- TF-IDF weights a word in a document by its term frequency (how often it appears there) times its inverse document frequency, log(N / df), which is high for words few documents contain. Words frequent in one document but rare across the corpus score highest.
- When building your vocabulary, is it OK to use the tokens from the entire dataset to shrink your out-of-vocabulary list?
- False. Build the vocabulary from the training split only (or from an external corpus, such as a pretrained model's vocabulary); tokens seen only in validation or test data map to UNK, or are split into known subword pieces by a subword tokenizer.
- What is downsampling in the context of class-imbalanced dataset?
- Training on a disproportionately low percentage of over-represented class examples in order to improve model training on under-represented classes.
- What is data leakage?
- When information from outside the training dataset is used to create the model. For example, including any information from the validation or test sets into the model.
- What is a time series?
- A time series is a set of observations ordered in time usually collected at regular intervals.
- Would you use k-fold cross validation on time series data? Explain.
- Not standard shuffled k-fold: time series rows are ordered and autocorrelated, so random folds train on the future to predict the past. Use time-ordered splits instead, such as walk-forward validation (scikit-learn's TimeSeriesSplit).
About · Quizzes · History of AI · To suggest new questions or report an error send me a dm.