15 selected classical machine learning interview questions grouped by seniority level. Use them to review fundamentals, practical trade-offs, and senior-level production reasoning.
1How do linear and logistic regression differ in output interpretation and training objective?
Linear regression uses a linear predictor xᵀbeta for a continuous response, commonly interpreted as a conditional mean, and ordinary least squares minimizes squared residuals. Under independent constant-variance Gaussian errors, this is also maximum likelihood. Binary logistic regression uses the same kind of linear score but maps it through the sigmoid to a probability in (0,1); equivalently the log-odds are linear in features. It is usually fit by minimizing binary cross-entropy, the negative Bernoulli log-likelihood. Turning that probability into a class requires a threshold chosen for the application's costs, not necessarily 0.5. Both can use transformed input features and regularization, so 'linear' describes the predictor in its coefficients rather than requiring only raw straight-line effects. Logistic regression is not ordinary least squares followed by a sigmoid; its training objective differs.
2What assumptions does ordinary least squares linear regression make, and how would residual diagnostics reveal assumption violations?
OLS minimizes squared residuals; computing a fit does not require normally distributed errors. For a unique coefficient vector the design matrix must have full column rank, excluding exact linear dependence rather than all predictor correlation. For the usual unbiased linear-model interpretation, assume a correctly specified conditional mean E[y|X] = X beta, equivalently E[epsilon|X] = 0. Homoscedastic, uncorrelated errors give the classical Gauss–Markov efficiency result and standard covariance formula. Conditional normality additionally supports exact finite-sample t/F inference; suitable large-sample or robust methods can work without it under their own assumptions. Fitted residuals are estimates of errors and are generally correlated even when underlying errors are independent. Plot residuals against fitted values for curvature and variance changes, against time for dependence, and use a Q–Q plot for distributional departures. Leverage and Cook's distance flag influential observations. These diagnostics suggest problems but cannot prove exogeneity or rule out omitted confounders.
import numpy as np
import statsmodels.api as sm
np.random.seed(42)
X = np.linspace(1, 10, 50)
# Quadratic underlying pattern creates a linearity violation
y = 2 * X + 0.5 * (X ** 2) + np.random.normal(0, 2, 50)
X_with_const = sm.add_constant(X)
model = sm.OLS(y, X_with_const).fit()
residuals = model.resid
print(f"Mean Residual: {np.mean(residuals):.4f}")
print(f"Curvature in residuals indicates model misspecification.")
3How does logistic regression model binary classification, and what is the role of the sigmoid function?
Logistic regression models binary classification by estimating the posterior class probability $P(Y=1|X)$. To ensure predicted probabilities remain bounded within $(0, 1)$, logistic regression models the log-odds (logit) of the positive class as a linear function of the inputs: $\ln\left(\frac{p}{1-p}\right) = w^T x + b$. The sigmoid (logistic) function, $\sigma(z) = \frac{1}{1 + e^{-z}}$, serves as the link function that maps any real-valued linear score $z = w^T x + b \in (-\infty, +\infty)$ monotonically into a valid probability $p \in (0, 1)$. Discrete class decisions are made by applying a decision threshold $\tau$ (typically 0.5): $\hat{y} = 1$ if $P(Y=1|X) \ge \tau$, otherwise $0$. Because $\sigma(z) = 0.5$ occurs precisely when $z = 0$, the decision boundary in feature space is the linear hyperplane $w^T x + b = 0$, making standard logistic regression a linear classifier.
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
w = np.array([1.5, -2.0])
b = 0.5
x = np.array([2.0, 1.0])
z = np.dot(w, x) + b
prob = sigmoid(z)
threshold = 0.5
pred = int(prob >= threshold)
print(f"Log-odds (z): {z:.2f}")
print(f"Probability: {prob:.4f}")
print(f"Class Prediction: {pred}")
4What is L2 regularization, and how does Ridge regression change the objective and coefficient estimates?
L2 regularization (Ridge regression) adds a penalty proportional to the sum of squared weights to the ordinary least squares (OLS) loss function: $$\min_w \|y - Xw\|_2^2 + \lambda \|w\|_2^2$$ Analytically, Ridge modifies the normal equations by adding $\lambda I$ to the gram matrix before inversion: $$w_{\text{ridge}} = (X^T X + \lambda I)^{-1} X^T y$$ Key impacts on the objective and coefficient estimates: 1. Shrinkage: Coefficients are shrunk toward zero in proportion to feature variance and correlation, reducing model complexity without forcing them to exact zero. 2. Multicollinearity and Invertibility: When features are collinear or $p > N$, $X^T X$ is singular or ill-conditioned. For $\lambda > 0$, adding $\lambda I$ ensures $(X^T X + \lambda I)$ is strictly positive definite and invertible, stabilizing parameter estimates. 3. Bias-Variance Trade-off: Increasing $\lambda$ introduces intentional bias into coefficient estimates while reducing variance under the usual fixed-design model; the net predictive benefit depends on the problem and penalty strength, so select it using validation. 4. Feature Scaling Requirement: Because the penalty treats all weights equally, a feature with larger numerical scale can produce the same effect with a smaller, less-penalized coefficient. Standardization is usually useful for comparable penalties, but is a modeling choice rather than a mathematical requirement. Fit scaling only on training folds and usually leave the intercept unpenalized.
import numpy as np
def ridge_regression(X, y, alpha):
X_std = (X - np.mean(X, axis=0)) / np.std(X, axis=0)
n_features = X_std.shape[1]
I = np.eye(n_features)
beta = np.linalg.inv(X_std.T @ X_std + alpha * I) @ X_std.T @ y
return beta
X = np.array([[1.0, 2.0], [2.0, 4.1], [3.0, 5.9], [4.0, 8.2]])
y = np.array([2.1, 4.0, 6.2, 8.1])
weights = ridge_regression(X, y, alpha=1.0)
print('Ridge Weights:', weights)
5How does a decision tree recursively partition feature space, and what criteria are used to choose classification splits?
A decision tree partitions feature space through a top-down, greedy algorithm called **recursive binary partitioning**. Starting at the root node with all training data, the algorithm searches over all features and possible threshold values to find the single axis-aligned split ($X_j \le t$) that maximizes the reduction in impurity. The dataset is split into two child nodes, and this procedure is applied recursively on each child node until a stopping criterion (e.g., maximum depth, minimum samples per leaf, or pure nodes) is reached. Because splits evaluate one feature at a time against a threshold, the resulting decision boundaries are orthogonal hyperplanes (axis-aligned rectangular regions in feature space). To evaluate and select the best split in classification trees, two main impurity criteria are used: 1. **Gini Impurity (used in CART)**: Measures the probability that a randomly chosen sample would be misclassified if labeled randomly according to the node's class distribution. For $K$ classes with proportions $p_k$: $$I_G = 1 - \sum_{k=1}^K p_k^2$$ 2. **Entropy and Information Gain (used in ID3, C4.5)**: Entropy measures the uncertainty in a node: $H = -\sum_{k=1}^K p_k \log_2(p_k)$. The split is chosen to maximize **Information Gain**, which is the parent node's entropy minus the weighted average entropy of the child nodes: $$IG = H(\text{parent}) - \sum_{c \in \{\text{left, right}\}} \frac{N_c}{N} H(c)$$ Both metrics reach 0 when a node is completely pure (all samples belong to a single class) and reach their maximum when classes are equally distributed.
6What is k-nearest neighbors, and how does it make predictions for classification and regression?
k-Nearest Neighbors (kNN) is a non-parametric, instance-based (lazy) supervised learning algorithm. It does not train an explicit parametric model; instead, it stores the training dataset and performs all computations during inference. Prediction Workflow: 1. Distance Calculation: When a query instance is evaluated, the algorithm computes its distance to all stored training instances using a specified metric (such as Euclidean, Manhattan, or Minkowski distance). 2. Neighbor Selection: It selects the $k$ training instances with the smallest distances to the query instance. 3. Aggregation: - Classification: It assigns the class via majority vote (mode) among the $k$ neighbors (or distance-weighted vote). - Regression: It predicts the continuous target by taking the local average (mean or median) of the $k$ neighbors' target values (or distance-weighted average). Because distance calculations depend directly on feature scales, feature normalization or standardization is essential to prevent large-magnitude features from dominating distance calculations.
7State the naive Bayes conditional independence assumption and explain why naive Bayes can still work well when it is violated.
The naive Bayes conditional independence assumption states that, given the class label Y = y, all features X_1, X_2, ..., X_d are mutually independent: P(X_1, ..., X_d | Y = y) = \prod_{j=1}^d P(X_j | Y = y). Using Bayes' theorem, the posterior probability is: P(Y = y | X) \propto P(Y = y) \prod_{j=1}^d P(X_j | Y = y), where P(Y = y) is the class prior and P(X_j | Y = y) is the class-conditional likelihood (e.g., Gaussian for continuous features, Multinomial for counts). Naive Bayes often works well in practice despite independence violations because classification relies on the argmax decision rule (argmax_y P(Y=y | X)) rather than accurate probability calibration. Even if feature correlations cause predicted probabilities to become overconfident or distorted, the correct class often retains the highest relative ranking. As long as the correlation does not flip the ranking of class likelihoods, the 0-1 classification decision remains accurate.
from sklearn.naive_bayes import GaussianNB
import numpy as np
X = np.array([[1.0, 1.1], [1.2, 0.9], [-1.0, -1.2], [-0.8, -1.1]])
y = np.array([1, 1, 0, 0])
model = GaussianNB()
model.fit(X, y)
# Prediction uses argmax over class posterior scores
print("Predicted class:", model.predict([[1.1, 1.0]]))
8Implement the main steps of k-means without calling a clustering library.
Choose k initial centroids. Assign each point to the centroid with the smallest squared Euclidean distance. Replace each centroid by the mean of its assigned points, with an explicit rule such as reseeding an empty cluster. Repeat until assignments or centroids stabilize, or until the iteration cap. Keep the run with lowest within-cluster squared error across several starts if needed.
9What does changing the kernel in an SVM change about the model, and how would you choose one?
An SVM kernel computes an inner product in an implicit feature space, changing the similarity geometry in which a maximum-margin separator is learned. A linear kernel gives a linear boundary in the supplied features; a polynomial kernel includes controlled interactions, and an RBF kernel can form flexible nonlinear boundaries with locality governed by gamma. The regularization parameter C and kernel parameters jointly control fit and generalization, so kernel choice cannot be evaluated in isolation. I would scale appropriate numeric features using training-only statistics, compare a strong linear baseline with justified nonlinear alternatives, and tune inside a validation scheme matching deployment. I would examine held-out accuracy or task cost, calibration if probabilities are needed, support-vector count, prediction latency and training memory/time. A flexible kernel can overfit scarce or noisy data, while a linear model may be adequate for high-dimensional sparse text.
10How do bagging and boosting build ensembles differently, and what does each tend to address?
Bagging trains base learners on resampled datasets, commonly bootstrap samples, and combines their predictions by averaging or voting. Training can largely run in parallel. It especially helps unstable high-variance learners; the reduction depends on prediction errors not being perfectly correlated. Random forests add feature randomness to further diversify trees. Boosting builds an additive ensemble sequentially, choosing each learner based on the current ensemble's shortcomings: AdaBoost reweights examples, while gradient boosting follows the loss gradient. It often reduces bias by combining weak learners into a flexible model, but can also affect variance and is not immune to overfitting or noisy labels. I would tune learning rate, number and depth of learners, sampling and early stopping. The distinction is how learners are constructed and combined, not a universal claim that bagging only fixes variance or boosting always wins.
11How do LDA and PCA differ when used to reduce the dimension of labeled data?
PCA finds orthogonal directions of maximum total variance in centered features without using labels. Its leading components can preserve reconstruction information while discarding a low-variance direction that is highly predictive of class. Linear discriminant analysis as a dimensionality reducer uses labels to maximize between-class separation relative to within-class scatter. With C classes it provides at most C−1 discriminant dimensions, also limited by feature rank. Its classical probabilistic form assumes class-conditional Gaussian distributions with shared covariance, and high-dimensional covariance estimates may need regularization. I would fit either transformation using training data only, with scaling and tuning inside validation folds, then compare downstream performance. LDA is not automatically better because labels are available: noisy labels, nonlinear boundaries or poor covariance estimation can hurt it. Here LDA means linear discriminant analysis, not latent Dirichlet allocation.
12What is the difference between Ridge regression, Principal Component Regression, and Partial Least Squares at a high level?
Ridge Regression, Principal Component Regression (PCR), and Partial Least Squares (PLS) are three linear techniques used to handle multicollinearity and high dimensionality, but they differ in how they reduce variance and whether reduction is continuous or supervised: 1. Ridge Regression: Retains all original $p$ features and applies continuous shrinkage to coefficient magnitudes via an L2 penalty. It does not construct lower-dimensional latent components or discard feature dimensions; rather, it shrinks the variance along low-eigenvalue directions of $X^T X$. 2. Principal Component Regression (PCR): A two-step, unsupervised dimensionality reduction method. It first applies Principal Component Analysis (PCA) strictly to the predictor matrix $X$ to find orthogonal directions of maximal variance, keeps the top $k$ principal components, and fits an OLS regression on those $k$ components. Because PCA ignores the target variable $y$, PCR risks discarding components that have low variance in $X$ but high predictive power for $y$. 3. Partial Least Squares (PLS): A supervised dimensionality reduction method. It constructs $k$ orthogonal latent components by finding linear combinations of $X$ that maximize the covariance between $X$ and the response $y$. By explicitly incorporating target information, PLS identifies components that explain both feature variance and response variation.
from sklearn.linear_model import Ridge, LinearRegression
from sklearn.decomposition import PCA
from sklearn.cross_decomposition import PLSRegression
from sklearn.pipeline import make_pipeline
# 1. Ridge: Regularized full feature space
ridge = Ridge(alpha=1.0)
# 2. PCR: Unsupervised PCA followed by OLS
pcr = make_pipeline(PCA(n_components=2), LinearRegression())
# 3. PLS: Supervised latent component projection and regression
pls = PLSRegression(n_components=2)
13How do modern gradient boosting implementations such as XGBoost, LightGBM, and CatBoost optimize training or handle tabular features differently?
Modern GBDT frameworks differ substantially in their split-finding algorithms, tree growth strategies, and tabular/categorical feature handling: 1. XGBoost: Traditionally relies on exact greedy or approximate quantile sketch split-finding (and later Fast Hist), uses level-wise (depth-wise) tree growth, and handles missing values by learning an optimal default branch direction during split search. 2. LightGBM: Uses histogram-based split-finding (binning continuous features into discrete buckets, typically 256), leaf-wise (best-first) tree growth for faster loss reduction, Gradient-based One-Side Sampling (GOSS) to keep large-gradient instances while subsampling small-gradient ones, and Exclusive Feature Bundling (EFB) to merge mutually exclusive sparse features. For categorical variables, it finds optimal splits by sorting categorical histogram bins ($O(K \log K)$). 3. CatBoost: Uses oblivious (symmetric) decision trees where all nodes at a given depth share the exact same split, enabling fast vectorized CPU/GPU scoring. Its primary innovation is Ordered Target Statistics and ordered boosting, which computes target statistics over random permutations of training data to prevent target leakage and prediction shift.
14How would you decide whether a custom loss is appropriate for a gradient boosting model under asymmetric business costs?
Deciding whether to implement a custom loss function in gradient boosting under asymmetric business costs requires evaluating whether the asymmetry can be handled downstream via probability calibration and threshold tuning, or whether it fundamentally alters the optimization landscape during tree induction: 1. Threshold Tuning vs Custom Loss: For classification tasks with asymmetric error costs (e.g., false negatives costing $10\times$ false positives), standard cross-entropy is a proper scoring rule that aims to estimate posterior probabilities $P(y=1|x)$, but calibration should be checked and, if needed, corrected on validation data. Shifting the classification decision threshold based on business cost matrix $\tau = \frac{C_{FP}}{C_{FP} + C_{FN}}$ or applying sample weights is often cleaner and avoids custom derivatives. However, for asymmetric regression (e.g., asymmetric pinball loss for inventory demand) or non-linear business penalties where standard objectives cannot guide split finding, a custom loss is warranted. 2. Mathematical Requirements for GBDT: In second-order boosters (XGBoost, LightGBM), a custom loss $L(y, \hat{y})$ normally needs computable first-order gradients ($g_i = \partial L / \partial \hat{y}_i$) and valid second-order curvature/Hessian values ($h_i = \partial^2 L / \partial \hat{y}_i^2$) for split gain and leaf-weight calculations ($w^* = -\sum g_i / (\sum h_i + \lambda)$). Hessians should be non-negative or safely approximated/clipped for numerical stability; some implementations support first-order or approximate objectives, so the requirement is framework-specific. Non-differentiable or discontinuous business metrics should be replaced with smooth surrogate approximations (e.g., Huberized or log-cosh variants).
import numpy as np
import xgboost as xgb
def asymmetric_mse_objective(preds, dtrain):
labels = dtrain.get_label()
residual = preds - labels
# Penalize underestimation (residual < 0) 5x more heavily than overestimation
penalty = np.where(residual < 0, 5.0, 1.0)
grad = 2.0 * penalty * residual
hess = 2.0 * penalty
return grad, hess
# Usage:
# model = xgb.train(params, dtrain, obj=asymmetric_mse_objective)
15What is LambdaMART, and how does it adapt gradient boosting for learning-to-rank objectives?
LambdaMART combines gradient-boosted regression trees with LambdaRank's metric-weighted pairwise updates. For documents i and j within the same query where i is more relevant, use the logistic pair loss log(1 + exp(-sigma * (s_i - s_j))). Let a_ij = sigma * abs(Delta NDCG_ij) / (1 + exp(sigma * (s_i - s_j))). Under a negative-gradient convention, this pair contributes +a_ij to document i and -a_ij to document j, pushing the preferred item upward. Sum these signed contributions over the selected pairs for each document, then fit boosting updates, often using corresponding curvature estimates for leaf values. Delta NDCG measures the metric change from swapping their current rank positions. This creates a surrogate signal aligned with ranking quality; it is not an ordinary derivative of the discrete NDCG function and does not guarantee a global metric optimum. Keep query groups intact in training and evaluation; pair sampling, metric truncation and zero-gain cases depend on the implementation.
import lightgbm as lgb
import numpy as np
# Simulated query-grouped data: 2 queries with 3 docs each
X = np.random.randn(6, 10)
y = np.array([3, 1, 0, 2, 0, 1]) # Relevance grades (0-3)
group = [3, 3] # Query group sizes
train_data = lgb.Dataset(X, label=y, group=group)
params = {
'objective': 'lambdarank',
'metric': 'ndcg',
'ndcg_eval_at': [1, 3],
'learning_rate': 0.1,
'n_estimators': 50
}
ranker = lgb.train(params, train_data)