Skip to content
E
Educatum
ML Fundamentals

Classic Machine Learning Interview Questions

Strong fundamentals remain the fastest filter in machine learning phone screens and onsite loops. This bank of 103 classic machine learning interview questions spans statistical foundations, probability distributions, linear and tree-based models, optimization algorithms such as Adam and SGD, overfitting controls, dimensionality reduction, and core neural network mechanics. Use the direct answers to test yourself aloud before diving into the worked examples.

103Study Cards
6Categories
Updated:
103 / 103
Category:
01Basic Concepts

What is density estimation in ML?

Density estimation is the unsupervised task of estimating the underlying probability density function (PDF) of a dataset from observed samples. Parametric approaches fit fixed-form distributions such as Gaussians or Gaussian Mixture Models, whereas non-parametric methods such as histograms and Kernel Density Estimation infer smooth densities directly from local sample concentrations. It underpins anomaly detection, Bayesian inference, and probabilistic generative modeling.

02Basic Concepts

K-means vs Gaussian Mixture Models (GMM)

K-means partitions data into non-overlapping clusters using hard assignments based on Euclidean distance to centroids, implicitly assuming spherical clusters of similar variance. Gaussian Mixture Models (GMMs) model data as a mixture of multivariate Gaussian distributions via Expectation-Maximization, providing soft probabilistic assignments and full covariance matrices to capture elliptical clusters of varying sizes and orientations.

03Basic Concepts

What is underfitting and overfitting?

Underfitting happens when a model lacks the capacity to learn the underlying data structure, causing high error on both training and validation sets (high bias). Overfitting happens when an overly flexible model memorizes noise and training-set quirks, producing near-zero training error alongside poor generalization on unseen test data (high variance). Good machine learning practice balances model complexity, regularization, and data size to hit the validation-error minimum between these regimes.

04Basic Concepts

How does KNN classification work?

k-Nearest Neighbors (k-NN) classification is a non-parametric, instance-based algorithm that stores labeled training data without learning parametric weights. To classify a query point, it computes distances to training samples, selects the k closest neighbors, and predicts the majority (or inverse-distance-weighted) class label.

05Basic Concepts

How to avoid overfitting?

Overfitting happens when a model memorizes training noise and sample-specific quirks rather than generalizable patterns, causing strong training scores alongside poor test accuracy. Key defenses include collecting more diverse data, applying data augmentation, reducing model complexity, adding L1/L2 regularization or dropout, using early stopping on a validation set, and combining models via ensembles.

06Basic Concepts

Effect of k on variance and bias in KNN

In k-Nearest Neighbors (k-NN), the neighborhood size k acts inversely to model complexity. A small k yields low bias and high variance because predictions closely follow individual noisy training points (overfitting), while a larger k averages over broader neighborhoods to reduce variance at the expense of higher bias and smoother decision boundaries (underfitting).

07Basic Concepts

Why does decision tree have high variance?

Decision trees have high variance because small perturbations in the training data can trigger different greedy splits near the root, cascading into radically different tree structures and predictions. Unconstrained trees partition feature space down to tiny, near-pure leaf subsets that memorize noise and local outliers. Variance is typically controlled by limiting tree depth and leaf size, pruning branches, or averaging many decorrelated trees via bagging and Random Forests.

08Basic Concepts

How to choose number of features in random forest?

The max_features hyperparameter controls how many random features are evaluated at each node split in a Random Forest, governing the tradeoff between individual-tree bias and inter-tree correlation. Standard heuristics are sqrt(p) for classification and p/3 for regression, while tuning via cross-validation or Out-of-Bag (OOB) error identifies the optimal dataset-specific value.

09Basic Concepts

RMSprop Optimizer

RMSprop (Root Mean Square Propagation) is an adaptive gradient-based optimizer that normalizes each parameter's update by the root of an exponentially weighted moving average (EWMA) of its squared gradients. Unlike AdaGrad, whose monotonically growing gradient accumulation prematurely shrinks learning rates toward zero, RMSprop's moving average forgets distant history, dampening oscillations in steep directions while sustaining progress along flatter dimensions.

10Basic Concepts

What is batch normalization?

Batch Normalization standardizes each layer's pre-activations or activations across the current mini-batch to zero mean and unit variance, then applies learned per-channel scale (gamma) and shift (beta) parameters. Originally proposed to reduce internal covariate shift, subsequent research showed its main benefit comes from smoothing the optimization landscape so higher learning rates train reliably. During inference, it uses fixed exponential moving averages of training mean and variance rather than batch statistics.

11Basic Concepts

Effects of feature scaling on logistic regression

Feature scaling does not alter the optimal decision boundary of unregularized logistic regression once converged, because weights rescale inversely with feature units. However, scaling dramatically improves gradient-based optimization convergence by conditioning the Hessian, and it is strictly essential whenever L1 or L2 regularization is applied so large-weight penalties treat all features fairly.

12Basic Concepts

Bias of linear regression

Under classical Gauss-Markov assumptions where the true relationship is linear and correctly specified, ordinary least squares (OLS) is statistically unbiased. However, linear regression carries strong inductive bias by restricting hypotheses to linear hyperplanes, causing high approximation bias and systematic underfitting whenever the true target function is non-linear or omits key interaction terms.

13Basic Concepts

Stochastic Gradient Descent (SGD)

