Prev Next

AI / Essential Machine Learning Algorithms Interview questions

Last updated

1. What is linear regression? 2. What is logistic regression? 3. What is a decision tree? 4. What is k-nearest neighbors (KNN)? 5. What is the k-means clustering algorithm? 6. What is Naive Bayes? 7. What is a support vector machine (SVM)? 8. What is a random forest? 9. What is gradient boosting? 10. What is Principal Component Analysis (PCA)? 11. What is gradient descent? 12. What is a neural network? 13. What is hierarchical clustering? 14. What is DBSCAN? 15. What are the types of machine learning? 16. What is the purpose of regularization? 17. What is XGBoost? 18. What is bagging? 19. What is Q-learning? 20. What is the purpose of an activation function in a neural network? 21. What is the difference between bagging and boosting? 22. What is the difference between L1 and L2 regularization? 23. Why does logistic regression use log loss instead of mean squared error? 24. How does a decision tree choose its splits? 25. Why do random forests reduce overfitting? 26. How does the kernel trick work in SVM? 27. Why is feature scaling important for KNN and SVM? 28. How does k-means++ choose initial centroids, and why does it matter? 29. How do you choose the number of clusters in k-means? 30. What is the difference between k-means and DBSCAN? 31. How does gradient boosting build its ensemble step by step? 32. What is the difference between XGBoost, LightGBM, and CatBoost? 33. Why does Naive Bayes work well despite its independence assumption? 34. What is the bias-variance tradeoff? 35. How does PCA work internally? 36. What is the difference between PCA and t-SNE? 37. Explain the execution flow of backpropagation? 38. What is the difference between batch, stochastic, and mini-batch gradient descent? 39. Why does Adam often converge faster than plain SGD? 40. What is the vanishing gradient problem and how do you fix it? 41. How do you detect and handle multicollinearity in linear regression? 42. What is the difference between generative and discriminative models? 43. How do you handle class imbalance in classification algorithms? 44. When would you choose a decision tree over logistic regression? 45. What happens when you increase k in KNN? 46. How does AdaBoost update sample weights? 47. Explain the internal working of the Expectation-Maximization algorithm for Gaussian Mixture Models? 48. How does Q-learning differ from SARSA? 49. Which is better and why: random forest or gradient boosting? 50. How does self-attention work in a transformer?

1. What is linear regression?

Linear regression is a supervised algorithm that predicts a continuous value by fitting a straight line (or a hyperplane, with many features) through the training data. The model looks like y = w1*x1 + w2*x2 + ... + b, and the weights are chosen to minimize the sum of squared errors between predictions and actual values.

It can be solved directly with the normal equation or iteratively with gradient descent. It is fast, easy to interpret, and a sensible baseline for problems like price or demand forecasting.

It assumes a roughly linear relationship, independent errors, constant error variance, and little multicollinearity between features.

Take quiz
Linear regression is mainly used to predict:
a class label only
cluster membership
a continuous numeric value
Which loss does ordinary linear regression minimize?
cross-entropy
hinge loss
Gini impurity
sum of squared errors

2. What is logistic regression?

Logistic regression is a supervised classification algorithm. It computes a weighted sum of the features, then squeezes it through the sigmoid function to get a probability between 0 and 1. A threshold, usually 0.5, turns that probability into a class label.

Training minimizes log loss (cross-entropy). Each coefficient can be read as the change in the log-odds of the positive class for a one-unit change in that feature, which makes the model easy to explain.

Despite the word 'regression' in its name, it is used for classification, such as spam detection or churn prediction.

Take quiz
Logistic regression converts a linear score into a probability using:
the sigmoid function
the ReLU function
a decision stump
a distance matrix
Despite its name, logistic regression is mainly used for:
predicting continuous house prices
grouping unlabeled data
classification
dimensionality reduction

3. What is a decision tree?

A decision tree is a supervised model that makes predictions by asking a series of yes/no questions about the features. Internal nodes hold a test (for example age < 30), branches are the outcomes, and leaf nodes hold the final class or value.

The tree is built top-down. At each node the algorithm picks the split that most reduces impurity, measured by Gini or entropy for classification and variance for regression.

Trees are easy to read and need little preprocessing, but a deep tree memorizes the training set. Pruning or limiting max_depth keeps that in check.

Take quiz
In a decision tree, a leaf node holds:
a feature test
the learning rate
the full training set
the final prediction (a class or a value)
A node containing samples of only one class has a Gini impurity of:
0.5
0
1
it depends on the feature count

4. What is k-nearest neighbors (KNN)?

KNN predicts the label of a new point by looking at the k closest training points and letting them decide. For classification it takes a majority vote; for regression it averages their target values.

It is a lazy learner: there is no real training step, the algorithm just stores the data and does the work at prediction time. Closeness is usually measured with Euclidean distance, so features should be scaled first.

KNN is simple and makes no assumption about the data shape, but prediction gets slow on large datasets and it struggles in very high dimensions.

Take quiz
KNN is called a lazy learner because it:
trains very slowly
ignores most features
defers all computation to prediction time
never uses distances
For classification, KNN predicts the label by:
majority vote among the k closest points
averaging every training label
fitting a straight line
building a tree of splits

5. What is the k-means clustering algorithm?

k-means is an unsupervised algorithm that groups data into k clusters by minimizing the distance between points and their cluster center, called the centroid.

  1. Pick k initial centroids.
  2. Assign every point to its nearest centroid.
  3. Update each centroid to the mean of its assigned points.
  4. Repeat steps 2-3 until assignments stop changing.

You must choose k up front, and the result depends on the starting centroids, so libraries run it several times and keep the best run.

