Machine Learning
2. Classification I: logistic regression, k-nearest neighbour, naive Bayes
Despite its name, logistic regression is a classifier: it models P(y=1 | x) as the sigmoid of a linear combination of the predictors, and is trained by maximising likelihood (equivalently, minimising cross-entropy loss) rather than by least squares. k-nearest neighbour classifies a new point by a majority vote among the k closest labelled points in the training set, by some distance metric — it does no explicit training at all (a 'lazy' learner), pushing all the work to prediction time, and its cost per prediction scales with the size of the training set rather than with model complexity.
Naive Bayes applies Bayes' theorem to classification with one simplifying ('naive') assumption: every feature is conditionally independent of every other, given the class. That assumption is rarely exactly true, but it reduces estimating one large joint distribution to estimating several small per-feature distributions, which is cheap, needs little training data, and in practice classifies well even when the independence it assumes is visibly violated.
3. Classification II: linear discriminant analysis, support vector machine, decision trees
Linear discriminant analysis (LDA) finds the linear combination of features that best separates the classes — maximising the ratio of between-class scatter to within-class scatter — under the assumption that classes are (approximately) normally distributed and share a common covariance matrix. Where that assumption holds, LDA can outperform logistic regression, and it doubles as a dimensionality-reduction technique, projecting data onto the directions that best discriminate the classes rather than, as PCA does, the directions of highest variance regardless of class.
A support vector machine (SVM) finds the hyperplane that separates the classes with the maximum margin — the widest possible gap to the nearest point of either class. Only the points exactly on that margin, the support vectors, determine where the hyperplane sits; every other correctly classified point could be moved or removed without changing it at all. The kernel trick lets an SVM find a nonlinear boundary in the original feature space by implicitly computing distances as if the data had been mapped into a much higher-dimensional space, without ever constructing that mapping explicitly.
A decision tree recursively splits the feature space on the attribute and threshold that most reduces impurity (measured by Gini impurity or entropy) at each node, until a stopping rule is reached. It is easy to read off as a set of rules, but a tree grown to full depth on the training data fits its noise as readily as its signal — low training error paired with much higher variance on unseen data — which is why depth limits and pruning are the standard countermeasure.
4. Bias-variance trade-off, cross-validation, and the multi-layer perceptron
A model's expected prediction error on new data decomposes into three parts: bias (error from a model too simple to capture the true relationship — underfitting), variance (error from a model sensitive enough to fit the training data's noise — overfitting), and irreducible noise (error no model can remove). Increasing model complexity generally lowers bias and raises variance, so the two trade against each other rather than both improving together, and the goal is the complexity that minimises their sum, not either one alone.
Cross-validation estimates out-of-sample error without setting aside a separate, never-touched test set for that purpose alone. k-fold cross-validation splits the data into k roughly equal folds, trains on k-1 of them and validates on the remaining one, repeats this k times so every fold serves as the validation set exactly once, and averages the k error estimates. Leave-one-out (LOO) cross-validation is the extreme case k = n: it trains on all but one example, n times over, giving an estimate with very low bias but higher variance across folds and a training cost of n full model fits — expensive on a large dataset, though it uses almost all the data for training on every single fold.
A multi-layer perceptron (a feed-forward neural network) stacks layers, each a weighted sum of the previous layer's outputs passed through a nonlinear activation function; with even a single hidden layer of sufficient width, it can approximate any continuous function on a compact domain to arbitrary accuracy — the universal approximation property. It is trained by backpropagation: the chain rule applied layer by layer to compute how the loss changes with each weight, feeding a gradient-descent update.
5. Unsupervised learning I: clustering
k-means partitions data into k clusters by iterating two steps: assign every point to its nearest cluster centroid, then recompute each centroid as the mean of the points now assigned to it — repeated until assignments stop changing. It converges, but only to a local optimum that depends on the initial centroid positions, and because it uses the mean it is pulled noticeably by outliers. k-medoid does the same two-step iteration but restricts a cluster's centre to be an actual data point (the medoid) rather than a computed mean, which is more robust to outliers at the cost of a more expensive search for the best medoid at each step.
Hierarchical clustering builds a full tree of nested clusters (a dendrogram) without requiring k in advance — the number of clusters is chosen afterward by cutting the tree at a chosen height. Agglomerative (bottom-up) clustering starts with every point as its own cluster and repeatedly merges the closest pair; divisive (top-down) clustering starts with one cluster containing everything and repeatedly splits the least cohesive one.
| Linkage | Distance between two clusters | Tendency |
|---|---|---|
| Single-linkage | Minimum distance between any pair, one point from each cluster | Can chain distant clusters together through a sequence of close points |
| Complete-linkage (multiple-linkage) | Maximum distance between any pair, one point from each cluster | Produces more compact, roughly equal-sized clusters |
6. Unsupervised learning II: dimensionality reduction and principal component analysis
Dimensionality reduction re-expresses data in fewer dimensions while keeping as much of its structure as possible, both to fight the curse of dimensionality (distances between points become less meaningful as dimensions grow, and the amount of data needed to fill a space grows exponentially with it) and to make high-dimensional data visualisable at all.
Principal component analysis (PCA) finds the orthogonal directions of maximum variance in the data, ranked from most to least variance explained; these principal components are the eigenvectors of the data's covariance matrix (equivalently obtainable via the singular value decomposition of the data matrix), and keeping only the first few of them — the ones that explain most of the total variance — is what actually achieves the reduction, discarding the rest with the least possible loss of information as measured by variance.
Key takeaways
- Ridge regression adds an L2 penalty that shrinks every coefficient toward zero, trading a little bias for reduced variance when predictors are numerous or correlated — but it never sets a coefficient to exactly zero.
- Logistic regression, k-NN and naive Bayes reach classification three different ways — a parametric probability model, a lazy distance-based vote, and Bayes' theorem plus a conditional-independence assumption — and only the support vectors on an SVM's margin determine its boundary.
- Model complexity trades bias against variance; k-fold cross-validation, and its extreme case leave-one-out, estimate out-of-sample error without setting aside a separate held-out set.
- A feed-forward neural network with even one sufficiently wide hidden layer can approximate any continuous function, trained by backpropagating the loss's gradient layer by layer.
- k-means and k-medoid both assume roughly spherical clusters and need k fixed in advance; hierarchical clustering needs no k in advance, but its shape depends heavily on whether the linkage rule is single (chains) or complete (compact).
- PCA finds the directions of maximum variance from the covariance matrix's eigenvectors and is entirely unsupervised — it can discard the very direction that would best separate classes, which only a supervised technique like LDA looks for.
Practice questions (23)
Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.
Ridge regression differs from ordinary least-squares linear regression chiefly by adding, to the objective being minimised,
Show answer
Answer: B — an L2 penalty on the coefficients
Ridge regression adds λΣβᵢ², the squared (L2) magnitude of the coefficients, to the least-squares objective, shrinking them toward zero.Logistic regression is used for
Show answer
Answer: B — classification, via a probability estimated by the sigmoid function
Despite its name, logistic regression is a classifier: it models P(y=1|x) as the sigmoid of a linear combination of the predictors.Using k = 1 in k-nearest neighbour classification, compared with a larger k, tends to give
Show answer
Answer: B — low bias and high variance, since a single noisy neighbour can flip the prediction
With k=1 the prediction at any point depends entirely on the single nearest training example, which fits the training data closely (low bias) but makes the prediction highly sensitive to noise in that one neighbour (high variance).The naive Bayes classifier makes which simplifying assumption?
Show answer
Answer: B — Features are conditionally independent of each other, given the class
The 'naive' in naive Bayes is exactly this conditional-independence assumption, which lets a joint distribution be approximated from independent per-feature distributions.Which of the following are true of a support vector machine's maximum-margin hyperplane?
Show answer
Answer: A — It is determined only by the support vectors sitting on the margin boundary; C — The kernel trick allows a nonlinear decision boundary without explicitly computing the higher-dimensional features; D — Soft-margin SVM training is a convex optimisation problem
A point well outside the margin, correctly classified, contributes nothing to the hyperplane and can be moved or removed without effect — the second option is the false one; the other three are standard properties of the SVM formulation.Linear discriminant analysis (LDA), compared with logistic regression, additionally assumes
Show answer
Answer: B — classes share a common covariance matrix and features are approximately normal within each class
LDA's derivation assumes classes are approximately normally distributed with a shared covariance matrix, an assumption logistic regression does not need to make.A decision tree grown to full depth on the training data, with no pruning, typically
Show answer
Answer: C — overfits — low training error, but higher variance and worse accuracy on unseen data
A fully grown tree fits the training data's noise as readily as its signal, giving low training error but higher variance and worse generalisation — the standard reason for depth limits and pruning.In the bias-variance decomposition of expected prediction error, a model that is too simple to capture the true relationship suffers mainly from
Show answer
Answer: B — high bias
An overly simple model underfits consistently, regardless of which training sample it saw — that consistent, systematic error is exactly what bias measures.In 5-fold cross-validation on a dataset of 100 examples, split into equal folds, how many examples are used for validation in each single fold?
Numerical answer — type the value.
Show answer
Answer: 20
100 examples split into 5 equal folds gives 20 examples per fold, and one fold at a time is held out for validation.Leave-one-out cross-validation is the special case of k-fold cross-validation in which
Show answer
Answer: C — k equals the number of training examples, n
LOO trains on all but one example and validates on that one, repeated n times over — exactly k-fold cross-validation with k = n.A feed-forward neural network with a single hidden layer of sufficient width can, by the universal approximation property,
Show answer
Answer: B — approximate any continuous function on a compact domain
The universal approximation property states that a single sufficiently wide hidden layer, with a nonlinear activation, can approximate any continuous function on a compact domain to arbitrary accuracy.At every iteration, k-means updates each cluster's centre to the
Show answer
Answer: B — mean of the points currently assigned to that cluster
k-means recomputes each centroid as the arithmetic mean of the points currently in its cluster, which is also why it is pulled by outliers.Compared with k-means, k-medoid clustering is generally
Show answer
Answer: B — more robust to outliers, at a higher computational cost
Using an actual data point (the medoid) instead of the mean as a cluster centre resists the pull of outliers, but searching for the best medoid at each step costs more than simply averaging points.Single-linkage hierarchical clustering defines the distance between two clusters as
Show answer
Answer: C — the minimum distance between any pair, one point from each cluster
Single-linkage takes the closest pair of points across the two clusters as the inter-cluster distance, which is what lets it chain distant clusters together through a sequence of close points.Compared with complete-linkage, single-linkage hierarchical clustering is more prone to
Show answer
Answer: B — the 'chaining' effect, where a sequence of close points links otherwise distant clusters
Because single-linkage only needs one close pair to merge two clusters, a chain of near-neighbours can link clusters that are otherwise far apart overall — the defect complete-linkage's max-distance rule avoids.Which clustering technique does NOT require the number of clusters k to be fixed before it runs?
Show answer
Answer: C — Hierarchical clustering
Hierarchical clustering builds the full dendrogram first and only afterward chooses how many clusters to read off by cutting it at a chosen height; k-means and k-medoid both need k as an input before they start.Principal component analysis re-expresses data along directions of
Show answer
Answer: B — maximum variance
PCA's principal components are ranked directions of decreasing variance in the data, found without any reference to class labels.The principal components produced by PCA are computed from
Show answer
Answer: A — the eigenvectors of the data's covariance matrix
The principal components are the eigenvectors of the covariance matrix, equivalently obtainable from the singular value decomposition of the (centred) data matrix.Before applying PCA to features on very different numeric scales — say income in rupees and age in years — standard practice is to
Show answer
Answer: B — standardize the features first, so no feature dominates purely due to its units
Since PCA ranks directions purely by variance, a feature with naturally larger numeric values dominates that variance for no substantive reason unless every feature is first standardized to a common scale.Reducing a dataset's dimensionality before feeding it to a distance-based classifier such as k-NN chiefly helps by
Show answer
Answer: B — mitigating the curse of dimensionality, where distances become less meaningful as dimensions grow
In very high dimensions, distances between points become less discriminating (the curse of dimensionality), and dimensionality reduction is one standard way to counter that before a distance-based method like k-NN is applied.In ridge regression, as the penalty weight λ is increased toward infinity, the fitted coefficients tend toward
Show answer
Answer: B — all zero, giving a constant-mean model
As λ grows, the penalty on the coefficients' size dominates the objective more and more, shrinking every coefficient toward zero — in the limit, the model predicts only the mean response.Which of the following are true of naive Bayes and k-nearest neighbour?
Show answer
Answer: A — k-NN performs no explicit training phase, pushing the work to prediction time; B — Naive Bayes estimates a joint distribution from independent per-feature distributions
k-NN's prediction cost actually grows with training-set size, since it must find the nearest neighbours among all of it, and naive Bayes classifies well in practice even when its independence assumption is visibly violated — the third and fourth options are the false ones.Running k-means several times from different random initial centroids and keeping the best result mainly helps because
Show answer
Answer: B — k-means converges only to a local optimum, which depends on the initial centroids
k-means only guarantees convergence to A local optimum, and which one depends on where the centroids started — running it multiple times and keeping the best (lowest within-cluster variance) result is the standard way to reduce this sensitivity.