Stochastic Gradient Descent (SGD) optimizes model parameters using noisy gradient estimates computed from a single training sample or a small mini-batch rather than the entire dataset. This lowers per-step computation from O(m) to O(batch_size), enables out-of-core streaming on massive datasets, and introduces stochastic noise that can help escape shallow saddle points or sharp local minima when paired with shuffling and learning rate decay.

14Basic Concepts

How does Cross Validation work?

Cross-validation evaluates generalization by partitioning training data into k disjoint folds, iteratively fitting the model (and any preprocessing steps) on k-1 folds while validating on the remaining fold, and averaging performance across all k splits. Using stratified folds for classification and wrapping scalers inside a pipeline prevents validation variance and data leakage.

15Basic Concepts

Bagging VS boosting

Bagging and boosting are ensemble methods that combine multiple base models into a stronger predictor, but they target opposite sources of error. Bagging trains low-bias, high-variance learners independently in parallel on bootstrapped subsets and averages their outputs to reduce variance, whereas boosting trains weak learners sequentially—each correcting errors or residuals from earlier models—to primarily reduce bias.

16Basic Concepts

Linear Support Vector Machine (SVM)

A Linear Support Vector Machine (SVM) is a supervised classification algorithm that finds the linear hyperplane maximizing the geometric margin between classes. For data that is not strictly linearly separable, a soft-margin Linear SVM introduces slack variables and a regularization parameter C to balance margin width against margin violations and misclassifications.

17Basic Concepts

Random forest VS Adaboost

Random Forest and AdaBoost are both tree-based ensemble methods, but they follow opposite strategies. Random Forest trains deep decision trees independently in parallel via bagging and feature subsampling to reduce variance, whereas AdaBoost trains shallow learners (typically decision stumps) sequentially while reweighting misclassified examples to reduce bias.

18Basic Concepts

What is relative entropy?

Relative entropy, commonly known as Kullback-Leibler (KL) divergence, quantifies how one probability distribution Q diverges from a reference distribution P, measuring the extra expected bits or nats required when coding samples from P using Q. KL divergence is always non-negative and equals zero if and only if P and Q match almost everywhere, but it is asymmetric and diverges to infinity whenever Q assigns zero probability to an event with positive probability under P. It links cross-entropy to entropy and underpins variational inference, VAEs, and policy-gradient regularization.

19Basic Concepts

ReLU (Rectified Linear Unit)

ReLU (Rectified Linear Unit) is a piecewise-linear activation function defined as f(x) = max(0, x), passing positive inputs unchanged and clamping negative inputs to zero. Its constant derivative of 1 for positive values preserves gradient flow and speeds up training compared to sigmoid or tanh, though units can suffer from the dying ReLU problem when pre-activations stay persistently negative.

20Basic Concepts

What is Inception-ResNet-V2?

Inception-ResNet-v2 is a deep convolutional neural network from Google Research that merges multi-branch Inception modules with ResNet-style identity skip connections. By combining factorized, computationally cheaper Inception blocks, Batch Normalization on convolutional layers, and scaled residual additions, it trains much faster and avoids optimization degradation in very deep networks. Upon release in 2016, it achieved state-of-the-art ImageNet accuracy and remains a widely used vision backbone.

21Basic Concepts

Precision, recall and F1 score

Precision, recall, and F1 score evaluate classification performance beyond raw accuracy, particularly on imbalanced datasets. Precision measures the fraction of predicted positives that are truly positive, recall measures the fraction of actual positives successfully detected, and the F1 score takes their harmonic mean to penalize extreme imbalance between the two.

22Basic Concepts

What is U-Net?

U-Net is a fully convolutional encoder-decoder architecture originally built for biomedical semantic segmentation that pairs a downsampling contracting path with a symmetric upsampling expansive path. At each resolution stage, skip connections concatenate high-resolution encoder feature maps directly onto the corresponding decoder maps, combining coarse semantic context with sharp spatial boundaries. Its efficiency and strong inductive bias make it effective even with limited annotated data, as well as a standard backbone in diffusion models.

23Basic Concepts

Can logistic regression handle unbalanced classes?

Logistic regression can handle imbalanced classes, though using the default 0.5 probability threshold often causes low recall on the minority class. Adjusting the decision threshold, applying class weighting (class_weight='balanced'), or resampling training folds restores minority detection, though weighting and resampling shift predicted probabilities away from true base rates.

24Basic Concepts

Choosing k in k-means Clustering

Selecting the optimal number of clusters k in k-means balances intra-cluster compactness against inter-cluster separation because raw within-cluster variance decreases monotonically as k grows. Common empirical techniques include the Elbow method on WCSS, Silhouette analysis (defined for k >= 2), and the Gap statistic, complemented by downstream domain constraints.

25Basic Concepts

Why doesn't MSE work with logistic regression?

Mean Squared Error (MSE) is poorly suited for logistic regression for two fundamental optimization reasons: non-convexity and vanishing gradients. Composing the non-linear sigmoid function with squared error produces a non-convex loss landscape with flat plateaus and local minima, whereas Binary Cross-Entropy (Log Loss) is convex in the weights. Furthermore, MSE's gradient includes the sigmoid derivative y_hat(1 - y_hat), which approaches zero precisely when predictions are confidently wrong, stalling gradient descent.

26Basic Concepts

Pros and Cons of Random Forest