from sklearn.cluster import KMeans
model = KMeans(n_clusters=3, n_init=10, random_state=42)
labels = model.fit_predict(X)

Take quiz
k-means alternates between which two steps?
splitting nodes and pruning
forward pass and backward pass
assigning points to the nearest centroid and recomputing the centroids
bootstrapping and voting
What must you supply to k-means before training?
the number of clusters k
the class labels
the tree depth
the kernel type

6. What is Naive Bayes?

Naive Bayes is a probabilistic classifier built on Bayes' theorem. For each class it multiplies the class prior by the likelihood of every feature, then picks the class with the highest posterior.

It is called naive because it assumes features are conditionally independent given the class. That is rarely true, but it makes the math cheap and needs very little training data.

  • Gaussian - continuous features
  • Multinomial - word counts in text
  • Bernoulli - binary presence/absence features

It is a classic choice for spam filtering and document classification.

Take quiz
The 'naive' in Naive Bayes refers to assuming that:
all classes are equally likely
features are conditionally independent given the class
the data is linearly separable
every feature is Gaussian
Which variant is the usual fit for raw word-count features?
Gaussian Naive Bayes
Linear Naive Bayes
Multinomial Naive Bayes

7. What is a support vector machine (SVM)?

An SVM is a supervised algorithm that finds the decision boundary with the widest possible margin between two classes. The training points sitting closest to that boundary are the support vectors, and they alone define it.

The parameter C controls the trade-off: a high C punishes misclassification hard and gives a narrow margin, while a low C tolerates some errors for a wider, smoother margin.

With a kernel such as RBF, an SVM can separate data that is not linearly separable. It works well on medium-sized datasets but scales poorly to millions of rows.

Take quiz
Support vectors are:
the training points closest to the decision boundary
the cluster centroids
the features with highest variance
the misclassified points removed from training
An SVM picks the hyperplane that:
minimizes the number of features
passes through the class means
maximizes the margin between classes
maximizes tree depth

8. What is a random forest?

A random forest is an ensemble of many decision trees whose predictions are combined: a majority vote for classification, an average for regression.

Two kinds of randomness make the trees different from each other. Each tree trains on a bootstrap sample of the rows, and at every split it only considers a random subset of the features.

Averaging many decorrelated trees cancels out their individual mistakes, so the forest overfits much less than a single deep tree. It also gives feature importance scores and out-of-bag error for free.

Take quiz
Each tree in a random forest is trained on:
only the rows the previous tree got wrong
the same full dataset with identical splits
a single feature
a bootstrap sample of the rows
A random forest classifier produces its final label by:
using only the deepest tree
majority vote across trees
summing residuals
picking the first tree

9. What is gradient boosting?

Gradient boosting builds a strong model by adding small trees one after another, where each new tree is trained to correct the errors of the ensemble so far.

Concretely, each tree fits the residuals (the negative gradient of the loss) of the current predictions. Its output is then added to the ensemble after being multiplied by a small learning rate, so no single tree dominates.

It usually beats random forests on tabular data when tuned well, but it trains sequentially and overfits if you use too many trees without early stopping.

Take quiz
Each new tree in gradient boosting is trained to predict:
a fresh bootstrap of the labels
the cluster centers
the residual errors of the current ensemble
the feature means
In boosting, the learning rate:
shrinks the contribution of each new tree
sets the number of features per split
chooses the number of clusters
sets the minimum leaf size

10. What is Principal Component Analysis (PCA)?

PCA is an unsupervised technique that reduces the number of features while keeping as much variance as possible. It rotates the data onto new, mutually perpendicular axes called principal components.

The first component points in the direction of greatest variance, the second captures the most remaining variance at a right angle to the first, and so on. Keeping only the top few components compresses the data.

Features should be centered, and usually scaled, before PCA. Common uses are visualization, noise reduction, and speeding up downstream models.

Take quiz
The first principal component captures:
the direction that best separates the classes
the feature with the highest mean
the direction of maximum variance
the rarest category
Before applying PCA you should normally:
center and usually scale the features
one-hot encode the target
shuffle the labels
remove all correlated rows

11. What is gradient descent?

Gradient descent is an optimization algorithm that minimizes a loss function by repeatedly stepping in the direction that decreases it fastest, which is opposite to the gradient.

The update rule is w = w - lr * gradient. The learning rate sets the step size: too small and training crawls, too large and the loss oscillates or diverges.

for _ in range(epochs):
    grad = (2 / n) * X.T @ (X @ w - y)   # MSE gradient
    w -= lr * grad

It powers linear models, logistic regression, and neural networks.

Take quiz
Gradient descent updates parameters by moving:
along the gradient of the loss
opposite to the gradient of the loss
toward the data mean
in a random direction
A learning rate that is far too large usually causes:
guaranteed faster convergence
automatic regularization
fewer parameters
oscillation or divergence of the loss

12. What is a neural network?

A neural network is a model made of layers of connected units called neurons. Each neuron takes a weighted sum of its inputs, adds a bias, and passes the result through an activation function.

Data flows forward through an input layer, one or more hidden layers, and an output layer. During training, backpropagation computes how much each weight contributed to the error, and an optimizer such as SGD or Adam adjusts the weights.

Networks can learn very complex non-linear patterns, but they need more data and compute than classical algorithms and are harder to interpret.

Take quiz
A single neuron computes:
a weighted sum of inputs plus a bias, passed through an activation
the median of its inputs
the distance to a centroid
a Gini impurity
Neural network weights are learned using:
counting class frequencies
k-means centroids
backpropagation with a gradient-based optimizer
a nearest-neighbor lookup

13. What is hierarchical clustering?

