















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
















A topic-by-topic guide covering dimension reduction, clustering, regression, regularization, classification, support vector machines, tree-based models, and neural networks. Original study notes — independently written summary and explanation
avoid data leakage — this transformation must be fit only on training data within a properly constructed pipeline.
Many ML models are strongly affected by the scale or distribution of the input data, so transformations are often applied first — for example, a log transform to reduce the skew of long-tailed raw data. Common choices include power transformations (e.g. the Yeo-Johnson transformation), standardisation, and min-max scaling. Higher-dimensional feature spaces can also be built deliberately, by adding interaction terms or nonlinear combinations of existing features, to enrich what a linear model can capture.
Given a labelled training dataset D = {(x , y )} for n = 1, ..., N, with N training examples, theₙ ₙ general aim is to learn the mapping from x to y well enough to generalise — that is, to correctly label future, unseen inputs x*.
A typical end-to-end project moves through: problem definition → data collection → exploratory data analysis (EDA) → pre-processing → a decision point (feature engineering manually, or moving toward dimension reduction) → model training → evaluation/validation → (if the model isn't good enough) further tuning or feature work, looping back as needed → a final test → model deployment → ongoing performance monitoring, which in turn can loop all the way back to problem definition as new needs emerge.
In unsupervised learning, only the features are observed — not the labels. Dimension reduction addresses a common situation: when the number of features D is very large, and many of those features are highly correlated or repetitive, is there an informative way to visualise and/or summarise the data with fewer numbers? Formally, dimension reduction aims to learn a mapping from the high-dimensional space of observed features, x ∈ ℝᴰ, to a low-dimensional latent space, z ∈ ℝᴸ (with L < D), that captures most of the information in the data.
PCA is the simplest and most widely-used form of dimensionality reduction. Its aim is to find a linear, orthogonal projection of the high-dimensional x into a low-dimensional z that provides a good approximation by explaining most of the variability in the data. Let W be a D×L orthonormal matrix (columns w₁, ..., wL), meaning w ᵀw = 1 for each columnₗ ₗ (normalised) and w ᵀw = 0 for k ≠ l (orthogonal).ₖ ₗ
PCA minimises the average reconstruction error, subject to W being orthonormal: L(W, Z) = (1/N) Σ ₙ ‖x ₙ − Wz ‖²ₙ Step 1 — optimal encoding: taking the gradient of the loss with respect to z ₙand setting it to zero gives z ₙ = Wᵀx , confirming that the encoder defined above is in fact optimal given W.ₙ Step 2 — optimal W: substituting the optimal encoding back into the loss and simplifying (using the fact that WWᵀ is a projection matrix) shows that minimising the reconstruction error is equivalent to maximising Σ w ᵀΣw , where Σ = (1/N)XᵀX is the empirical covarianceₗ ₗ ₗ matrix (assuming the data has been centred so xZ = 0). Solving this one basis vector at a time via Lagrange multipliers (maximising w ᵀΣw subject toₗ ₗ w ᵀw = 1, and orthogonality to all previously-found vectors) shows, after taking derivativesₗ ₗ and pre-multiplying by w ᵀ, that each w must be an eigenvector of Σ, with the correspondingₗ ₗ eigenvalue λ equal to w ᵀΣw itself. Because the goal is to maximise this quantity, the firstₗ ₗ ₗ principal component w₁ is the eigenvector of Σ with the largest eigenvalue; the second, w₂, is constrained to be orthogonal to w₁ and turns out to be the eigenvector with the second- largest eigenvalue, and so on. Geometrically, the vectors w₁, ..., wL can be thought of as the dominant patterns in the data — the directions along which the data varies the most.
PCA results will be dominated by whichever features have the highest variance, so data is typically standardised first. An exception: if all features already share the same units, it can be appropriate not to standardise, since scale differences may carry genuine meaning.
Clustering broadly aims to find groups of data points that are similar to one another. Unlike classification, in clustering neither the label of each data point nor the number of classes is known in advance — both must be learned from the data. Both clustering and PCA share the same broad goal of simplifying data down to a small number of summaries, just via different mechanisms.
The starting point for any clustering method is defining a dissimilarity Dᵈ(x ,d, x ′,d) betweenₙ ₙ two observations, for each feature d.
An alternative strategy defines dissimilarity as a single function of all features jointly, rather than summing per-feature terms. Cosine dissimilarity is D(x ,x ′) = 1 − S(x ,x ′), where S isₙ ₙ ₙ ₙ the cosine of the angle between the two vectors. If the angle θ = 0° the dissimilarity is 0; if θ = 90° the dissimilarity is 1. Worked example (market basket analysis) — four customers' purchase quantities of apples and bananas. Customers 1 and 3 bought small, proportionally similar quantities of different products (mostly apples vs mostly bananas respectively), so cosine similarity treats them as dissimilar (different direction in feature space) despite both having "small" total purchases — illustrating that cosine dissimilarity captures the pattern/direction of a customer's behaviour rather than the magnitude. Correlation dissimilarity centres each observation's own values before comparing, so it captures similarity in relative pattern across features even when the overall scale differs substantially between observations.
Let K denote the number of clusters. A clustering assignment C = (C₁, ..., CK) partitions the N observations into K non-overlapping groups. The goal is to find the clustering C that minimises a loss function based on the chosen dissimilarity — the total within-cluster variation: L(C) = Σ ₖ W(C )ₖ
K-means is one of the most widely-used clustering algorithms, and the simplest to implement. The goal is to find C minimising: L(C) = Σ ₖ (1/|C |) Σ(n,n′ₖ ∈C ) ‖x ₖ ₙ − x ′‖² = 2 Σₙ ₖ Σ(n ∈C ) ‖x ₖ ₙ − x*ₖ ‖² where xZ ₖis the sample mean vector within cluster k, across all features. This equivalence — between the sum of all pairwise squared distances within a cluster, and the sum of squared distances to the cluster mean — can be shown directly by expanding (x ,d − x ′,d)² aroundₙ ₙ the cluster mean and simplifying.
K-means needs to be initialised, and a poor initialisation can lead to a poor final clustering. K-means++ initialises the centroids sequentially (not the labels): the first centroid is chosen uniformly at random from the data points; each subsequent centroid is chosen from the remaining points with probability proportional to its squared distance from the nearest centroid already chosen. This biases initialisation toward spreading the initial centroids out, which tends to give better final clusterings than fully random initialisation.
The choice of K can have a strong impact and depends on the problem. Common approaches include plotting the within-cluster variation against K and looking for an elbow, or silhouette analysis (for K > 1). Silhouette analysis defines, for each observation: the average dissimilarity to every other cluster (giving the within-cluster and between-cluster dissimilarities), from which a silhouette score s(xᵢ) = 1 − a/b is computed (where a is the mean within-cluster dissimilarity and b is the mean dissimilarity to the nearest other cluster). A score close to 1 indicates the point is well-classified; close to 0 indicates it sits between clusters; close to −1 suggests it may be misclassified into the wrong cluster.
K-medoids extends the K-means idea to work with any choice of dissimilarity (not just squared Euclidean distance), by iterating between: (1) finding each cluster's medoid — the point within the cluster minimising the total dissimilarity to all other points in that same cluster (for squared Euclidean distance, this recovers the mean exactly; for a general dissimilarity, the search is restricted to the actual data points within the cluster); and (2) reassigning each point to the cluster of its nearest medoid. Computational complexity: finding a mean (step 1 under squared Euclidean distance) is O(N) per cluster, giving O(N) overall; finding a general medoid requires comparing every pair of points within a cluster, giving O(N²) overall — meaningfully more expensive for large datasets.
Hierarchical clustering partially alleviates the problem of having to choose a fixed number of clusters upfront, by building either an agglomerative (bottom-up) or a divisive (top-down) hierarchy of clusterings, typically visualised as a dendrogram. This hierarchy is built using a linkage criterion that defines the dissimilarity between two whole clusters (rather than two individual points):
Much of ML is about fitting functions to data. In regression tasks, linear regression is widely used and assumes a simple linear form: y = wᵀx + ε = Σᵈ wᵈxᵈ + ε where w are the regression weights, ε is the residual error, and w₀ (the intercept, folded in via a constant feature) is the bias term. Linear regression has two aims: (1) learn the mapping from x to y — in practice, this means learning an estimate ŵ of w from the training data — and (2) generalisation: predicting for unseen inputs x* via ŷ* = ŵᵀx*.
Minimising the least squares criterion is the most common way to estimate w. The residual sum of squares (RSS) is: RSS(w) = Σ ₙ ε ² = Σₙ ₙ (y ₙ − wᵀx )² = (y − Xw)ᵀ(y − Xw) = yᵀy − 2yᵀXw + wᵀXᵀXwₙ Taking the gradient with respect to w and setting it to zero gives the normal equations, XᵀXw = Xᵀy, so: ŵ = (XᵀX) ¹Xᵀy⁻ This requires XᵀX to be invertible, which in turn requires X to have full column rank (D+1). A common way this fails in practice: one-hot encoding a categorical variable using all C dummy columns (rather than C−1) makes the design matrix rank-deficient, since the dummy columns then sum to the intercept column exactly — meaning infinitely many values of w fit the data equally well.
Polynomial regression is a simple extension, assuming polynomial basis functions φ ₘ(x) = xᵐ, with weights again estimated by least squares: ŵ = (ΦᵀΦ) ¹Φᵀy. Arbitrarily large M gives⁻ increasingly nonlinear fits, but larger M does not always lead to a better fit on new data.
Overfitting occurs when a model starts capturing minor variations that are really just due to noise, rather than genuine underlying structure. The mean squared error (MSE) measures how closely predictions match the observed outputs on the training data: MSE = (1/N) Σ ₙ (y ₙ − f̂^6 (x ))²ₙ Generally, MSE decreases as model complexity (e.g. polynomial order M) increases — but this is measuring fit to the training data, which is a poor guide to how well the model will generalise.
Writing the true relationship as y = f(x) + ε and a prediction as ŷ* = fX(x), prediction accuracy decomposes as: _y − ŷ* = [f̂ (x) − f̂_^6 _(x)] + ε*_ The first term is the reducible error — the discrepancy between the true function f and the estimated function fX, which can in principle be reduced by a better model or more data. The
second term is the irreducible error — inherent noise in the data (the residual ε), which no model can eliminate. This tradeoff underlies the classic picture of underfitting vs. overfitting: as model complexity increases, training error keeps falling, but test and validation error initially fall, reach a minimum, and then rise again as the model starts fitting noise rather than signal. The best- performing model, in terms of genuine generalisation, sits at that minimum.
The golden rule of ML: never train on the test data — doing so causes data leakage and gives a misleadingly optimistic estimate of performance. Instead, split the data into a training set (used to fit and estimate the model) and a validation set (used to select between competing models or hyperparameters). This split should happen before EDA — very early in the pipeline, to avoid any information about the test set leaking into modelling decisions. A common approach is an 80/20 split for training/validation, or an 80/10/10 split for training/validation/test if a genuinely held-out test set is also needed.
K-fold cross-validation randomly splits the training data into K folds; for each fold k = 1, ..., K, the model is validated on that fold while training on the remaining K−1 folds. Popular choices of K are 5 or 10. Leave-one-out cross-validation (LOO-CV) is the special case K = N: the model is trained leaving out exactly one data point, and validated on that held-out point, repeated for every point in the dataset. The goal of cross-validation is to locate the genuine minimum of the test error curve — using cross-validation to estimate that curve well enough to choose between models or hyperparameters reliably.
(where RSS is the residual sum of squares and TSS is the total sum of squares). It is good practice to compare any candidate model against a set of simple baseline models — "keep it simple" as a starting benchmark before investing in complexity.
Suppose we simply want to estimate a population mean μ and variance σ² from data D = {y }. The natural estimators areₙ μX = ȳ (the sample mean) and σX² = (1/(N−1))Σ (y −ȳ)².ₙ ₙ Using the properties V(aX) = a²V(X) and, for independent X and Y, V(X+Y) = V(X)+V(Y), the variance of the sample mean estimator can be derived directly: V(μX) = σ²/N, giving the standard error SE(μX) = σX/√N. The Central Limit Theorem then justifies constructing confidence intervals using this standard error, since (μX−μ)/(σ/√N) is approximately standard normal for large enough N. The same logic extends to the regression weights: using V(AX) = AV(X)Aᵀ and substituting A = (XᵀX) ¹Xᵀ, the variance of ŵ works out to σ²(XᵀX) ¹. This in turn gives the standard error of⁻ ⁻ a prediction fX(x) = ŵᵀx: V(ŵᵀx) = σ²xᵀ(XᵀX) ¹x*.⁻ When the standard error can't be computed analytically (for more complex, data-driven models), the bootstrap offers a general alternative: repeatedly resample the training data with replacement (B bootstrap datasets), refit the model to each resample, and use the standard deviation of the resulting estimates as an empirical estimate of the standard error.
As with any regularized model, choosing a good value of λ is critical, and cross-validation provides a systematic way to do this: choose a grid of candidate λ values, compute the cross-validation error for each, and select the λ that minimises that error.
Ridge regression has an elegant Bayesian interpretation. Placing an independent Gaussian prior N(0, s²) on each weight, and a Gaussian likelihood N(x ᵀw, σ²) on each observation,ₙ the maximum a posteriori (MAP) estimate — maximising the log posterior over w — works out, after expanding the Gaussian log-densities and simplifying, to be exactly equivalent to minimising RSS plus a ridge penalty, with: λ = σ²/s² In other words, ridge regression is exactly the MAP estimate under a Gaussian prior on the weights — a smaller prior variance s² (a stronger prior belief that weights should be small) corresponds to a larger effective λ.
Lasso regression uses an L1 penalty instead, selecting ŵ to minimise: Σ (yₙ ₙ − wᵀx )² + λΣᵈ|wᵈ|ₙ The key practical difference from ridge: ridge shrinks weights toward zero but essentially never sets any of them exactly to zero, so all inputs remain in the final model. Lasso, by contrast, forces some weights to be exactly zero for a sufficiently large λ, so only a subset of inputs are included in the final model — giving lasso a built-in feature selection property. Lasso is a biased estimator — even large true weights get shrunk somewhat toward zero. A simple two-stage debiasing procedure addresses this: (1) use lasso to identify which weights are non-zero, then (2) re-estimate just those weights using ordinary least squares. For a correctly chosen λ, lasso is selection consistent: as N → ∞ (under appropriate assumptions), it recovers exactly the true set of relevant features.
Elastic net is a hybrid between lasso and ridge, with penalty pλ1,λ2(w) = λ₁|w| + λ₂w². It exhibits a grouping effect — coefficients of highly correlated variables tend to be estimated as similar to one another — and can select more than N non-zero inputs even when N is small, unlike lasso alone.
Sparse kernel machines use the training inputs themselves as the centroids, giving basis functions φ(x) = (1, k(x,x₁), ..., k(x,x ))ᵀ. Kernelized ridge regression applies the kernel trickₙ directly to ridge regression — rather than defining the feature vector explicitly, predictions and the model itself are rewritten to depend on the data only through kernel evaluations, following the same two-step kernel trick recipe described in Section 2: rewrite predictions to depend on inputs only through inner products, then replace every inner product with a kernel evaluation.
The Bayes classifier assigns the most likely class label. But false positives and false negatives are not always equally costly. Let lFP be the cost of a false positive and lFN the cost of a false negative, giving a loss function L(y, ŷ) = lFP· 𝟙(ŷ=1, y=0) + lFN· 𝟙(ŷ=0, y=1). Minimising the expected loss leads to a threshold decision rule: predict ŷ = 1 whenever p(y=1|x) > lFP/(lFP + lFN) =: τ When the two error types are equally costly, this threshold is τ = 0.5 — but the optimal threshold shifts away from 0.5 whenever one type of error is more costly than the other.
The ROC curve plots Recall (true positive rate) against the false positive rate (FPR), as an implicit function of the threshold τ. At the extremes: τ = 0 always predicts ŷ = 1 (Recall = 1, FPR = 1); τ = 1 always predicts ŷ = 0 (Recall = 0, FPR = 0). A purely random classifier that predicts ŷ = 1 with fixed probability τ, regardless of x, traces out the diagonal "chance level" line — genuinely useful classifiers sit above this diagonal, ideally hugging the top-left corner. The precision-recall curve plots precision (TP/(TP+FP)) against recall, again as an implicit function of τ — particularly useful when the classes are heavily imbalanced, since the ROC curve can look deceptively good in that setting.
Logistic regression models the probability of the positive class using the sigmoid function: p(y=1|x) = 1/(1 + exp(−wᵀx)) The decision boundary (p = 0.5) works out to exactly wᵀx = 0 — a linear decision boundary in x. The odds of the positive class are p(y=1|x)/p(y=0|x) = exp(wᵀx), so the log-odds (logit) are exactly linear in x: log[p(y=1|x)/p(y=0|x)] = wᵀx
Maximising the likelihood of the observed labels under the Bernoulli model leads, after taking logs, to the equivalent objective of minimising the binary cross-entropy loss: ŵ = argmin over w −Σ ₙ [y ₙ log(1+exp(−wᵀx )) + (1−y ) log(1+exp(wᵀx ))]ₙ ₙ ₙ
For more than two classes, the multinomial extension models the probability of each class c via the softmax function: p(y=c|x) = exp(wcᵀx) / Σc′ exp(wc′ᵀx) A subtlety: this parameterisation is non-identifiable — adding any constant vector a to every wc leaves every predicted probability completely unchanged, since the a-dependent terms cancel exactly between numerator and denominator. In practice this is resolved by fixing one class's weight vector (commonly to zero) as a reference.
Support Vector Machines (SVMs) provide a geometric approach to binary classification. Consider a separating hyperplane w₀ + wᵀx = 0, with observations labelled y ₙ ∈{−1, +1} such that w₀+wᵀx ₙ > 0 when y =1 and w₀+wᵀxₙ ₙ < 0 when y =−1. The decision boundary isₙ f(x) = 0, with predictions y* = sign(f(x)); the magnitude of f(x) reflects the model's confidence in that prediction. The (signed) distance r from a point x to the hyperplane satisfies w₀+wᵀx = r‖w‖, so r = (w₀+wᵀx)/‖w‖ — positive for points on the y=1 side, negative on the y=−1 side. The margin is defined as the smallest such (correctly-signed) distance across all training points: margin = min ₙ y (w₀+wᵀx )/‖w‖. Since (w₀,w) and any rescaling (cw₀,cw) define theₙ ₙ exact same hyperplane and the exact same margin, uniqueness requires an extra constraint — commonly, that the smallest value of y (w₀+wᵀx ) across all training points equals exactlyₙ ₙ
The Support Vector Classifier (SVC) generalises the maximal margin classifier by allowing a soft margin. Slack variables ε ₙ≥ 0 are introduced, relaxing the hard constraints to y (w₀+wᵀx ) ≥ 1−ε. The objective becomes minimising ‖w‖² + C·Σ ε , subject to those softₙ ₙ ₙ ₙ ₙ constraints and ε ₙ≥ 0 for every n, where C ≥ 0 is a tuning parameter controlling the trade-off between margin width and constraint violations. Equivalently, this can be minimised as (1/C)‖w‖² + Σ ε , exposing that minimising the ridge-ₙ ₙ style objective plus the sum of slacks is the same problem viewed from a different scaling of the tuning parameter.
The SVC objective can equivalently be written using the hinge loss, L ₙ = max(0, 1−y f(x)) —ₙ the slack variable ε ₙis precisely this hinge loss for point n. Platt scaling is a common heuristic for converting the (unbounded, unitless) SVM output into a genuine probability, by fitting a logistic function of the raw decision value: p(y=1|x,w) = 1/(1+exp(a+b(w₀+wᵀx))).
Introducing Lagrange multipliers α ₙ ≥ 0 and μ ₙ≥ 0, the generalized Lagrangian is: L(w₀,w,ε,α,μ) = wᵀw + C·Σ εₙ ₙ − Σ ₙ α [y (w₀+wᵀx )−1+ε ] − Σₙ ₙ ₙ ₙ ₙ μ εₙ ₙ Taking the gradient with respect to w and setting it to zero gives w = (1/2)Σ ₙ α y xₙ ₙ ₙ — expressing the optimal w entirely in terms of a weighted sum of the training inputs. Substituting into the decision function reveals that predictions depend on the inputs only through their inner products, f(x) = w₀ + (1/2)Σ ₙ α yₙ ₙ⟨ ₙ x ,x ⟩— precisely the structure needed for the kernel trick. The dual formulation also reveals that α ₙ> 0 only for points lying exactly on (or violating) the margin — the support vectors — while α ₙ= 0 for every other point. This means the decision boundary is determined entirely by the support vectors, not by the full training set. Because everything depends only on inner products, the kernel trick extends SVMs directly to nonlinear decision boundaries, by replacing every inner product with a kernel evaluation
— commonly the polynomial kernel or the RBF kernel introduced in Section 2, corresponding to a large, possibly infinite-dimensional, implicit feature expansion.
SVMs are inherently binary classifiers. Two common strategies extend them to multiclass problems:
Random forests overcome this with a small but effective trick to decorrelate the trees: at each split, only a random sample of M < D features is considered as candidates (rather than all D). A common default choice is M ≈ √D. This forces different trees to rely on different features, reducing the correlation between them and improving the variance-reduction benefit of averaging.
Unlike bagging (where models are trained independently, in parallel, on the same data via bootstrapping), boosting grows models sequentially, using a slow learning approach where each new model focuses on correcting the errors of the ensemble so far. Voting-based ensembles, more generally, combine predictions from several different models trained on the same data.
In logistic regression, a linear combination of the inputs is formed, a(x) = b + wᵀx, and passed through the sigmoid function φ(a) = 1/(1+e^(−a)), giving predictions f(x) ∈(0,1) — interpreted as the probability that the neuron "fires". A perceptron replaces the sigmoid with a Heaviside step function h(a) = 𝟙(a>0), giving a deterministic classifier f(x) = 𝟙(b+wᵀx > 0) — this is called the activation function, since the neuron "fires" (outputs 1) when the incoming weighted activity is large enough, and does not otherwise. A single perceptron cannot represent every function — the classic example is XOR, which is not linearly separable. Stacking multiple perceptrons on top of one another, as a multilayer perceptron (MLP), overcomes this. Worked example: XOR can be represented using two hidden units implementing the logical AND and OR functions respectively (each a perceptron with manually-constructed weights), followed by a combining output unit — demonstrating concretely how composing simple linear units with nonlinearities can represent a function no single linear unit can.
The general structure is: input layer x → L hidden layers z¹,...,zᴸ → output layer y. Collecting all biases and weights into θ = (b₁,W₁,...,bL+1,WL+1), the total number of parameters is: Σ(l=1)^{L+1} (D + D ·Dₗ ₗ ₗ₋₁) Worked example — for D₀=1, L=1, D₁=5, D(L+1)=1: total parameters = 5 + 5·1 + 1 + 1·5 =
A good activation function should be nonlinear (otherwise the whole network reduces to an equivalent linear model, regardless of depth) and differentiable (a Heaviside step function causes problems for gradient descent, since its gradient is zero almost everywhere).