Random Forest excels on tabular data by combining bootstrap aggregation and random feature subsampling to drastically reduce decision tree variance while resisting overfitting and outliers. Its main drawbacks are larger memory footprints, slower inference across many trees, reduced interpretability, biased impurity-based feature importances toward high-cardinality features, and an inability to extrapolate beyond training target bounds.

27Basic Concepts

What is t-SNE (t-distributed Stochastic Neighbor Embedding)

t-SNE (t-distributed Stochastic Neighbor Embedding) is a non-linear dimensionality reduction technique built primarily for visualizing high-dimensional datasets in 2D or 3D. It converts pairwise high-dimensional distances into Gaussian neighbor probabilities and matches them in low dimensions using a heavy-tailed Student-t distribution by minimizing KL divergence, preserving local neighborhoods while avoiding crowding. Because t-SNE optimizes a non-convex objective focused on local structure, cluster sizes and distances between distant clusters should not be interpreted literally.

28Basic Concepts

What is Inception Network in Deep Learning?

The Inception network (originally introduced as GoogLeNet / Inception-v1) is a deep CNN architecture built around parallel multi-scale Inception modules instead of uniform sequential convolutions. Each module runs 1x1, 3x3, and 5x5 convolutions alongside a 3x3 max-pooling branch, using 1x1 bottleneck convolutions to compress channel dimensionality before expensive spatial filters and concatenating all branch outputs. Combined with Global Average Pooling instead of heavy fully connected layers, Inception achieved high ImageNet accuracy with far fewer parameters than VGG.

29Basic Concepts

Difference between generative and discriminative model

Generative models learn the full joint probability distribution P(X, Y) = P(X|Y)P(Y), enabling them to synthesize new examples and classify via Bayes' theorem. Discriminative models learn the conditional distribution P(Y|X) or a direct decision boundary without modeling the input distribution P(X), often achieving higher predictive accuracy when labeled data is abundant.

30Basic Concepts

Choosing k in k-Nearest Neighbors (k-NN)

Choosing k in k-Nearest Neighbors directly controls the bias-variance tradeoff: small k (such as k = 1) fits local noise with high variance, while overly large k oversmooths decision boundaries and increases bias. Practitioners select k empirically using k-fold cross-validation inside a scaled pipeline, often preferring odd values in binary classification to prevent voting ties.

31Basic Concepts

Intuition of Gradient Boosting

Gradient boosting builds a strong predictive model as an additive sum of shallow trees via functional gradient descent. At each step, instead of adjusting model parameters directly, a new tree is trained to fit the negative gradient (pseudo-residuals) of the loss function with respect to current predictions, stepping toward the minimum scaled by a learning rate.

32Basic Concepts

Supervised vs. Unsupervised Learning

Supervised learning trains models on labeled input-output pairs to predict targets or classify new observations. Unsupervised learning operates on unlabeled inputs without explicit target labels to uncover latent patterns, clusters, low-dimensional manifolds, or anomalies within the data itself.

33Basic Concepts

Steps of Principal Component Analysis (PCA)

Principal Component Analysis (PCA) reduces dimensionality by projecting centered (and typically standardized) data onto orthogonal directions of maximum variance. The core steps are centering and scaling features, computing the covariance matrix, finding its eigenvectors and eigenvalues (or SVD), selecting the top k components by explained variance, and projecting the data onto that subspace.

34Basic Concepts

Logistic regression

Logistic regression is a linear classification algorithm that maps a weighted sum of input features through the sigmoid function to predict probabilities between 0 and 1. Its parameters are learned via Maximum Likelihood Estimation (minimizing binary cross-entropy loss), yielding an interpretable linear decision boundary and log-odds feature weights.

35Basic Concepts

Log Loss

Log loss, also known as binary cross-entropy or logistic loss, evaluates a binary classifier's predicted probabilities against true 0/1 labels. Lower log loss indicates better calibration and accuracy, while confident but wrong predictions incur an exponentially growing penalty that approaches infinity as the predicted probability of the true class approaches zero.

36Basic Concepts

t-SNE VS PCA

PCA is a deterministic linear dimensionality reduction method that preserves global variance and learns an explicit projection matrix for transforming unseen test data in ML pipelines. t-SNE is a stochastic, non-linear visualization technique that preserves local neighborhood similarities in 2D or 3D, but it is non-parametric (cannot directly transform new points) and does not reliably preserve global cluster distances or sizes.

37Basic Concepts

Grid Search vs. Random Search

Grid search exhaustively evaluates every point on a fixed Cartesian grid of hyperparameter values, whereas random search samples a specified budget of combinations from prior distributions. Random search is generally far more sample-efficient in higher dimensions—especially when only a subset of hyperparameters strongly affects validation performance—because every trial tests distinct values along important axes.

38Basic Concepts

Evaluate k means

Evaluating k-means clustering relies primarily on internal metrics that measure intra-cluster compactness and inter-cluster separation without ground-truth labels. Standard internal metrics include Within-Cluster Sum of Squares (WCSS / inertia), Silhouette score, Calinski-Harabasz index, and Davies-Bouldin index; when reference labels exist, external metrics such as Adjusted Rand Index (ARI) and Normalized Mutual Information (NMI) apply.

39Basic Concepts

Importance of feature selection