Hierarchical clustering builds a tree of clusters instead of a flat set. The common agglomerative version starts with every point as its own cluster and repeatedly merges the two closest clusters until only one remains.

How 'closest' is measured depends on the linkage: single (nearest members), complete (farthest members), average, or Ward (smallest increase in variance).

The result is drawn as a dendrogram. Cutting it at a chosen height gives the final clusters, so you do not need to fix k in advance. The cost is poor scaling, roughly quadratic or worse in the number of points.

Take quiz
A dendrogram shows:
feature importance scores
the ROC curve of a classifier
the loss per epoch
the order and distance at which clusters merge
Agglomerative clustering starts with:
one cluster holding all points
every point as its own cluster
k random centroids
a pre-trained tree

14. What is DBSCAN?

DBSCAN is a density-based clustering algorithm. It groups together points that are packed closely and marks isolated points as noise.

It uses two parameters: eps, the neighborhood radius, and min_samples, the number of neighbors needed to call a point dense.

  • Core point - has at least min_samples points within eps
  • Border point - within eps of a core point but not dense itself
  • Noise - neither of the above

Unlike k-means, it finds clusters of arbitrary shape and does not need k, but it struggles when clusters have very different densities.

Take quiz
In DBSCAN, points that are not reachable from any core point are labeled:
centroids
support vectors
noise
border leaders
Which two parameters drive DBSCAN?
eps and min_samples
k and max_iter
C and gamma
learning rate and epochs

15. What are the types of machine learning?

Machine learning is usually split into four types based on the feedback the algorithm learns from.

Type Learns from Typical algorithms
Supervised labeled examples linear/logistic regression, SVM, random forest
Unsupervised unlabeled data k-means, PCA, DBSCAN
Semi-supervised few labels plus many unlabeled rows self-training, label propagation
Reinforcement rewards from an environment Q-learning, policy gradients

Supervised learning covers classification and regression, while unsupervised learning covers clustering and dimensionality reduction.

Take quiz
Which type of learning is driven by reward signals?
supervised learning
unsupervised learning
reinforcement learning
Grouping customers into segments with no labels is an example of:
unsupervised learning
supervised classification
reinforcement learning
supervised regression

16. What is the purpose of regularization?

Regularization adds a penalty on model complexity to the loss function so the model cannot fit noise in the training data. Its purpose is to reduce overfitting and improve performance on unseen data.

In linear models the penalty is on the size of the weights: L2 (ridge) shrinks all weights, while L1 (lasso) can push some to exactly zero. In neural networks, dropout and weight decay serve the same goal. Tree models use limits such as max_depth and min_samples_leaf.

A strength parameter (lambda or alpha) controls the trade-off. Too much regularization causes underfitting; too little leaves overfitting in place.

Take quiz
Regularization primarily helps reduce:
the size of the training set
overfitting
inference latency
the number of classes
Increasing regularization strength typically:
makes the model more complex
has no effect on the weights
adds new features
shrinks the weights and simplifies the model

17. What is XGBoost?

XGBoost (Extreme Gradient Boosting) is an optimized, regularized implementation of gradient-boosted decision trees, famous for winning many tabular-data competitions.

It improves on plain gradient boosting in a few concrete ways:

  • Uses second-order gradient information when fitting each tree
  • Adds L1/L2 regularization and a complexity penalty on leaves
  • Finds splits in parallel and supports column and row subsampling
  • Learns a default direction for missing values at every split

It also supports early stopping and custom objectives, which makes it practical for production use.

Take quiz
XGBoost improves on plain gradient boosting partly by:
adding regularization and using second-order gradient information
training every tree independently like bagging
replacing trees with linear kernels
removing the learning rate
How does XGBoost handle missing values?
it requires all values to be imputed first
it learns a default direction at each split
it drops every row with a missing value

18. What is bagging?

Bagging (bootstrap aggregating) trains several copies of the same model on different bootstrap samples - random draws from the training data with replacement - and combines their outputs by voting or averaging.

Because each model sees a slightly different dataset, their errors are partly independent and averaging reduces variance without raising bias much. It works best with unstable, high-variance learners such as deep decision trees.

About 37% of rows are left out of each bootstrap sample. These out-of-bag rows give a free validation estimate.

Take quiz
Bagging mainly reduces:
bias
the number of features
the dataset size
variance
Out-of-bag samples are:
the final test set
rows not drawn into a given model's bootstrap sample
duplicated rows with noise
rows with missing labels

19. What is Q-learning?

Q-learning is a model-free reinforcement learning algorithm that learns a table of Q-values, where Q(s, a) estimates the total future reward for taking action a in state s and acting well afterward.

Q[s, a] += alpha * (r + gamma * max(Q[s_next]) - Q[s, a])

alpha is the learning rate and gamma is the discount factor that decides how much future rewards matter. The agent usually follows an epsilon-greedy policy: mostly the best known action, occasionally a random one to keep exploring.

It is off-policy, since the update uses the best next action rather than the one actually taken.

Take quiz
Q-learning is best described as:
a supervised classifier
a clustering method
a model-free, off-policy value-based method
a dimensionality reduction method
In the Q-learning update, gamma controls:
how much future rewards are valued
the number of clusters
the tree depth
the size of the replay table only

20. What is the purpose of an activation function in a neural network?

An activation function adds non-linearity to a neuron's output. Without it, stacking layers would still collapse into a single linear transformation, and the network could never learn curved decision boundaries.

Function Range Typical use
Sigmoid 0 to 1 binary output layer
Tanh -1 to 1 older hidden layers, RNNs
ReLU 0 to infinity default for hidden layers
Softmax probabilities summing to 1 multi-class output layer

ReLU is the usual hidden-layer choice because it is cheap and does not saturate for positive inputs.