Feature selection retains the most informative predictors and discards irrelevant or redundant inputs before or during modeling. Doing so reduces overfitting and model variance in high-dimensional datasets, improves human interpretability, lowers training and inference costs, and mitigates multicollinearity.

40Basic Concepts

What is hierarchical clustering?

Hierarchical clustering is an unsupervised learning method that organizes data into a nested tree of clusters without requiring a fixed cluster count up front. It operates either bottom-up (agglomerative, merging closest pairs from individual points) or top-down (divisive, recursively splitting one global cluster), visualizing merges in a dendrogram. While flexible in cluster shape via linkage choice, standard agglomerative clustering requires O(n^2) memory and O(n^2 log n) to O(n^3) time, limiting scale to large datasets.

41Basic Concepts

ROC curve

An ROC curve evaluates a binary classifier across all classification thresholds by plotting True Positive Rate (TPR, recall) against False Positive Rate (FPR). The Area Under the ROC Curve (AUC-ROC) measures pure ranking discrimination—the probability that a randomly selected positive example receives a higher predicted score than a randomly selected negative example.

42Basic Concepts

Methods to Avoid Overfitting

Overfitting occurs when a model memorizes noise and spurious patterns in the training set, leading to poor generalization on unseen data. Common remedies include collecting more diverse data, adding L1/L2 regularization, constraining model capacity (e.g., tree pruning or shallower networks), applying dropout or early stopping, using cross-validation for hyperparameter tuning, and combining models through bagging ensembles.

43Basic Concepts

Machine Learning (ML) vs. Deep Learning (DL)

Machine Learning encompasses algorithms that learn predictive patterns from data, while Deep Learning is a specialized subfield that uses multi-layer neural networks to learn hierarchical feature representations automatically. Traditional ML (such as gradient-boosted trees) often excels on small-to-medium tabular datasets with engineered features, whereas Deep Learning dominates large-scale unstructured data such as images, audio, and natural language.

44Basic Concepts

Feature selection methods

Feature selection identifies the most informative subset of original input features to improve generalization, interpretability, and computational efficiency. Methods fall into three families: filter methods (model-agnostic statistical scores such as ANOVA F-test, chi-squared, or mutual information), wrapper methods (model-in-the-loop search like RFE), and embedded methods (built into training, such as L1/Lasso penalties and tree splits).

45Basic Concepts

Ridge and Lasso

Ridge and Lasso regression regularize linear regression to prevent overfitting by adding norm penalties on the weights. Ridge adds an L2 squared penalty that yields a unique closed-form solution and shrinks correlated weights evenly toward zero, whereas Lasso adds an L1 absolute penalty solved numerically that drives weak coefficients to exact zero for automatic feature selection.

46Basic Concepts

k-means steps

K-means clustering partitions data into k clusters by minimizing the within-cluster sum of squares. After choosing k and initializing k centroids, Lloyd's algorithm alternates between assigning each point to its nearest centroid and recomputing each centroid as the mean of its assigned points until assignments stabilize.

47Basic Concepts

Why is bias used in NN?

A bias term adds a learnable scalar offset to a neuron's weighted sum before applying the non-linear activation function, playing the same role as the intercept in linear regression. Without bias, the pre-activation hyperplane w^T x = 0 must pass through the origin and the zero-input response stays fixed at phi(0) (such as 0.5 for sigmoid). Including bias lets every neuron shift its activation threshold freely, dramatically expanding representational flexibility.

48Basic Concepts

Pros and cons of k-means

K-means clustering is popular because it is simple, fast, and scales linearly in sample count with time complexity O(n * k * d * i). However, it requires specifying k upfront, converges only to local minima sensitive to initialization, struggles with non-convex clusters or varying sizes and densities, and is sensitive to outliers and feature scales.

49Basic Concepts

Optimal k in k means

Selecting the optimal number of clusters k in K-means commonly combines the Elbow Method and Silhouette Analysis. The Elbow Method looks for diminishing returns in within-cluster sum of squares (WCSS) as k grows, while Silhouette Analysis selects the k maximizing average cluster cohesion relative to separation across all data points.

50Basic Concepts

DBSCAN

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) groups points in high-density neighborhoods into clusters of arbitrary shape while labeling isolated points in sparse regions as noise. Using two parameters—neighborhood radius epsilon and minimum point count minPoints—it classifies points as core, border, or noise without requiring the number of clusters k in advance.

51Basic Concepts

Pros and Cons of Tanh Activation Function

The hyperbolic tangent (tanh) activation function maps inputs smoothly to (-1, 1), offering zero-centered outputs and a steeper maximum gradient of 1.0 compared to sigmoid's 0.25. While zero-centering improves optimization dynamics, tanh still saturates for large magnitude inputs, causing vanishing gradients that make ReLU-family activations preferable in deep feedforward networks.

52Basic Concepts

Comparing Two Classifiers: Logistic Regression vs. Support Vector Machines (SVM)

Logistic Regression models conditional class probabilities via the sigmoid function and minimizes binary cross-entropy (log loss), yielding calibrated probabilities and interpretable linear weights. Support Vector Machines minimize hinge loss with an L2 margin penalty to find a maximum-margin hyperplane, supporting non-linear boundaries via kernel functions while requiring Platt scaling for probability estimates.

53Basic Concepts

Explain the two steps of EM algorithm?

Expectation-Maximization (EM) is an iterative algorithm for finding maximum likelihood (or MAP) parameter estimates in statistical models with latent variables or missing data. The E-step computes the posterior distribution over latent variables to form the expected complete-data log-likelihood, and the M-step updates parameters to maximize that expectation, monotonically increasing observed log-likelihood toward a local optimum.

54Basic Concepts

What is leaky ReLU?

Leaky ReLU is a modified Rectified Linear Unit activation function that retains a small positive slope alpha (such as 0.01 or 0.2) for negative inputs instead of outputting zero. By keeping the gradient non-zero everywhere except at zero, it prevents neurons from becoming permanently stuck in an inactive state (the dying ReLU problem). While preserving ReLU's computational speed, it helps stabilize training in architectures prone to dead units, such as GANs or unnormalized deep networks.

55Basic Concepts

Pros and Cons of Linear Regression

Linear regression offers simplicity, high interpretability via direct coefficient weights, low variance, and an exact closed-form Ordinary Least Squares solution. Its primary drawbacks are the assumption of a linear relationship in features, strong sensitivity to outliers under squared error loss, coefficient instability under multicollinearity, and unreliable extrapolation beyond the training range.

56Basic Concepts

Why AUC is a Desirable Metric

AUC (Area Under the ROC Curve) is a desirable classification metric because it evaluates a model's ranking ability across all possible decision thresholds rather than at a single arbitrary cutoff. It equals the probability that a randomly selected positive example receives a higher predicted score than a randomly selected negative example, avoiding accuracy's trap on moderately imbalanced data. However, because ROC-AUC ignores calibration and can look overly optimistic when negatives vastly outnumber positives, Precision-Recall AUC and calibration metrics should complement it.

57Basic Concepts

Count based VS Prediction models for word embeddings

Count-based embedding methods construct word vectors from global corpus co-occurrence statistics using weighting and factorization techniques such as PPMI, truncated SVD, and GloVe's log-bilinear regression. Prediction-based methods like Word2Vec (CBOW and Skip-gram) learn dense embeddings incrementally by predicting target or context words within local sliding windows, scaling cleanly to massive streaming corpora.

58Basic Concepts

Bias and Variance

Bias and variance decompose a model's reducible prediction error into two competing sources. High bias stems from overly simplistic model assumptions that cause underfitting, whereas high variance stems from excessive sensitivity to training sample fluctuations that causes overfitting, making total generalization error lowest at an intermediate model complexity.

59Basic Concepts

How is Naive Bayes classifier naive?

The Naive Bayes classifier is called naive because it assumes every input feature is conditionally independent of all other features given the class label. This strong assumption collapses the joint likelihood into a product of single-feature probabilities, making training extremely fast and data-efficient while still ranking class predictions accurately even when features correlate.

60Basic Concepts

How does KNN regression work?

k-Nearest Neighbors (k-NN) regression is a non-parametric, lazy algorithm that predicts a continuous value by averaging the target values of the k closest training samples in feature space. Predictions can use uniform averages or inverse-distance weighting, producing flexible piecewise-constant approximations that cannot extrapolate beyond the training target range.

61Basic Concepts

Random Forest

Random Forest is an ensemble learning algorithm that aggregates predictions across many decision trees trained independently to improve generalization and stability. It mitigates single-tree overfitting through two sources of randomness: bootstrap sampling of training instances (bagging) and random feature subsampling at every split, which decorrelates trees and lowers ensemble variance.

62Basic Concepts

What is kernel method?

Kernel methods are machine learning algorithms that learn non-linear patterns by implicitly mapping inputs into a high- or infinite-dimensional Reproducing Kernel Hilbert Space (RKHS) using a positive semi-definite kernel function. Via the kernel trick, algorithms evaluate pairwise inner products in the transformed space directly in input space without explicitly computing high-dimensional feature coordinates. Classic examples include kernel Support Vector Machines, Gaussian Processes, Kernel Ridge Regression, and Kernel PCA.

63Basic Concepts

Prior of Lasso and Ridge

From a Bayesian Maximum a Posteriori (MAP) perspective under Gaussian observation noise, Ridge regression assumes a zero-mean Gaussian prior on the weights while Lasso assumes a zero-mean Laplace prior. The Gaussian log-prior produces the quadratic L2 penalty that shrinks coefficients smoothly, whereas the sharp peak of the Laplace prior at zero produces the L1 penalty whose MAP mode drives weak weights to exact zero.

64Basic Concepts

What Makes a Random Forest Random?

A Random Forest introduces randomness in two complementary ways during training: bagging (bootstrap aggregating) and random feature subsampling at each split. Bagging trains each decision tree on a distinct bootstrap sample drawn with replacement from the training set, while split-level feature randomness restricts each node split to a random subset of candidate features (such as sqrt(p) in classification). Together, these mechanisms decorrelate individual low-bias, high-variance trees so averaging their predictions sharply lowers ensemble variance.

65Basic Concepts

Standardization VS Normalization

Standardization (z-score scaling) centers each feature to zero mean and unit variance, while normalization (min-max scaling) rescales features into a fixed interval such as [0, 1]. Standardization is generally preferred for gradient-based models, SVMs, and PCA because it preserves zero-centered distributions and handles moderate outliers better, whereas normalization is useful when bounded inputs like image pixels are explicitly required.

66Basic Concepts

What is EM algorithm?