Take quiz
Without non-linear activations, a deep network is equivalent to:
a decision tree
a random forest
a single linear transformation
a k-means model
Softmax is typically used:
in the output layer for multi-class classification
in hidden layers of regression nets
to scale input features
to compute the loss gradient only

21. What is the difference between bagging and boosting?

Both combine many weak models, but they attack different errors. Bagging trains models in parallel to cut variance, while boosting trains them sequentially to cut bias.

Aspect Bagging Boosting
Training order independent, parallel sequential, each depends on the last
Main goal reduce variance reduce bias
Data per model bootstrap sample reweighted data or residuals
Combination equal vote or average weighted sum
Overfitting risk low higher without early stopping
Examples random forest AdaBoost, XGBoost

Pick bagging when your base model is unstable and overfits. Pick boosting when a simple model underfits and you can afford careful tuning.

Take quiz
Which approach trains learners one after another, correcting earlier mistakes?
boosting
bagging
random subspace sampling only
Random forest is an example of:
boosting
stacking
reinforcement learning
bagging

22. What is the difference between L1 and L2 regularization?

Both penalize large weights, but the shape of the penalty changes the result. L1 adds the sum of absolute weights; L2 adds the sum of squared weights.

Aspect L1 (Lasso) L2 (Ridge)
Penalty lambda * sum(|w|) lambda * sum(w^2)
Effect on weights drives some exactly to zero shrinks all, rarely to zero
Feature selection built in none
Correlated features tends to keep one, drop others spreads weight across them
Solution no closed form closed form exists

L1 gives sparse, compact models. L2 is smoother and more stable with collinear features. Elastic Net mixes both when you want sparsity and stability.

Take quiz
Which penalty can set coefficients exactly to zero?
L1
L2
both equally
neither
The L2 penalty term is:
the sum of absolute weights
the count of non-zero weights
the sum of squared weights
the largest weight

23. Why does logistic regression use log loss instead of mean squared error?

Log loss is the negative log-likelihood of the Bernoulli model that logistic regression assumes, and it is convex in the weights. That guarantees gradient descent reaches the global minimum.

Mean squared error on sigmoid outputs is not convex. When the sigmoid saturates, its slope is nearly zero, so a confidently wrong prediction produces a tiny gradient and learning stalls.

Log loss avoids this because the sigmoid derivative cancels out, leaving a clean gradient: (p - y) * x. It also punishes confident mistakes heavily, which pushes the model toward well-calibrated probabilities.

Take quiz
Log loss suits logistic regression because it is:
unbounded for correct predictions
free of any probability model
only usable for regression
convex in the weights and comes from maximum likelihood
MSE on sigmoid outputs tends to cause:
a closed-form solution
a non-convex loss with vanishing gradients when saturated
perfectly calibrated probabilities
faster convergence always

24. How does a decision tree choose its splits?

At each node the tree tries every feature and every candidate threshold, scores each split by how much it reduces impurity, and keeps the best one.

For classification, impurity is Gini (1 - sum(p_i^2)) or entropy (-sum(p_i * log2 p_i)). The gain is the parent impurity minus the weighted average impurity of the two children. For regression, the tree minimizes variance (MSE) instead.

The procedure is greedy: it picks the best split at the current node and never revisits earlier choices, so the final tree is not guaranteed to be globally optimal. It recurses until it hits a stopping rule such as max_depth, min_samples_leaf, or a pure node.

Take quiz
A tree picks the split that:
uses the feature seen most often
creates the most leaves
gives the largest impurity reduction
is chosen at random
A greedy tree builder:
picks the best local split and never backtracks
searches all possible trees
restarts from the root after each split
uses gradient descent on splits

25. Why do random forests reduce overfitting?

A single deep tree has low bias but very high variance. Averaging many trees lowers that variance, and the trees must be decorrelated for the averaging to work.

For B trees with variance sigma^2 and pairwise correlation rho, the ensemble variance is rho*sigma^2 + (1 - rho)*sigma^2 / B. More trees shrink the second term, but only lower correlation shrinks the first.

That is the reason for random feature subsets at each split: without them, a few strong features would dominate every tree and they would all look alike. Bootstrap sampling adds more diversity.

Adding more trees does not cause overfitting; the accuracy gain just flattens out.

Take quiz
Random feature subsets at each split help mainly by:
making each tree deeper
reducing the number of rows
decorrelating the trees
removing bias entirely
Adding more trees to a random forest generally:
does not increase overfitting, and gains plateau
causes steady overfitting
reduces bias sharply
makes training sequential

26. How does the kernel trick work in SVM?

A linear SVM cannot separate data like concentric circles. Mapping the data into a higher-dimensional space can make it separable, but computing that mapping explicitly is expensive or even infinite-dimensional.

The SVM's dual formulation only needs dot products between points. A kernel function K(x, z) returns the dot product in the high-dimensional space directly from the original inputs, so the mapping is never computed.

  • Linear - no mapping
  • Polynomial - captures feature interactions up to a degree
  • RBF - similarity decays with distance; gamma sets how narrow each point's influence is