The Expectation-Maximization (EM) algorithm is an iterative optimization method for finding maximum likelihood (or MAP) parameter estimates in statistical models with latent variables or missing data. It alternates between an E-step, which computes the posterior distribution over latent variables to form the expected complete-data log-likelihood, and an M-step, which maximizes that expectation with respect to the model parameters. By Jensen's inequality, each EM iteration guarantees that the observed-data log-likelihood never decreases.

67Basic Concepts

How does boosting work?

Boosting is a sequential ensemble technique that converts weak learners (such as shallow decision stumps) into an accurate strong learner. Each subsequent model focuses on correcting prior ensemble mistakes—either by increasing weights on misclassified points (AdaBoost) or fitting negative gradients of a loss function (Gradient Boosting)—primarily reducing bias.

68Regularization Techniques

L1 VS L2

L1 (Lasso) and L2 (Ridge) regularization prevent overfitting by adding a weight penalty to the training loss. L1 penalizes the sum of absolute weights and drives irrelevant coefficients to exactly zero for automatic feature selection, whereas L2 penalizes the sum of squared weights to shrink all coefficients smoothly toward zero without eliminating them.

69Regularization Techniques

What is regularization?

Regularization is any technique that constrains a model's effective capacity or training dynamics to prevent overfitting and improve generalization on unseen data. Most classically, it adds a complexity penalty such as L1 (Lasso) or L2 (Ridge) weight norms to the empirical training loss, trading a small increase in bias for a larger reduction in variance. Beyond explicit parameter penalties, regularization encompasses dropout, early stopping, data augmentation, and architectural constraints.

70Basic Concepts

What is GMM?

A Gaussian Mixture Model (GMM) is a probabilistic latent-variable model that represents a data distribution as a convex combination of K multivariate Gaussian components, each with its own weight, mean vector, and covariance matrix. Unlike hard clustering methods such as K-means, GMMs compute soft posterior probabilities assigning every point partially to each cluster and can capture elliptical cluster shapes. Model parameters are typically learned via the Expectation-Maximization (EM) algorithm.

71Basic Concepts

Adam Optimizer

Adam (Adaptive Moment Estimation) is a first-order gradient optimization algorithm that maintains exponential moving averages of both the gradients (first moment, like Momentum) and squared gradients (second raw moment, like RMSProp). By applying bias correction to counter zero initialization in early steps, Adam adapts the effective step size per parameter, converging rapidly on noisy or sparse-gradient problems.

72Basic Concepts

Non-linear SVM

Non-linear Support Vector Machines extend linear SVMs to curved decision boundaries by using kernel functions such as the Radial Basis Function (RBF) or polynomial kernels. Via the kernel trick, the dual optimization computes inner products in a potentially infinite-dimensional feature space implicitly, avoiding explicit coordinate transformations.

73Regularization Techniques

Derivation of Ridge and Lasso Regularization

Ridge and Lasso augment ordinary least squares (OLS) with squared L2 and L1 coefficient penalties, respectively. Setting the Ridge gradient to zero yields a closed-form solution that adds lambda I to X-transpose X, ensuring invertibility; Lasso's non-differentiable L1 penalty is solved via subdifferential KKT conditions and coordinate descent, producing soft-thresholding that zeroes small coefficients.

74Basic Concepts

What is ResNet?

ResNet (Residual Neural Network) is a deep learning architecture introduced in 2015 that adds identity skip connections bypassing one or more layers. Instead of fitting a direct mapping H(x) from scratch, each block learns a residual mapping F(x) = H(x) - x so the block outputs F(x) + x, making identity transformations trivial when extra layers are unneeded. This resolves the deep network degradation problem and creates an unobstructed additive gradient highway during backpropagation, enabling networks with hundreds of layers.

75Regularization Techniques

Why is L1 supposed to lead to sparsity than L2?

L1 regularization induces sparsity because its constraint region is a cross-polytope (a diamond in 2D) with sharp corners lying directly on the coordinate axes, where one or more weights equal zero. Expanding elliptical loss contours are much more likely to hit a sharp axial corner of the L1 diamond than to intersect a smooth L2 hypersphere exactly on an axis. Analytically, L1's constant subgradient magnitude pushes small weights all the way to zero, whereas L2's gradient fades proportionally toward zero.

76Regularization Techniques

Why L1 and L2 are Commonly Used for Regularization

L1 and L2 norms dominate regularization because they strike the optimal balance between statistical usefulness, convexity, and computational tractability. Ideal sparsity (L0 pseudo-norm) requires NP-hard combinatorial subset search, whereas L1 is its tightest convex relaxation and yields sparse models efficiently, and squared L2 is strictly convex, smooth everywhere, and admits a closed-form linear solution in Ridge regression. Probabilistically, L1 and L2 correspond directly to Laplace and Gaussian MAP priors.

77Model Evaluation

relative-entropy VS cross-entropy

Cross-entropy H(P, Q) measures the average code length when encoding events from true distribution P using a model distribution Q, while KL divergence (relative entropy) D_KL(P || Q) measures the extra information lost beyond P's intrinsic entropy H(P). Because H(P, Q) = H(P) + D_KL(P || Q) and H(P) does not depend on model parameters, minimizing cross-entropy with respect to Q is mathematically equivalent to minimizing KL divergence.

78Regularization Techniques

Why Regularization Reduces Overfitting

Regularization reduces overfitting by constraining a model's effective hypothesis space so it cannot fit random noise in the training data with extreme weights. Shrinking weight magnitudes bounds the function's Lipschitz constant—making predictions smoother across neighboring inputs—and damps unstable directions associated with small singular values. In doing so, regularization accepts a modest bias increase in exchange for a much larger drop in variance, improving test generalization.

79Model Evaluation

Precision/recall tradeoff

The precision-recall tradeoff occurs because shifting a classifier's decision threshold moves false positives and false negatives in opposite directions. Raising the threshold makes positive predictions stricter—typically increasing precision while decreasing recall—whereas lowering the threshold captures more true positives (higher recall) at the expense of more false alarms (lower precision).

80Model Evaluation

Loss function of logistic regression

Logistic regression uses binary cross-entropy (log loss) rather than mean squared error. Derived directly from Maximum Likelihood Estimation under a Bernoulli likelihood, binary cross-entropy is convex with respect to the model weights and bias, ensuring gradient-based optimizers avoid spurious local minima.

81Model Evaluation

Pros and Cons of the Sigmoid Function

The sigmoid function maps real inputs smoothly into (0, 1), making it ideal for binary classification outputs and multiplicative gates where values represent probabilities or fractions. However, as a hidden-layer activation in deep networks it suffers from severe vanishing gradients (maximum derivative is 0.25), non-zero-centered outputs that slow optimization, and higher exponential compute cost.

82Model Evaluation

What is AUC - ROC Curve?

The ROC (Receiver Operating Characteristic) curve plots a binary classifier's True Positive Rate against its False Positive Rate across all classification thresholds from 0 to 1. AUC (Area Under the ROC Curve) summarizes this curve as a scalar between 0 and 1, equal to the probability that the model ranks a randomly chosen positive instance higher than a randomly chosen negative instance. A higher AUC indicates stronger threshold-independent class separation, with 1.0 representing perfect ranking and 0.5 representing random guessing.

83Model Evaluation

Loss function of SVM

Support Vector Machines optimize an L2-regularized hinge loss objective. Hinge loss is zero for any sample classified on the correct side of the margin with functional margin at least 1, and grows linearly for points inside the margin or on the wrong side of the decision boundary, focusing optimization on the support vectors.

84Model Evaluation

Entropy

Shannon entropy measures the average uncertainty or expected surprise (information content) of a random variable's probability distribution. Zero entropy corresponds to a deterministic outcome, whereas entropy reaches its maximum under a uniform distribution; in machine learning it underpins decision tree information gain and cross-entropy loss.

85Model Evaluation

Confusion matrix

A confusion matrix is a cross-tabulation of actual class labels against predicted class labels in supervised classification. For binary tasks it records True Positives, True Negatives, False Positives, and False Negatives, forming the exact foundation for derived metrics such as precision, recall, specificity, accuracy, and F1-score.

86Neural Networks and Deep Learning

Vanishing Gradient Problem

The vanishing gradient problem occurs during backpropagation when gradients shrink exponentially as they propagate from later layers back to earlier layers, starving early weights of meaningful updates. It arises through the chain rule when repeated Jacobian products involve small weight singular values and saturating activations like sigmoid or tanh whose derivatives approach zero. Common mitigations include non-saturating activations such as ReLU, He or Xavier initialization, normalization layers, residual skip connections, and gating in LSTMs or GRUs.

87Neural Networks and Deep Learning

Initializing weights with 0s for NN?

Initializing all weights to zero in a multi-layer neural network fails because it destroys symmetry breaking and can trap hidden layers with zero gradients. Every neuron in a layer receives identical pre-activations and identical updates—effectively collapsing the layer to a single unit—and zero downstream weights or ReLU at zero can stall gradients completely, making random Xavier or He initialization essential.

88Neural Networks and Deep Learning

Relation between logistic regression and neural network?

Logistic regression is mathematically equivalent to a single-layer neural network with one output neuron using a sigmoid activation and binary cross-entropy loss. Deep neural networks generalize this building block by stacking multiple hidden layers with non-linear activations, transforming linearly inseparable inputs into separable latent representations.

89Neural Networks and Deep Learning

Batch size

Batch size determines how many training examples are processed in one forward and backward pass to compute a gradient update. Larger batches reduce gradient variance and maximize GPU throughput but require more memory and careful learning rate scaling, whereas smaller batches save memory and introduce gradient noise that often acts as implicit regularization for better generalization.

90Neural Networks and Deep Learning

Motivation of Recurrent Neural Networks (RNNs)

Recurrent Neural Networks (RNNs) were motivated by the inability of standard feedforward networks to handle variable-length sequences and share parameters across time. By maintaining a recurrent hidden state updated at every time step with shared weights, RNNs preserve context from prior inputs when modeling time series, audio, and language.

91Neural Networks and Deep Learning

Learning Rate in Machine Learning

The learning rate is a hyperparameter that scales the magnitude of parameter updates during gradient-based optimization. Too small a learning rate causes slow convergence and risks stalling, whereas too large a learning rate causes overshooting, oscillation, or divergence, making careful tuning and learning rate schedules essential.

92Neural Networks and Deep Learning

Avoid overfitting in NN