from sklearn.svm import SVC
clf = SVC(kernel=&#x27;rbf&#x27;, C=1.0, gamma=&#x27;scale&#x27;)

A large gamma gives a wiggly boundary that can overfit; a small gamma gives a smoother one.

Take quiz
The kernel trick lets an SVM:
skip the training phase
compute high-dimensional dot products without explicit mapping
remove all support vectors
avoid using labels
A very large gamma in an RBF kernel tends to:
smooth the boundary heavily
turn the kernel linear
ignore the support vectors
make each point's influence narrow and risk overfitting

27. Why is feature scaling important for KNN and SVM?

Both algorithms are driven by distances or dot products. If one feature ranges from 0 to 100,000 (income) and another from 0 to 1 (a flag), the large feature dominates the distance and the small one is practically ignored.

For KNN this changes which neighbors are 'nearest'. For an RBF SVM it distorts the kernel; for a regularized linear SVM it makes the penalty uneven across features.

Use standardization (zero mean, unit variance) or min-max scaling. Fit the scaler on the training set only, then apply it to validation and test data to avoid leakage.

Tree-based models are the exception, since they split on thresholds and are unaffected by monotonic scaling.

Take quiz
Which algorithm is least affected by feature scaling?
decision tree
KNN
RBF SVM
k-means
The scaler should be fit on:
the full dataset including test
the test data only
the training data only
the labels

28. How does k-means++ choose initial centroids, and why does it matter?

Plain k-means picks starting centroids at random, which can drop two of them in the same natural cluster and leave another cluster uncovered. The algorithm then settles into a poor local minimum.

k-means++ spreads the starting points out:

  1. Pick the first centroid uniformly at random.
  2. For each point, compute its squared distance to the nearest chosen centroid.
  3. Pick the next centroid with probability proportional to that squared distance.
  4. Repeat until k centroids are chosen.

Far-away points are more likely to be picked, so the seeds start well separated. This usually gives lower final inertia and faster convergence, and it is the default in scikit-learn alongside multiple restarts (n_init).

Take quiz
k-means++ picks the next centroid with probability proportional to:
the cluster size
the label frequency
the feature variance
the squared distance to the nearest existing centroid
Poor centroid initialization in k-means can lead to:
a negative number of clusters
a bad local minimum
a deeper decision tree
automatic outlier removal

29. How do you choose the number of clusters in k-means?

There is no single correct answer, so practitioners combine a few methods and check them against domain knowledge.

Method How it works Look for
Elbow plot inertia against k the bend where gains flatten
Silhouette average cohesion vs separation per point the k with the highest score (max 1)
Gap statistic compares inertia to random reference data the largest gap
Domain need business rule such as 4 customer tiers a practical fit

Inertia always decreases as k grows, so it cannot be minimized blindly. Silhouette is often more reliable because it penalizes clusters that overlap. Also check cluster stability across random seeds.

Take quiz
A silhouette score close to 1 indicates:
heavily overlapping clusters
mostly noise points
tight, well-separated clusters
an unused centroid
The elbow method plots:
inertia against the number of clusters
accuracy against tree depth
loss against epochs
precision against recall

30. What is the difference between k-means and DBSCAN?

k-means partitions data around centroids; DBSCAN grows clusters out of dense regions. That one design difference drives everything else.

Aspect k-means DBSCAN
Needs k? yes no (needs eps, min_samples)
Cluster shape roughly spherical arbitrary
Outliers forced into a cluster labeled as noise
Varying density copes moderately struggles
Speed on large data fast slower without a spatial index
Deterministic no, depends on init mostly yes

Use k-means for compact, similar-sized groups and large data. Use DBSCAN when clusters have odd shapes or you need explicit outlier detection.

Take quiz
Which algorithm explicitly labels outliers as noise?
k-means
both always
DBSCAN
linear regression
k-means works best when clusters are:
roughly spherical and similar in size
arbitrarily shaped
nested hierarchies
extremely sparse

31. How does gradient boosting build its ensemble step by step?

Gradient boosting performs gradient descent in function space: each tree is a step that moves the predictions toward lower loss.

flowchart TD
  A["Start with constant prediction F0"] --> B["Compute pseudo-residuals<br/>negative gradient of loss"]
  B --> C["Fit a small tree to the residuals"]
  C --> D["Set leaf values for best loss reduction"]
  D --> E["Update F = F + learning_rate * tree"]
  E --> F{More trees or<br/>early stop?}
  F -- continue --> B
  F -- stop --> G["Final model F"]
  1. Initialize with a constant: the mean of y for squared error, or the log-odds for classification.
  2. Compute residuals for every row from the current predictions.
  3. Fit a shallow tree (depth 3-8) to those residuals.
  4. Add the tree, scaled by the learning rate, to the running prediction.
  5. Repeat for the chosen number of trees, or stop when validation loss stops improving.

A smaller learning rate needs more trees but usually generalizes better.

Take quiz
For squared-error regression, the initial model F0 is:
a random tree
the mean of the targets
all zeros for every dataset
the median feature value
Pseudo-residuals in gradient boosting are:
feature importance scores
the test-set errors
the bootstrap indices
the negative gradient of the loss at the current predictions

32. What is the difference between XGBoost, LightGBM, and CatBoost?

All three are gradient-boosted tree libraries. They differ mainly in how they grow trees, handle categories, and trade off speed.

Aspect XGBoost LightGBM CatBoost
Tree growth level-wise by default leaf-wise (best-first) symmetric (oblivious) trees
Split finding exact or histogram histogram with GOSS histogram
Categorical features needs encoding (limited support) native support native, ordered target statistics
Strength mature, flexible very fast on large data strong defaults, less tuning
Watch out for slower on huge data overfits small data slower training on CPU

Reach for LightGBM on large datasets, CatBoost when you have many high-cardinality categorical columns, and XGBoost when you want maximum ecosystem support.

Take quiz
Which library uses ordered target statistics for categorical features?
CatBoost
classic XGBoost
scikit-learn's KNN
plain AdaBoost
LightGBM grows its trees:
strictly level by level only
at random
leaf-wise, expanding the best leaf first
without using splits

33. Why does Naive Bayes work well despite its independence assumption?

Classification only needs the correct class to have the highest posterior, not accurate probabilities. The independence assumption distorts the probability values, but the ranking of classes is often still right.

Dependencies between features can also partially cancel out, and with only a few parameters per class the model has low variance, which matters when data is limited. Text is a good example: word counts are correlated, yet Naive Bayes still classifies spam well.

The weakness is that its probabilities are poorly calibrated, often pushed toward 0 or 1, and strongly correlated features get counted twice. Use Laplace smoothing so an unseen feature value does not zero out the entire product.

Take quiz
Naive Bayes can classify well with poorly calibrated probabilities because:
it uses many hidden layers
it always predicts 50 percent
it ignores the labels
only the class with the highest posterior matters
The zero-frequency problem in Naive Bayes is fixed by:
PCA
Laplace smoothing
dropout
early stopping

34. What is the bias-variance tradeoff?

A model's expected error splits into bias squared + variance + irreducible noise. Bias is error from overly simple assumptions; variance is error from being too sensitive to the particular training sample.

High bias (underfit) High variance (overfit)
Training error high low
Validation error high, close to training much higher than training
Example linear model on curved data unpruned deep tree
Fixes more features, bigger model, less regularization more data, regularization, bagging, simpler model

Making a model more flexible lowers bias but raises variance. The goal is the sweet spot where validation error is lowest, which you find with cross-validation and learning curves.

Take quiz
An underfit model typically shows:
low bias and high variance
zero error everywhere
high bias and low variance
low bias and low variance
Which approach usually reduces variance?
averaging many models (bagging)
removing regularization
using a smaller dataset
making the model deeper

35. How does PCA work internally?

PCA finds the directions along which the data varies most by decomposing its covariance structure.

flowchart LR
  A["Raw data X"] --> B["Center and scale features"]
  B --> C["Covariance matrix or SVD"]
  C --> D["Eigenvectors and eigenvalues"]
  D --> E["Sort by eigenvalue, keep top k"]
  E --> F["Project data onto k components"]
  1. Center each feature (and usually scale it).
  2. Compute the covariance matrix, or apply SVD directly to the centered data.
  3. Extract eigenvectors (component directions) and eigenvalues (variance along each).
  4. Keep the top k components, often enough to explain 90-95% of total variance.
  5. Multiply the data by those eigenvectors to get the reduced representation.

The explained_variance_ratio_ attribute tells you how much information each component keeps. scikit-learn uses SVD under the hood because it is more numerically stable than forming the covariance matrix.

Take quiz
Eigenvalues in PCA represent:
the number of clusters
the learning rates
the variance captured along each component
the class priors
Which matrix decomposition does scikit-learn typically use for PCA?
singular value decomposition (SVD)
Cholesky decomposition of labels
k-means factorization
a decision tree split

36. What is the difference between PCA and t-SNE?

Both reduce dimensions, but PCA is a general-purpose linear tool while t-SNE is mainly for visualization.

Aspect PCA t-SNE
Type linear non-linear
Preserves global variance structure local neighborhoods
Deterministic yes no, depends on seed and perplexity
New data can transform new points cannot transform new points directly
Speed fast slow on large data
Typical use preprocessing, compression 2D/3D cluster plots

In t-SNE plots, distances between far-apart clusters and cluster sizes are not meaningful. A common workflow is to run PCA down to 30-50 dimensions first, then t-SNE for the final plot.

Take quiz
t-SNE is best suited for:
feature selection for linear models
visualizing high-dimensional data in 2D or 3D
speeding up inference
balancing classes
PCA is:
non-linear and stochastic
only for text data
a supervised method
linear and deterministic

37. Explain the execution flow of backpropagation?

Backpropagation computes the gradient of the loss with respect to every weight by applying the chain rule from the output layer back to the input.

flowchart LR
  A["Input batch"] --> B["Forward pass<br/>compute activations"]
  B --> C["Compute loss"]
  C --> D["Backward pass<br/>chain rule layer by layer"]
  D --> E["Gradients for all weights"]
  E --> F["Optimizer updates weights"]
  F --> A
  1. Forward pass - compute and cache every layer's activations.
  2. Loss - compare the output with the target.
  3. Backward pass - start with dLoss/dOutput and multiply by each layer's local derivative moving backward, reusing cached activations.
  4. Update - the optimizer (SGD, Adam) changes weights using these gradients.

Reusing intermediate results makes the backward pass cost about the same as one forward pass, which is what makes training deep networks feasible.

Take quiz
Backpropagation relies on which rule?
the chain rule of calculus
Bayes' rule
Newton's method only
the central limit theorem
In what order are gradients computed during backpropagation?
from input to output
in random order
from the output layer back toward the input layer
all layers are skipped except the first

38. What is the difference between batch, stochastic, and mini-batch gradient descent?

They differ in how many samples are used to compute each weight update.

Variant Samples per update Behavior
Batch entire dataset stable but slow, high memory use
Stochastic (SGD) 1 sample fast, noisy updates
Mini-batch e.g. 32-256 samples good balance, GPU friendly

Mini-batch is the practical default in deep learning because matrix operations on a batch run efficiently on GPUs and the gradient noise is moderate.

The noise in SGD is not purely bad: it can help the optimizer jump out of shallow local minima and saddle points, though it needs a decaying learning rate to settle near the minimum.

Take quiz
Most deep learning training uses:
full-batch gradient descent only
k-means updates
single-point Newton steps
mini-batch gradient descent
The noise in SGD updates can help by:
guaranteeing the exact global minimum
escaping shallow local minima and saddle points
removing the need for a learning rate
reducing the dataset size

39. Why does Adam often converge faster than plain SGD?

Adam combines momentum with per-parameter adaptive learning rates, so it makes steady progress even when gradients are noisy or scaled very differently across parameters.

  • First moment m: moving average of gradients, which smooths direction like momentum
  • Second moment v: moving average of squared gradients, used to scale each parameter's step
  • Update: w -= lr * m_hat / (sqrt(v_hat) + eps)

Parameters with consistently large gradients get smaller steps, and rarely updated ones get larger steps. Bias correction fixes the fact that m and v start at zero and would otherwise be underestimated early on.

Adam needs little learning-rate tuning, but plain SGD with momentum sometimes generalizes better on image tasks, so it is not always the winner at the end of training.

Take quiz
Adam combines:
k-means and PCA
bagging and boosting
momentum and adaptive per-parameter step sizes
L1 and L2 only
Bias correction in Adam fixes:
early moment estimates being biased toward zero
overfitting on the test set
class imbalance
missing values

40. What is the vanishing gradient problem and how do you fix it?

In deep networks, backpropagation multiplies many local derivatives. If each is below 1, as with sigmoid (max slope 0.25) and tanh in their saturated regions, the gradient shrinks exponentially toward early layers. Those layers barely learn.

Common fixes:

  • ReLU or variants (Leaky ReLU, GELU), which have slope 1 for active units
  • Proper initialization such as He or Xavier
  • Batch normalization to keep activations in a healthy range
  • Residual connections that give gradients a shortcut path
  • LSTM/GRU gates for recurrent networks

The opposite issue, exploding gradients, is handled with gradient clipping.

Take quiz
Which choice most directly helps with vanishing gradients?
stacking more sigmoid layers
using a smaller dataset
ReLU activations with proper initialization
removing the loss function
Residual connections help by:
giving gradients a shortcut path to earlier layers
reducing the number of classes
scaling the inputs
removing the need for weights

41. How do you detect and handle multicollinearity in linear regression?

Multicollinearity means predictors are highly correlated, so the model cannot tell which one deserves the credit. Predictions may stay fine, but coefficients become unstable with huge standard errors and flipping signs.

Detecting it: check the correlation matrix, compute the Variance Inflation Factor (VIF) for each feature (above 5-10 is a warning), or look at a large condition number.

Handling it:

  • Drop or merge redundant features
  • Combine correlated features into one (ratio, average)
  • Apply PCA to get uncorrelated components
  • Use ridge regression, which stabilizes coefficients by shrinking them

If you only care about prediction, mild multicollinearity is often acceptable. It matters most when you interpret coefficients.

Take quiz
A VIF above roughly 10 suggests:
underfitting
severe multicollinearity
missing labels
class imbalance
Which regularizer helps stabilize coefficients of correlated features?
dropout
early stopping
a larger learning rate
ridge (L2)

42. What is the difference between generative and discriminative models?

A discriminative model learns the boundary or P(y|x) directly. A generative model learns how the data is produced, P(x, y) = P(x|y) P(y), then uses Bayes' rule to classify.

Aspect Discriminative Generative
Learns P(y|x) or a decision boundary P(x|y) and P(y)
Examples logistic regression, SVM, neural net classifiers Naive Bayes, GMM, LDA, HMM
Can generate new samples no yes
Accuracy with lots of data often higher often lower
Small data / missing values less robust often handles better

If you only need predictions and have plenty of labeled data, a discriminative model is usually the better pick.

Take quiz
Which of these is a generative model?
Naive Bayes
logistic regression
SVM
a linear decision boundary only
Discriminative models learn:
the joint distribution P(x, y) first
cluster centroids
P(y|x) or the decision boundary directly
only feature means

43. How do you handle class imbalance in classification algorithms?

Start by fixing the metric. On 99:1 data, a model that always predicts the majority class scores 99% accuracy, so use precision, recall, F1, or PR-AUC instead.

Then choose a technique at the data, algorithm, or decision level:

Level Technique
Data random oversampling, undersampling, SMOTE (synthesizes minority points by interpolating neighbors)
Algorithm class_weight='balanced', focal loss, cost-sensitive learning
Decision tune the probability threshold on a validation set

Apply resampling only inside the training fold. Resampling before the split leaks synthetic copies into validation and inflates scores.

Take quiz
Which metric is more informative than accuracy on a 99:1 dataset?
plain accuracy
mean squared error
the silhouette score
precision-recall metrics such as F1 or PR-AUC
SMOTE works by:
duplicating majority rows
synthesizing new minority samples by interpolating between neighbors
dropping all features
reversing the labels

44. When would you choose a decision tree over logistic regression?

Choose a tree when the relationship between features and target is non-linear or involves interactions that logistic regression would need hand-crafted features to capture.

Situation Better pick
Non-linear patterns, feature interactions decision tree
Mixed numeric and categorical features, little preprocessing decision tree
Need explicit if-then rules decision tree
Mostly linear signal, small dataset logistic regression
Need smooth, calibrated probabilities and coefficients logistic regression
Many sparse features (e.g. text) logistic regression

A single tree is unstable, so in practice you often move to a random forest or boosted trees. Trees also need no feature scaling, while regularized logistic regression does.

Take quiz
A tree is the better choice when:
the signal is purely linear with tiny data
you need coefficient-based log-odds
the data has non-linear interactions and you want if-then rules
features are extremely sparse text
Which of these needs no feature scaling?
a decision tree
regularized logistic regression
KNN
an RBF SVM

45. What happens when you increase k in KNN?

Increasing k smooths the decision boundary: bias goes up and variance goes down.

  • k = 1 - boundary follows every point, including noise, so the model overfits (low bias, high variance).
  • Moderate k - neighbors vote, so single noisy points matter less.
  • k close to n - every prediction approaches the overall majority class, so the model underfits.

Prediction also gets slightly slower with larger k. Pick k with cross-validation, and use an odd k for binary problems to avoid tie votes. Distance weighting is another option, letting closer neighbors count more.

Take quiz
k = 1 in KNN typically gives:
high bias and low variance
a perfectly smooth boundary
low bias and high variance
no sensitivity to noise
As k approaches the number of training samples, predictions tend toward:
the overall majority class
a perfect fit
random labels
the nearest single point

46. How does AdaBoost update sample weights?

AdaBoost starts with every sample weighted equally (1/N) and uses each round to push attention onto the examples the last weak learner got wrong.

  1. Train a weak learner (often a depth-1 stump) on the weighted data.
  2. Compute its weighted error e.
  3. Compute its vote weight alpha = 0.5 * ln((1 - e) / e).
  4. Multiply weights of misclassified samples by exp(alpha) and correct ones by exp(-alpha).
  5. Normalize the weights so they sum to 1 and repeat.

The final prediction is a weighted vote of all learners. A learner with lower error gets a larger alpha. AdaBoost is sensitive to noisy labels, since mislabeled points keep gaining weight.

Take quiz
After each round, AdaBoost:
decreases the weights of misclassified samples
increases the weights of misclassified samples
removes the features used
resets all weights to zero
A weak learner with lower error receives:
a smaller alpha
the same alpha as all others
no vote at all
a larger alpha (more voting power)

47. Explain the internal working of the Expectation-Maximization algorithm for Gaussian Mixture Models?

A Gaussian Mixture Model assumes the data comes from several Gaussians, but you do not know which point came from which. EM solves this chicken-and-egg problem by alternating between guessing memberships and refitting parameters.

flowchart TD
  A["Initialize means, covariances, weights"] --> B["E-step: compute responsibilities<br/>probability of each component per point"]
  B --> C["M-step: update means, covariances, mixing weights<br/>using responsibilities"]
  C --> D{Log-likelihood<br/>converged?}
  D -- no --> B
  D -- yes --> E["Final GMM"]
  • E-step - for each point, compute the posterior probability (responsibility) that each Gaussian produced it.
  • M-step - recompute each Gaussian's mean, covariance, and mixing weight as responsibility-weighted statistics.

Each iteration never decreases the log-likelihood, but EM can land in a local optimum, so you run several initializations (k-means is a common starting point). Compared with k-means, GMM gives soft assignments and elliptical clusters.

Take quiz
The E-step computes:
the responsibilities, meaning each component's probability of generating each point
new tree splits
hard centroid labels only
the gradient of a neural network
EM guarantees that each iteration:
finds the global optimum
removes the need for initialization
does not decrease the log-likelihood, though it may reach a local optimum
increases the number of components

48. How does Q-learning differ from SARSA?

Both learn action values, but they bootstrap from different next actions. Q-learning uses the best possible next action (max Q(s', a')); SARSA uses the action the agent actually takes next (Q(s', a')).

Aspect Q-learning SARSA
Policy type off-policy on-policy
Update target r + gamma * max Q(s', a') r + gamma * Q(s', a')
Learns optimal policy, ignoring exploration value of the policy it follows, exploration included
Risky environments can take risky optimal paths tends to learn safer paths

The classic cliff-walking example shows it: Q-learning hugs the cliff edge because the optimal path is shortest, while SARSA stays further away since it accounts for random exploratory steps that might fall off.

Take quiz
The SARSA update uses:
the maximum over all next actions
a random label
the cluster centroid
the next action actually taken by the policy
In cliff walking, which method tends to learn the safer path?
Q-learning
SARSA
neither, both are identical
k-means

49. Which is better and why: random forest or gradient boosting?

Neither wins everywhere. Gradient boosting usually reaches higher accuracy on tabular data when tuned, while random forest is more forgiving and easier to get right.

Aspect Random forest Gradient boosting
Training parallel trees sequential trees
Tuning effort low, good defaults higher: learning rate, depth, trees
Overfitting resistant needs early stopping
Noisy labels robust more sensitive
Peak accuracy good often better
Training speed scales well across cores slower, though LightGBM is fast

Use random forest as a quick, strong baseline. Move to gradient boosting when you need the last few points of accuracy and have time to tune.

Take quiz
Which is typically a quick, strong baseline needing little tuning?
a heavily tuned gradient boosting model
KNN with k = 1
random forest
an unpruned single tree
Which trains its trees independently, so they can be built in parallel?
random forest
gradient boosting
AdaBoost
Q-learning

50. How does self-attention work in a transformer?

Self-attention lets every token look at every other token in the sequence and decide how much each one matters when building its own representation.

flowchart LR
  X["Token embeddings"] --> Q["Queries Q"]
  X --> K["Keys K"]
  X --> V["Values V"]
  Q --> S["Scores = Q K^T / sqrt d_k"]
  K --> S
  S --> W["Softmax weights"]
  W --> O["Weighted sum of V"]
  V --> O
  1. Project each token into a query, key, and value vector using learned matrices.
  2. Score every query against every key with a dot product.
  3. Divide by sqrt(d_k) so large dot products do not push softmax into saturation.
  4. Apply softmax to get attention weights, then take the weighted sum of the values.

Multi-head attention runs several of these in parallel so different heads can capture different relationships. The cost grows quadratically with sequence length, which is why long contexts are expensive.

Take quiz
Dividing scores by sqrt(d_k) is done to:
reduce the vocabulary size
shuffle the tokens
keep dot products from growing so softmax does not saturate
normalize labels
Self-attention cost scales with sequence length roughly:
quadratically
linearly
as a constant
logarithmically only
«
»

Comments & Discussions