Overfitting occurs when a neural network memorizes training noise rather than generalizable patterns, causing high training accuracy alongside degraded validation and test performance. Common defenses include L1/L2 weight regularization, dropout, label-preserving data augmentation, early stopping monitored on a held-out validation split, and constraining model capacity.

93Neural Networks and Deep Learning

Why is non linear activation function needed?

Non-linear activation functions are essential because composing any number of purely linear layers algebraically collapses into a single affine transformation, giving a deep linear network no more expressive power than linear regression. Introducing non-linear, non-polynomial activations such as ReLU, GELU, sigmoid, or tanh breaks this collapse, enabling hierarchical feature composition and curved decision boundaries. By the Universal Approximation Theorem, even a single hidden layer with enough non-polynomial units can approximate any continuous function on a compact domain.

94Neural Networks and Deep Learning

What is backpropagation?

Backpropagation is the reverse-mode automatic differentiation algorithm used to compute exact gradients of a loss function with respect to every weight and bias in a neural network. After a forward pass caches intermediate activations, backpropagation applies the chain rule from output to input in time proportional to a single forward pass. Optimization algorithms such as SGD or Adam then use these gradients to update parameters and minimize the loss.

95Neural Networks and Deep Learning

Does NN fit data better than logistic regression?

Multi-layer neural networks with non-linear activations can fit complex non-linear data far better than logistic regression, which is restricted to linear decision boundaries in input space (and is itself equivalent to a single-layer sigmoid network). However, on small, noisy, or linearly separable tabular datasets, logistic regression often generalizes better due to lower variance and convex optimization.

96Neural Networks and Deep Learning

What is dropout?

Dropout is a neural network regularization technique that randomly sets each hidden unit's activation to zero with probability p during each training forward pass. Modern implementations use inverted dropout, scaling surviving activations by 1/(1-p) during training so the network requires no rescaling at inference time. By breaking feature co-adaptation, dropout approximates training and averaging an exponential ensemble of thinned sub-networks.

97Neural Networks and Deep Learning

Exploding Gradient

Exploding gradients arise during backpropagation when repeated multiplication of layer weight matrices and activation derivatives causes error gradients to grow exponentially across deep layers or long sequences. This produces huge parameter updates, loss oscillations, or NaN overflow, and is mitigated using gradient norm clipping, proper initialization (Xavier/He), normalization layers, residual connections, and gated RNNs.

98NLP

What's the motivation behind LSTM?

Long Short-Term Memory (LSTM) networks were designed to overcome the vanishing gradient problem that prevents standard Recurrent Neural Networks (RNNs) from learning long-range dependencies during Backpropagation Through Time (BPTT). Standard RNNs repeatedly multiply hidden states by recurrent weight matrices and tanh derivatives at every step, causing gradients from distant inputs to decay exponentially. LSTMs introduce an additive cell-state highway controlled by input, forget, and output gates, enabling gradients and memory signals to persist across many time steps.

99Computer Vision and CNN

Why 1x1 convolutional layer?

A 1x1 convolutional layer applies a learned linear combination across channels at every spatial pixel independently, followed by a non-linear activation. Its primary uses are channel dimensionality reduction (bottlenecks before expensive 3x3 or 5x5 convolutions), channel expansion in residual blocks, and adding cheap depth with far fewer parameters than spatial kernels. It acts as a parameter-sharing MLP across the channel dimension without altering height or width.

100NLP

How does bagging work?

Bagging (Bootstrap Aggregating) reduces variance by training multiple instances of a high-variance base model independently on bootstrap datasets sampled with replacement from the training set. Averaging their predictions for regression or taking majority votes for classification cancels out sample-specific noise and yields more stable generalization.

101NLP

What is a Language Model?

A language model defines a probability distribution over sequences of tokens or words, scoring how plausible a sequence is in a language. Autoregressive language models factorize sequence probability via the chain rule into next-token predictions conditioned on prior context, whereas masked language models predict hidden tokens from bidirectional context. Evaluated commonly by perplexity, modern language models built on Transformers power text generation, translation, speech recognition, and reasoning tasks.

102NLP

Word Embeddings

Word embeddings are dense, low-dimensional vector representations of words learned from text corpora so that semantically and syntactically similar words lie close together in vector space. Grounded in the distributional hypothesis, methods like Word2Vec, GloVe, and FastText replace sparse, orthogonal one-hot vectors with continuous representations that support similarity search and analogical reasoning. Unlike static embeddings that assign one fixed vector per word, modern Transformers produce contextualized embeddings that vary with surrounding words.

103Computer Vision and CNN

Zero padding in CNN

Zero-padding appends borders of zeros around an input feature map before applying a convolutional kernel. It prevents spatial dimensions from shrinking across deep stacks of convolutional layers ('same' padding) and ensures edge pixels participate in multiple receptive fields rather than being under-sampled. While simple and computationally cheap, zero-padding introduces artificial step edges at borders and can leak absolute spatial position cues compared with reflection or replication padding.

Frequently Asked Questions

Which classic ML concepts still show up in GenAI-focused interviews?

Bias-variance trade-offs, regularization, cross-entropy and KL divergence, gradient clipping, batch normalization vs. layer normalization, and precision-recall evaluation remain standard baseline questions across AI roles.

How should I practice these 103 ML interview questions?

Filter by category (Basic Concepts, Neural Networks, Math & Optimization), summarize the core mechanism in two sentences without peeking, then verify edge cases and failure modes in the full study card.

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.