Classical Machine Learning

These notes cover the classical core of machine learning — regression, classification and clustering — and follow one thread through all three. We first fit a line to data and understand the fit three ways — geometrically, analytically, and probabilistically. Then we bend the same machinery until the output is a probability rather than a number, and regression becomes classification. After that we take classification on its own terms — hyperplanes, margins, trees — learn how to grade a classifier, and finally remove the labels altogether and let the data group itself.

I — Linear Regression

The linear model is one of the simplest models in data science, and we use it as the starting point for several common ideas.

Least Square Problem

Suppose we have $n$ data points, $x_1,\cdots,x_n$, in $\mathbb{R}^p $, denote $$\mathbf{X} \in \mathbb{R}^{n\times p }$$ the matrix with entries given by $$\mathbf{X}_{i,j}=(x_i)_j$$ For each point, $x_i$, there is a corresponding output $y_i$; we denote the output vector by $$\mathbf{y} := \begin{pmatrix} y_1\\\vdots\\y_n \end{pmatrix}$$ Denote the design matrix $$X:=[\mathbf{X}|\mathbb{1}] \in \mathbb{R}^{n\times (p+1) }$$ The goal of a least-squares problem is to find the vector $\mathbf{\beta}\in \mathbb{R}^{p+1}$ that minimizes the Sum of Squared Error $$\mathrm{SSE}(w):=\|X w - \mathbf{y}\|_2^2 $$

Geometric Approach

Projection Matrix

We start with the geometric approach, the one I find most natural. Recall that we have the following minimization problem, $$\min_{w\in \R^{p+1}} \|X w - \mathbf{y}\|_2^2$$ The object $$Xw$$ lives in the column space of $X$, thus to minimize the above squared distance, we only need to require $Xw= \widehat{\mathbf{y}}$ where $ \widehat{\mathbf{y}}$ is the projection of $\mathbf{y}$ onto the column space of $X$. In other words, recall that the projection can be done via the projection matrix $X( X^T X)^{-1}X^T$, we need to have $$Xw= \widehat{\mathbf{y}} =X( X^T X)^{-1}X^T \mathbf{y}$$ This implies $$ w = ( X^T X)^{-1}X^T \mathbf{y}$$ Since $$\hat{\mathbf{y}} = Xw =X( X^T X)^{-1}X^T \mathbf{y} $$ The following projection matrix is also often called the hat matrix $$P = X( X^T X)^{-1}X^T$$

Correlations, R Squared and F-statistics

Correlations
Denoting the $i$-th column of $X$ by $X_i$. $$ \begin{aligned} \mathtt{Corr}\left(\mathbf{y}, X_{i}\right):&=\frac{\sum(\mathbf{y}_j-\overline{\mathbf{y}}) (X_{ji}-\overline{X_{i}})}{\sqrt{\sum( X_{ji}-\overline{X_{i}})^2\sum(\mathbf{y_j}-\overline{\mathbf{y}})^2}} \\ &=\frac{\left(\mathbf{y}-\overline{\mathbf{y}}\right)\cdot\left( X_{i}-\overline{X_{i}}\right)}{\|X_i-\overline{X_{i}}\|\|\mathbf{y}-\overline{\mathbf{y}}\|}\\ &=\cos \left(\angle\left(\mathbf{y}-\overline{\mathbf{y}}, X_{i}-\overline{X_{i}}\right)\right) \end{aligned} $$
$R^2$
$$SST=SSE+SSR$$ $$R^{2}:=\frac{SSR}{SST}=\cos ^{2}(\angle(\mathbf{y}-\overline{\mathbf{y}}, \widehat{\mathbf{y}}-\overline{\mathbf{y}}))$$
$F$ Statistics
The $F$-statistics for nested models $$ F=\frac{\frac{\mathrm{RSS}_{\text {Reduced }}-\mathrm{RSS}_{\text {Full }}}{\mathrm{df}_{\text {Reduced }}-\mathrm{df}_{\text {Full }}}}{\frac{\mathrm{RSS}_{\text {Full }}}{\mathrm{df}_{\text {Full }}}} \propto \tan ^{2}(\angle\left(\widehat{Y}_{\mathrm{F}}-\bar{Y}, \widehat{Y}_{\mathrm{R}}-\bar{Y}\right)) $$

The identity $SST = SSE + SSR$ is Pythagoras in the geometry above: with an intercept in the model, the residual $\mathbf{y} - \widehat{\mathbf{y}}$ is orthogonal to the whole column space, hence to $\widehat{\mathbf{y}} - \overline{\mathbf{y}}$, so the centered response splits into perpendicular fitted and residual parts — and $R^2$ is the squared cosine of the angle between them, equivalently the squared correlation of $\mathbf{y}$ and $\widehat{\mathbf{y}}$. Two corrections keep $R^2$ honest. It never decreases when a feature is added, even a useless one, so comparisons across model sizes use the adjusted $R^2$, $\bar R^2 = 1 - (1 - R^2)\frac{n - 1}{n - p - 1}$, which charges each feature its degree of freedom. And the $F$ above specializes to the test of the whole regression against the intercept-only model: $F = \frac{R^2 / p}{(1 - R^2)/(n - p - 1)}$; for a single coefficient it reduces to $F = t^2$, the square of that coefficient's $t$-statistic.

Multicollinearity

When a feature can be expressed as a linear combination of other features, the features are termed collinear. In scenarios of multicollinearity or near multicollinearity, the design matrix $X$ lacks full rank or is nearly rank deficient, making the inverse of $X^TX$ nonexistent or unstable. Exact collinearity is the extreme: $X^TX$ is singular and $\widehat\beta$ is not unique at all — the data say nothing about how the shared direction splits among the features that span it. Near collinearity keeps the inverse but taxes every coefficient along that direction, by an amount one regression measures exactly. Regress feature $j$ on all the other features and call its $R^2$ value $R_j^2$; then $$\operatorname{Var}\left(\widehat\beta_j\right) = \frac{\sigma^2}{(1 - R_j^2)\, S_j}, \qquad S_j := \sum_i \left(X_{ij} - \overline{X_j}\right)^2$$ The factor $\mathrm{VIF}_j := 1/(1 - R_j^2)$, the variance inflation factor, is the price relative to an orthogonal design with the same spread $S_j$: the standard error of $\widehat\beta_j$ grows by $\sqrt{\mathrm{VIF}_j}$. With two features at correlation $\rho$ the auxiliary regression gives $R_j^2 = \rho^2$, so $\rho = 0.9, 0.95, 0.99$ inflates the variance by $5.3$, $10.3$ and $50.3$ — the standard error by $2.3\times$, $3.2\times$ and $7.1\times$. Nothing here biases $\widehat\beta$: least squares stays unbiased and the fitted values barely move, because the shared direction itself is still estimated well. What fails is attribution — which of the entangled features gets the credit. The symptoms follow: large standard errors and implausible or sign-flipped coefficients, small individual $t$-statistics beside a large joint $F$ (the features matter together, not separately), and estimates that swing when a few points are added or dropped. Prediction inside the span of the observed data is largely unaffected; extrapolation along the unobserved direction is where the instability bites.

Detection. Compute $\mathrm{VIF}_j$ for every feature — it needs only the design, not $\mathbf{y}$. Values above $5$ or $10$ (that is, $R_j^2$ above $0.8$ or $0.9$) are the usual rules of thumb for concern. A single-number summary is the condition number $\kappa(X) = s_{\max}/s_{\min}$ of the design's singular values: near collinearity is exactly a small $s_{\min}$, and $\kappa$ above roughly $30$ on scaled features signals the same problem.

Remedies. Drop or combine the redundant features when one of them carries no separate meaning; replace the entangled block by its principal components, which are orthogonal by construction (at the cost of interpreting components instead of features); collect data that breaks the near-dependence, the only remedy that adds information; or shrink — ridge regression, in Regularizations below, adds $\lambda I$ to $X^TX$ before inverting, which is precisely a floor under the small singular values, trading a little bias for a large variance cut along exactly the directions multicollinearity inflates.

VIF, Computed

The formula above, measured instead of asserted. The design is $n = 400$ points with $y = x_1 + x_2 + \varepsilon$, $\sigma = 1$, where $x_2 = \rho z_1 + \sqrt{1-\rho^2}\, z_2$ is built from one seeded pair $(z_1, z_2)$ — the same points at every $\rho$ (common random numbers, seed 20261123), only more or less entangled. The design then stays fixed while $200$ seeded noise draws are refit: the spread of $\widehat\beta_1$ across those resamples is its standard error, computed rather than quoted. The slider sets $\rho$; the third panel grades the measured spread against the section's $\sigma/\sqrt{(1-\rho^2) S_1}$ at every stop.

The design: $x_2$ against $x_1$ (half the 400 points). As $\rho \to 1$ the cloud collapses onto the diagonal — one direction of data, two coefficients claiming it.
Measured $\mathrm{sd}(\widehat\beta_1)$ across the 200 resamples (dots) against the formula $\sigma/\sqrt{(1-\rho^2)S_1}$ (curve).

At every stop the measured spread sits within a few percent of the formula — $0.162$ against $0.160$ at $\rho = 0.95$, $0.365$ against $0.354$ at $\rho = 0.99$ — so the inflation is real arithmetic, not a rule of thumb. And the control group is in the readout: $\mathrm{sd}(\widehat\beta_1 + \widehat\beta_2)$ goes from $0.071$ at $\rho = 0$ to $0.046$ at $\rho = 0.99$, flat to slightly better, while $\mathrm{sd}(\widehat\beta_1)$ grows eightfold. The shared direction is estimated as well as ever; only the split between the two coefficients is lost — at $\rho = 0.99$, $\widehat\beta_1$ comes out below $0.5$ in $15$ of the $200$ resamples and negative in $3$, with the truth at $1$. That is the section's distinction made visible: prediction survives multicollinearity, attribution does not.

Analytic Approaches

Normal Equation

The loss function can be expanded $$\mathrm{SSE}(b)=b^TX^TXb-2(Xb)^T\mathbf{y}+\mathbf{y}^T\mathbf{y} $$ Taking derivative (gradient) w.r.t $b$ gives $$\nabla \mathrm{SSE} = 2X^TX b - 2X^T \mathbf{y}$$ At a local minimum, we have $$\nabla \mathrm{SSE} = 2X^TX b - 2X^T \mathbf{y}=0$$ which gives us the Normal Equation $$X^TX b= X^T \mathbf{y}$$ When the inverse of $X^TX$ exists, we have, again $$ b = ( X^T X)^{-1}X^T \mathbf{y}$$
$$ \begin{aligned} \nabla b^TX^TXb &= \left[\lim_{\epsilon \to 0} \frac{(b+\epsilon e_i)^TX^TX(b+\epsilon e_i)-b^TX^TXb}{\epsilon}\right] \\ &= \left[\lim_{\epsilon \to 0} \frac{b^TX^TXb+2\epsilon b^TX^TXe_i+\epsilon^2 e_i^TX^TXe_i-b^TX^TXb}{\epsilon} \right]\\ &=\left[ \lim_{\epsilon \to 0} \frac{2\epsilon b^TX^TXe_i+\epsilon^2 e_i^TX^TXe_i}{\epsilon}\right] \\ &= 2X^TXb \end{aligned} $$

Gradient Descent

For ideas behind the Gradient Descent Algorithm, see the page Optimization Methods. In the example, we applied the Gradient Descent algorithm to minimize $\mathrm{SSE}(b)$. The updating rule is given by $$b_{j+1}=b_{j}-\alpha X^{T}(Xb-Y)$$

The Hessian of $\mathrm{SSE}$ is given by $$H_\mathrm{SSE}(b)=J_{\nabla \mathrm{SSE}}( b )=2X^TX$$ Thus $H_\mathrm{SSE} (b)$ is positive definite, locally by the Derivative Test, any local optimum of $\mathrm{SSE}(b)$ will be a local minimum. And globally $H_\mathrm{SSE} (b) $ positive definite for all $b$ implies $\mathrm{SSE}(b)$ is convex , and thus our local minimum is the unique global minimum.

Parametric Approach

Linear Model Assumptions

Regarded merely as fitting the least-squares line to the data points, linear regression is just a mathematical problem. But the moment one tries to do Statistical Inference, it becomes a statistical problem — and assumptions are needed for the interpretations to mean anything.

A Linear Model in regression is a model of the form $$\mathbf{y}=X b+\mathcal{E} $$, where the residual is a random vector with distribution $\mathcal{E}\sim \mathcal{N}(0,\sigma^2 I)$.

Maximum Likelihood

Let's take a small quiz:

Let $\mathbf{x}$ be a Gaussian random variable with mean $1$, and we observe 4 realizations of $\mathbf{x}$

Which of the following choices is a more likely distribution for $\mathbf{x}$?

The idea of maximum likelihood essentially formalizes the above example. Let $V$ be a random vector distributed according to the following density, a function in $V$, $$ p(V|\theta)$$ Given a realization $v$ of $V$, the likelihood function is defined as follows — now viewed as a function of $\theta$, $$L(\theta): = p(V|\theta)$$ And the maximum likelihood estimator for $\theta$ is given by $$ \mathrm{argmax}\ L(\theta) $$ Since the $\ln$ function is monotonically increasing, and turns products into sums, it is often easier to work with the log-likelihood function $$l(\theta)=\ln L(\theta)$$ And the corresponding optimization problem $$ \mathrm{argmax}\ l(\theta) $$

In the linear regression model, it turns out that the MLE for $b$ does not depend on $\sigma$, thus for simplicity we will assume $$\mathbf{y}=X b+\mathcal{E}\sim \mathcal{N}(Xb,I) $$ Given $\mathbf{y}$, $X$ fixed, the Likelihood function for $b$ is given by $$L(b)=(2 \pi)^{-\frac{n}{2}} e^{-\frac{1}{2}(\mathbf{y} -Xb)^{T}(\mathbf{y} -Xb)}, $$ and the log-likelihood is given by $$l(b)=\text{constant}-\frac{1}{2}(\mathbf{y} -Xb)^{T}(\mathbf{y} -Xb) $$ Note that from here we see that the maximization problem for MLE is equivalent to the minimization problem for $\mathrm{SSE}(b)$.

Both the Derivative Test, and Gradient Descent/Ascent can be used to find or estimate the maximum likelihood estimator. But let us use this opportunity to apply Newton's method.

Newton's Method

The idea behind Newton's Method is discussed on the page Optimization Methods. We go straight to its application to maximizing the log-likelihood function. To maximize $$l(b)=\text{constant}-\frac{1}{2}(\mathbf{y} -Xb)^{T}(\mathbf{y} -Xb) $$ We apply Newton's method to $$f(b):=\nabla l(b) = -X^TX b + X^T \mathbf{y}$$ The Jacobian of $f$ is $$J_f(b) = H_l(b)=-X^TX$$ Note that $J_f(b)$ is negative definite, thus locally by the Derivative Test, any local optimum of $l(b)$ will be a local maximum. And globally $J_f(b) $ negative definite for all $b$ implies $l(b)$ is concave , and thus our local maximum is the unique global maximum.

Given any initial guess $b $, one step of Newton's Method gives $$\begin{align} \beta&=b-J_f(b)^{-1}f(b)\\ & =b+(X^TX)^{-1}(-X^TXb+X^Ty)\\ &=(X^TX)^{-1}X^Ty \end{align}$$ i.e. only one step is needed. The application of Newton's method to Linear Regression requires only one step, since $f(b)$ is an affine map in $b$, i.e. it is of the form $f(b) = Mb+v$. A simple nontrivial application of Newton's Method can be found on the page Optimization Methods.

Regularizations

Regularization is a technique used to prevent overfitting in linear regression. It adds a penalty term to the loss function, which encourages the model to have smaller coefficients. This helps to prevent the model from fitting the noise in the data and instead focuses on the underlying relationship between the features and the target variable.

Ridge Regression & Lasso Regression

Lasso Regression Uses absolute value penalty for coefficient sparsity: $$\text{Regularized Loss} = \text{Original Loss} + \lambda \sum_{i=1}^{p} |\beta_i|$$ Key properties: Best for:
Ridge Regression Adds a penalty proportional to the square of coefficients to the loss function: $$\text{Regularized Loss} = \text{Original Loss} + \lambda \sum_{i=1}^{p} \beta_i^2$$ Key properties: Best for:

Elastic Net Regression

Elastic Net Combines L1 and L2 penalties through convex combination: $$\text{Regularized Loss} = \text{Original Loss} + \lambda \left( \alpha \sum_{i=1}^{p} |\beta_i| + (1 - \alpha) \sum_{i=1}^{p} \beta_i^2 \right)$$ Key advantages: Implementation considerations:

The Regularization Path Explorer

One dataset, eight predictors, every penalty on this page. The loss is the one above — $\mathrm{RSS} + \lambda\big(\alpha\sum_j|\beta_j| + (1-\alpha)\sum_j\beta_j^2\big)$ — fit on standardized predictors with an unpenalized intercept. Drag $\lambda$ and watch each coefficient travel its path: at the left edge ($\lambda \to 0$) every path lands on the least-squares estimate; at the right edge the penalties win. Two of the eight predictors are decoys — $x_7$ is pure noise, and $x_8$ only shadows $x_1$ — and $x_3, x_4$ are a correlated pair ($\rho \approx 0.96$) carrying one shared effect.

Three things worth noticing. Lasso's paths hit zero exactly and stay there — that is the feature selection the text above promises, and the decoys $x_7, x_8$ are usually the first to go. The correlated pair behaves differently under each penalty: lasso tends to keep one of $x_3, x_4$ and kill the other, elastic net shares the effect between them (the grouping effect), and ridge shrinks both together. And ridge's paths only approach zero — no finite $\lambda$ sets a ridge coefficient to exactly zero, which is why ridge never selects.

Choosing the Penalty: Cross-Validation

The explorer above leaves one question open: which $\lambda$? The training error cannot answer — it falls monotonically as $\lambda$ shrinks, because the fit is grading its own homework. The estimate has to come from data the fit has not seen. $K$-fold cross-validation manufactures such data: split the sample into $K$ folds, fit on the other $K-1$, score the held-out fold, rotate, and average: $$\mathrm{CV}_K(\lambda) = \frac{1}{n}\sum_{i=1}^{n} \Big(y_i - \hat f^{-\kappa(i)}_{\lambda}(\mathbf{x}_i)\Big)^2,$$ where $\kappa(i)$ is the fold containing point $i$ and the $-\kappa(i)$ on the hat means the fit that never saw point $i$. The working rule is then simply choose the $\lambda$ that minimizes $\mathrm{CV}_K(\lambda)$ — and the same procedure tunes $\alpha$, a tree's depth, or any other hyperparameter: anything with a knob gets a CV curve.

Two refinements matter in practice. The CV curve is itself an estimate, with a standard error across the folds; the one-standard-error rule picks the largest $\lambda$ whose CV error lies within one standard error of the minimum — the most strongly shrunk model the data cannot distinguish from the best. And the extreme $K = n$, leave-one-out, needs no refitting at all for a linear smoother like ridge: with $e_i$ the ordinary residuals of the single full fit and $h_{ii}$ the diagonal of the hat matrix, $$\mathrm{LOO}(\lambda) = \frac{1}{n}\sum_{i=1}^{n} \left(\frac{e_i}{1 - h_{ii}}\right)^{\!2},$$ because a point's leave-one-out residual is its ordinary residual inflated by $1/(1 - h_{ii})$ — its own leverage handed back. (Generalized cross-validation replaces every $h_{ii}$ by their average, $\mathrm{tr}(H)/n$.)

One honesty note. The CV value at the chosen $\hat\lambda$ is not quite an honest error estimate for the chosen model: it mixes two small biases — the folds train on only $n(K-1)/K$ points (slightly pessimistic) while $\hat\lambda$ won a contest judged on these very folds (slightly optimistic). An untouched test set, or an outer loop around the whole selection (nested CV), settles the number. The demo below cheats in your favor: it shows the test set.

The Cross-Validation Curve

One dataset — $n = 48$ points, $p = 12$ predictors of which seven are pure noise, noise level $\sigma = 1.5$ — and ridge fits along the whole $\lambda$ grid. Grey is the training error, which always votes for $\lambda \to 0$. Navy is the cross-validation estimate, with its $\pm 1$ SE band. Green, dashed, is the truth no practitioner gets to see: the mean squared error on 4,000 fresh points. At the left edge the training error reads $1.57$ against an honest $\approx 2.9$ — that gap is the overfit, measured. Watch how the navy curve tracks the green one's valley, and how flat that valley is.

At the default 5-fold setting, CV picks $\lambda = 1.78$ — on this sample, exactly where the test curve bottoms out ($2.86$); 10-fold and leave-one-out pick $\lambda = 3.16$ and land within a percent of that optimum. The one-standard-error rule is visibly more conservative, taking $\lambda = 10$: the extra shrinkage costs real error here (test $3.26$ against $2.86$), which is the rule's known character — it buys simplicity, and with ridge there is little simplicity to buy. Draw a new sample and the picks move, but the shape does not: a flat valley between two ditches. Finding that valley — and staying out of the ditches — is the whole of what tuning is.

The Bias–Variance Tradeoff

The cross-validation curve above has a valley because the test error it estimates is a sum of two curves pulling opposite ways. For a fit $\hat f$ trained on a random sample, the expected squared error at a point splits exactly: $$\E\big[(y - \hat f(x))^2\big] = \underbrace{\big(\bar f(x) - f(x)\big)^2}_{\text{bias}^2} + \underbrace{\Var\big(\hat f(x)\big)}_{\text{variance}} + \underbrace{\sigma^2}_{\text{noise}},$$ where $\bar f$ is the average fit over all possible training samples. Cross-validation can only see the total; this demo knows the truth — $f(x) = \sin 2\pi x - 0.6\cos 2\pi x + 0.4(x - \tfrac12)$, sampled at $n = 25$ fixed points with noise $\sigma = 0.5$ — so it can draw the split. For each polynomial degree it refits $80$ fresh datasets: the average fit against the truth is the bias, the spread of the fits is the variance, and the three components on the right are averaged over the input range. It is the same U the CV curve traces, opened up.

II — From Regression to Classification

The linear model can be pushed beyond a Gaussian response. Change the response distribution and add a link function, and the same machinery estimates probabilities instead of values — regression turns into classification. We cross that bridge first (logistic regression), then step back to the framework behind it (generalized linear models), and close with a second, orthogonal generalization: random effects for grouped data (mixed models).

Logistic Regression

log-odds

A Linear Model assumes $$y\sim \mathcal{N}(\mathbf{b}^T\mathbf{x},\sigma^2)$$ i.e. at any given point $\mathbf{x}$, it assumes $y= f(\mathbf{x})$ follows a Gaussian distribution, which rules out modeling cases where $y=f(\mathbf{x})$ follows other distributions. Consider, for example, a binary classification problem with labels $0$ and $1$. Then at any point $\mathbf{x}$, it is reasonable to assume that $$f(\mathbf{x})\sim \mathtt{Bernoulli}(p(\mathbf{x}))$$ And this leads us naturally to the Logistic Regression.

In Logistic Regression, we assume for some parameter $\theta$, $$y\sim \mathtt{Bernoulli}(p_\theta(\mathbf{x}))$$ Recall that the odds of $y=1$ conditioned on $\mathbf{x}$ is given by $$\frac{\mathtt{Pr}(y=1\mid \mathbf{x})}{\mathtt{Pr}(y=0\mid \mathbf{x})}= \frac{p_\theta(\mathbf{x})}{1-p_\theta(\mathbf{x})}\geq 0$$ Consider applying the monotonic function $\log$ to the above, we get the log-odds of $y=1$ or equivalently the logit function on $p_\theta(\mathbf{x})$, i.e. $$\mathtt{logit}(p_\theta(\mathbf{x})):=\log\left(\frac{p_\theta(\mathbf{x})}{1-p_\theta(\mathbf{x})}\right)\in \mathbb{R}$$ and the key assumption is that the log-odds is a linear function of $\mathbf{x}$, i.e. $$\log\left(\frac{p_\theta(\mathbf{x})}{1-p_\theta(\mathbf{x})}\right)=\theta\cdot \mathbf{x}$$ thus by the above assumptions, we have $$p_\theta(\mathbf{x})= \frac{1}{1+\exp(-\theta\cdot \mathbf{x})}=:\mathtt{sigmoid}(\theta\cdot \mathbf{x})$$ Here sigmoid is the inverse of the logit function.

And the goal of logistic regression is to estimate the probabilities $p_\theta(\mathbf{x})$. Since the sigmoid function is not linear, it is more convenient to use MLE to estimate $\theta$. Maximizing the likelihood function is equivalent to minimizing the negative log-likelihood $$L(\theta)=-\sum_{i=1}^{n} \left[ y^{(i)} \log \left(p_\theta(\mathbf{x}^{(i)})\right)+\left(1-y^{(i)}\right) \log \left(1-p_\theta(\mathbf{x}^{(i)})\right)\right]$$ The summands are$$\begin{cases}\log \left(p_\theta(\mathbf{x}^{(i)})\right),\qquad & y^{(i)}=1\\ \log \left(1-p_\theta(\mathbf{x}^{(i)})\right) & y^{(i)}=0 \end{cases} $$ The above loss function is also known as the Binary Cross Entropy function. Using Gradient Descent, we get the following updating rule $$\theta_{j+1}=\theta_{j}-\alpha X^{T}(p_\theta(X)-Y)$$ Where $X$ is the design matrix.

Model Coefficients

The logistic regression model can be expressed as:

$$ \log\left(\frac{P(y=1)}{1-P(y=1)}\right) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n $$ Taking the exponential of both sides, we get: $$ \begin{align} \text{odds}(y=1) &= \exp(\beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n)\\ &= \exp(\beta_0)\exp(\beta_1 x_1)\exp(\beta_2 x_2)\cdots\exp(\beta_n x_n) \end{align} $$ The exponential of the coefficients $$\exp(\beta_j)$$ gives the relation between the odds of $y=1$ and the corresponding feature $x_j$.

Generalized Linear Models

A Generalized Linear Model is of the form $$\eta(\mu_{\bf x}):=\eta\left(\mathrm{E}\left(Y \mid \bf x\right)\right)= \theta \cdot \bf x',\qquad \bf x' = \begin{pmatrix}1\\ \bf x \end{pmatrix} $$ for some link function $\eta$, and we assume that the entries of $ Y$ are independently sampled from an exponential family.

A common choice is $\eta = \log$, used when $Y$ is non-negative; the model can then be expressed as:

$$ \mu_{\bf x} = \exp\left(\beta_0 + \beta_1 x_{1} + \beta_2 x_{2} + \cdots + \beta_p x_{p}\right) = e^{\beta_0} \times e^{\beta_1 x_{1}} \times \cdots \times e^{\beta_p x_{p}} $$

Examples of GLM

  1. The Linear Model is a GLM, where the link function is the identity function, and $Y$ is from the Gaussian Distribution (an exponential family).
  2. The Logistic Regression Model is a GLM, where the link function is the logit function $$\eta(p)=\log \left(\frac{p}{1-p}\right)$$ and $Y$ is from the Bernoulli Distribution (another example of exponential family).
  3. If we let $y$ take on the following PMF $$\mathtt{Pr}(y=k \mid\mathbf{x})= \begin{cases}\frac{\exp(\beta_k \cdot \bf x)}{1+\sum_{l=1}^{K-1}\exp(\beta_l\cdot \mathbf{x})} \quad & k = 1,2,\cdots,K-1 \\ \frac{1}{1+\sum_{l=1}^{K-1}\exp(\beta_l\cdot \bf x)} & k=K \end{cases} $$ and $$\eta(p) = \log(\frac{p}{\mathtt{Pr}(y=K| \mathbf{x})}) $$ we get the Multinomial Logistic Regression.
  4. If we let $Y\sim \mathtt{Poisson}(\lambda)$, and take $\eta = \log$, then we get the Poisson Regression Model. $$ \lambda:=\mathrm{E}(Y \mid x)=e^{\theta^{\prime} x} $$ $$ p(y \mid x ; \theta)=\frac{\lambda^y}{y !} e^{-\lambda}=\frac{e^{y \theta^{\prime} x} e^{-e^{\theta^{\prime} x}}}{y !} $$
    1. Modeling Default Rates $$\log(\lambda) = \beta_0 + \beta_1 (\text{unemployment rate}) + \beta_2 (\text{loan-to-income ratio}) + \log(\text{exposure})$$ Here $\lambda$ is the expected default count, and $\text{exposure}$ accounts for loan volume

Mixed Effect Models

A Linear Mixed Effect Model is of the form $$\mathbf{y} = X\beta + U\gamma + \mathbf{\epsilon}$$ Where
  • $X,U$ are fixed design matrices
  • $\beta$ is an unknown fixed vector
  • $\gamma\sim \mathscr{N}{(0,G)}$, $\epsilon\sim \mathscr{N}{(0,R)}$
If $U$ is the zero matrix, the model reduces to an ordinary linear model.

import statsmodels.api as sm
import statsmodels.formula.api as smf

# Example data
data = sm.datasets.get_rdataset("dietox", "geepack").data

# Fit model
model = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"])
results = model.fit()

# Predict fixed-effects only
fixed_predictions = results.predict(data)

# Predict with random effects
random_effects = results.random_effects
group_predictions = fixed_predictions + data["Pig"].map(random_effects)

III — Classification

We now take classification on its own terms: find a separating rule, and judge it by the geometry of its boundary — a hyperplane learned by correction (the perceptron), a maximum-margin hyperplane (the SVM), or an ensemble of decision trees (bagging, random forests, XGBoost). The probabilistic classifier, logistic regression, was already built as the bridge in II. The last chapter of this part asks how a finished classifier should be graded.

The Perceptron Algorithm

  • Click on the Canvas to add Points.
    Change pen color:


Binary Classification Problem

Given $n$ points $\mathbf{x}_1,\cdots,\mathbf{x}_n$, each is assigned a label $l_i\in \{\pm 1\}$, we need to find a vector $\mathbf{w} $ and $t\in \mathbb{R}$, such that $$\begin{aligned} &\mathbf{w} \cdot \mathbf{x}_{\mathbf{i}}>t \quad \forall i\quad : \quad l_i=+1 \\ &\mathbf{w} \cdot \mathbf{x}_{\mathbf{i}} < t\quad \forall i\quad : \quad l_i=-1 \end{aligned} $$ If we write $$\widehat{\mathbf{x}}_{\mathbf{i}}=\left(\mathbf{x}_{\mathbf{i}}, 1\right) $$ Then the problem is equivalent to find a $\widehat{\mathbf{w}}$ such that $$\left(\widehat{\mathbf{w}} \cdot \widehat{\mathbf{x}}_{\mathbf{i}}\right) l_{i}>0 \quad 1 \leq i \leq n$$

Perceptron Algorithm

One of the earliest algorithms for classification problems is the Perceptron Algorithm.


Initialize: $$\mathbf{w} = 0$$ while $\exists\ \mathbf{x}_{\mathbf{i}}$ with $\sgn(w'\mathbf{x}_{\mathbf{i}})\ne l_{i} $, update $$\widehat{\mathbf{w}} \leftarrow {\mathbf{w}}+{\mathbf{x}}_{\mathbf{i}} l_{i}$$


Initialize: $$\widehat{\mathbf{w}} = 0$$ while $\exists\ \widehat{\mathbf{x}}_{\mathbf{i}}$ with $\widehat{\mathbf{x}}_{\mathbf{i}} l_{i} \cdot \widehat{\mathbf{w}} \leq 0$, update $$\widehat{\mathbf{w}} \leftarrow \widehat{\mathbf{w}}+\widehat{\mathbf{x}}_{\mathbf{i}} l_{i}$$

As long as the points are linearly separable, i.e. a solution exists, the Perceptron Algorithm is guaranteed to stop and find a solution.

The guarantee comes with a rate, and the rate is a statement about geometry, not about the sample size. Suppose some unit vector $\mathbf{u}$ separates the (augmented) points with margin $\gamma > 0$, $$l_i\,(\mathbf{u}\cdot\widehat{\mathbf{x}}_i)\ge \gamma\quad\text{for all }i,$$ and every point lies in a ball of radius $R$, $\|\widehat{\mathbf{x}}_i\|\le R$. Then the number of updates the algorithm ever makes is at most $$\left(\frac{R}{\gamma}\right)^{2}$$ (Block, 1962; Novikoff, 1962). The proof is two lines of bookkeeping on the weight vector $\mathbf{w}_k$ after $k$ updates. Each update adds a misclassified point, so the alignment with $\mathbf{u}$ grows by at least $\gamma$ per update, $\mathbf{w}_k\cdot\mathbf{u}\ge k\gamma$; but the update is triggered exactly when $l_i(\mathbf{w}\cdot\widehat{\mathbf{x}}_i)\le 0$, so the squared length grows by at most $R^{2}$ per update, $\|\mathbf{w}_k\|^{2}\le kR^{2}$. Cauchy–Schwarz, $k\gamma\le \mathbf{w}_k\cdot\mathbf{u}\le\|\mathbf{w}_k\|\le R\sqrt{k}$, forces $k\le (R/\gamma)^{2}$.

Three consequences are worth keeping. First, the bound involves neither the number of points $n$ nor the dimension $p$: a wide-margin problem is learned after few mistakes however large the dataset, while a barely separable one ($\gamma$ near $0$) can take arbitrarily long — separability alone promises termination, the margin promises it soon. Second, the bound is scale-free: multiplying every point by a constant multiplies $R$ and $\gamma$ alike and changes nothing. Third, the hyperplane the algorithm stops at is a separator, whichever one the order of presentation happens to reach — nothing in the update prefers a large margin. Choosing the separator with the largest margin is a different, harder problem, and it is exactly the one the Support Vector Machines section below takes up. On non-separable data the loop above never exits: the algorithm cycles forever, which is the practical motivation for the kernel method that follows and, later, for soft margins.

Perceptron, Computed

The bound above, watched as it happens. Two seeded strips of $120$ points each face off across a gap: every point's distance from the midline is $\gamma_0 + 0.6 \cdot u$ with $u$ uniform, so the midline separates the sample with margin $\gamma$ just above $\gamma_0$ — the slider sets $\gamma_0$, moving the same points (common random numbers, seed 20261122) apart or together. The presentation order is one fixed seeded shuffle, $\mathbf{w}$ starts at $0$, and each Step is one update — one misclassified point added to $\mathbf{w}$. The readout grades the running update count against $(R/\gamma)^2$ with $R$ and $\gamma$ measured on the sample itself. The checkbox instead flips the six points nearest the midline on each side — a few mislabeled points, and no separator exists at all.

● class +1 ■ class −1 — current separator ┄ midline and margin strip ◎ point that caused the update

Across the slider the update counts run $18, 10, 8, 4, 3, 2$ against bounds $308, 80, 30, 16, 10, 7$: the theorem always holds, and always with room to spare — it is a worst case over presentation orders, and this order is ordinary. The separators the algorithm stops at are usually worse than the midline it was graded against (at $\gamma_0 = 0.7$ its margin is $0.029$ against the midline's $0.701$): it stops at the first separator the order reaches, exactly as the prose above says, and leaves the good one to the SVM section. The mislabeled variant makes the opposite point: $331$ updates by epoch $30$, about $11$ more every epoch, no clean pass in sight — with no $\gamma$ there is no bound, and the loop simply never exits.

Kernel Method

Kernel Function
When points in the $p$ dimensional space cannot be separated by a $p-1$ hyperplane, the Perceptron Algorithm is not going to find a solution (as solution does not exist). One technique to solve this issue is to move to a higher dimensional space of dimension $p+k$, where the points are separable by a hyperplane of dimension $p+k-1$, via some function $$f:\mathbf{R}^p \to \mathbf{R}^{p+k} $$ then apply the Perceptron Algorithm in the higher dimensional space, at the end translate the solution back to the original space $\mathbb{R}^p$.

What really matters is the inner product computation in the higher dimensional space. Define the Kernel function induced by $f$ as $$K(\mathbf{u},\mathbf{v}):=f(\mathbf{u})\cdot f(\mathbf{v})$$ A kernel function $K$ is of the form $$K(\mathbf{u},\mathbf{v}):=f(\mathbf{u})\cdot f(\mathbf{v})$$ for some $f$ iff for any $g\in L^2$ $$\int \int K(\mathbf{u},\mathbf{v})g(\mathbf{u})g(\mathbf{v})d\mathbf{u}d\mathbf{v} \ge 0$$
Perceptron Algorithm with Kernel Functions
To avoid the explicit transformation of the points into the higher dimensional space, we note that, in our earlier version of the algorithm, the weight vector $\mathbf{w}$ can be written as a linear combination of the points $$ \mathbf{w} = \sum_{i=1}^n \alpha_i l_i \mathbf{x}_i$$ where $\alpha_i$ is the number of times $\mathbf{x}_i$ is misclassified. This allows us to generalize the algorithm, by replacing the dot product with the kernel function. $$ \sgn(\mathbf{w}\cdot \mathbf{x}_i) \Longrightarrow \sgn(\sum_{j=1}^n \alpha_j l_j K(\mathbf{x}_i,\mathbf{x}_j)) $$ And we can write the algorithm as
Initialize: $$\alpha_i = 0$$ while $\exists\ \mathbf{x}_{\mathbf{i}}$ with $\sgn(\sum_{j=1}^n \alpha_j l_j K(\mathbf{x}_i,\mathbf{x}_j))\ne l_{i} $, update $$\alpha_i \leftarrow \alpha_i + 1$$

Support Vector Machines

Support Vector Machines (SVM)

The primary goal in SVM classification is to find the optimal hyperplane $$\mathbf{w}^T \mathbf{x} + b = 0$$ that maximizes the margin between two classes. For linearly separable data, this reduces to solving the quadratic optimization problem:

$$\min_{\mathbf{w}, b} \frac{1}{2} \|\mathbf{w}\|^2 \quad \text{subject to} \quad y_i(\mathbf{w}^T \mathbf{x}_i + b) \ge 1 \quad \forall i$$

where $y_i \in \{-1, 1\}$ are class labels. The support vectors (critical training samples closest to the hyperplane) define the margin boundaries $$\mathbf{w}^T \mathbf{x} + b = \pm 1$$.

For non-separable data, soft margin SVM introduces slack variables $\xi_i$ and a regularization parameter $C$:

$$\min_{\mathbf{w}, b} \frac{1}{2} \|\mathbf{w}\|^2 + C \sum_{i=1}^{n} \xi_i \quad \text{subject to} \quad y_i(\mathbf{w}^T \mathbf{x}_i + b) \ge 1 - \xi_i, \quad \xi_i \ge 0$$

This balances margin width and classification error.

Kernel Trick for Nonlinear Separation

When data isn't linearly separable, SVMs use kernel functions $K(\mathbf{x}_i, \mathbf{x}_j) = \phi(\mathbf{x}_i)^T \phi(\mathbf{x}_j)$ to map features into higher dimensions without explicit computation.

The trick is available because the SVM never needs $\phi$ itself — only inner products between mapped points. Solving the dual of the soft-margin problem above makes this plain: the solution has the form $\mathbf{w} = \sum_i \alpha_i y_i \phi(\mathbf{x}_i)$, and the dual objective $$\max_{\alpha} \; \sum_{i=1}^n \alpha_i - \frac{1}{2} \sum_{i,j} \alpha_i \alpha_j y_i y_j \, \phi(\mathbf{x}_i)^T \phi(\mathbf{x}_j) \quad \text{subject to} \quad 0 \le \alpha_i \le C, \;\; \sum_i \alpha_i y_i = 0$$ involves the mapped points only through their pairwise inner products. Replacing each inner product by $K(\mathbf{x}_i, \mathbf{x}_j)$ — any kernel from the Kernel Method section above, Mercer's condition being what guarantees a $\phi$ exists — trains the machine in the high-dimensional space while every computation stays in the original one. The classifier itself is a kernel expansion, $$f(\mathbf{x}) = \sgn\Big( \sum_{i=1}^n \alpha_i y_i K(\mathbf{x}_i, \mathbf{x}) + b \Big),$$ and since $\alpha_i > 0$ only for the support vectors, prediction costs one kernel evaluation per support vector, not per training point.

What is saved is the size of $\phi$. For the degree-2 polynomial kernel on $\mathbb{R}^2$ the map $\phi(\mathbf{x}) = (x_1^2, \sqrt{2}\, x_1 x_2, x_2^2,$ $\sqrt{2c}\, x_1, \sqrt{2c}\, x_2, c)$ is already six-dimensional, and in general a degree-$q$ polynomial kernel on $\mathbb{R}^p$ has $\binom{p+q}{q}$ coordinates — $66$ for $p = 10$, $q = 2$ — while the kernel value $(\mathbf{u} \cdot \mathbf{v} + c)^q$ costs one inner product. The Gaussian kernel goes further: expanding its cross term, $e^{\mathbf{u} \cdot \mathbf{v} / \sigma^2} = \sum_{k=0}^{\infty} \frac{(\mathbf{u} \cdot \mathbf{v})^k}{\sigma^{2k} k!}$, shows every polynomial degree present at once, so its $\phi$ is infinite-dimensional and no explicit map exists to compute with. Back in the original space the boundary $f(\mathbf{x}) = 0$ is a curved level set — a weighted sum of bumps centred on the support vectors, for the Gaussian kernel — which is exactly the nonlinear separation the primal could not express.

The costs move rather than vanish: training works with the $n \times n$ Gram matrix of all pairwise kernel values, so memory and solve time grow superlinearly in $n$, and the kernel's own parameters — the bandwidth $\sigma$ (equivalently $\gamma = 1 / 2\sigma^2$) alongside $C$ — are hyperparameters, chosen by the cross-validation of Part I like every penalty on this page.

Forest and Trees

Bagging (Bootstrap Aggregating)

At the core of Random Forest lies bagging, a resampling technique that generates multiple training datasets from the original data. For a dataset $D = \{(x_1, y_1), \ldots, (x_n, y_n)\}$, bagging creates $B$ bootstrap samples $D_1, D_2, \ldots, D_B$ by sampling $n$ instances with replacement from $D$. Each bootstrap sample has an expected overlap of $1-\frac{1}{e}$ with the original dataset.

For each bootstrap sample $D_b$, a decision tree $f_b(x)$ is trained. The final prediction is an aggregate of these individual trees:

This aggregation reduces variance by averaging out the noise inherent in individual trees.

Feature Randomization

Random Forest introduces feature randomness by selecting a random subset of features at each split. For a dataset with $d$ features, each tree is trained on a subset of size $k = \sqrt{d}$ (classification) or $k = \frac{d}{3}$ (regression). This randomness decorrelates trees, further reducing variance while preserving bias.

The probability $p_{nj}$ of selecting the $j$-th feature at a node determines the level of randomness. If $p_{nj} \in (0, 1)$, the correlation $\rho(x)$ between trees decreases, leading to lower variance in the ensemble.

Feature Importance

Feature importance in Random Forest is often measured by the mean decrease in impurity across all trees. For feature $j$, the importance is:

$$ \text{Importance}(j) = \frac{1}{B} \sum_{b=1}^{B} \sum_{n \in T_b} \Delta \text{Impurity}_{n}(j) $$

where $\Delta \text{Impurity}_{n}(j)$ is the reduction in impurity at node $n$ due to splitting on feature $j$.

XGBoost

Mathematical Foundations of XGBoost

XGBoost minimizes the loss function $L(y_i, F(x_i))$, where $F(x) = \sum_{m=1}^{M} f_m(x)$ is the ensemble of decision trees. At each iteration $m$, the algorithm approximates the loss using a second-order Taylor expansion:

$$ L(y_i, F_{m-1}(x_i) + f_m(x_i)) \approx L(y_i, F_{m-1}(x_i)) + g_i f_m(x_i) + \frac{1}{2} h_i f_m(x_i)^2 $$

The approximated objective function becomes:

$$ \text{Obj}(m) = \sum_{i=1}^{n} \left[ g_i f_m(x_i) + \frac{1}{2} h_i f_m(x_i)^2 \right] + \Omega(f_m) $$

where $\Omega(f_m)$ is the regularization term to control overfitting:

$$ \Omega(f_m) = \gamma T + \frac{1}{2} \lambda \sum_{j=1}^{T} w_j^2 $$

This term discourages deep trees (via $\gamma T$) and large leaf weights (via $\lambda \sum w_j^2$).

Feature Importance

Feature importance is measured by the gain in loss reduction when splitting on a feature. For XGBoost, when a node is split into left and right children with instance sets $I_L$ and $I_R$, write $G_L = \sum_{i \in I_L} g_i$ and $H_L = \sum_{i \in I_L} h_i$ for the sums of the gradients and Hessians over the left child, and $G_R$, $H_R$ similarly over the right child. The gain of the split is:

$$ \text{Gain} = \frac{1}{2} \left[ \frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{(G_L + G_R)^2}{H_L + H_R + \lambda} \right] - \gamma $$

This gain is accumulated across all trees to rank feature contributions.

Classification Metrics

Precision, Recall, and F1 Score

In classification tasks, it is important to evaluate the performance of the model using various metrics. Three commonly used metrics are precision, recall, and F1 score.

These metrics help in understanding the performance of a classification model, especially in cases where the class distribution is imbalanced.

AUC-ROC Curve

Precision, recall and the F1 score all judge a classifier at one fixed threshold. A scoring classifier, though, is a family of classifiers — one per threshold — and the ROC curve evaluates the whole family at once. For a threshold $t$, call an instance positive when its score exceeds $t$ and record the two rates $$ \text{TPR}(t) = \frac{\text{True Positives}}{\text{True Positives} + \text{False Negatives}}, \qquad \text{FPR}(t) = \frac{\text{False Positives}}{\text{False Positives} + \text{True Negatives}} $$ — the TPR is the recall of the previous section; the FPR is the fraction of actual negatives the threshold wrongly admits. Sweeping $t$ from $+\infty$ (nothing is called positive: the point $(0, 0)$) down to $-\infty$ (everything is: $(1, 1)$) traces the curve through the unit square, monotone non-decreasing as the threshold falls.

The AUC is the area under that curve, $$ \text{AUC-ROC} = \int_0^1 \text{TPR}(t) d \text{FPR}(t) = \int_0^1 \text{TPR}(FPR^{-1}(t)) dt $$ and it has a second, purely combinatorial reading: the AUC is the probability that the classifier ranks a random positive above a random negative, $$ \text{AUC} = \Pr(S_p > S_n) + \tfrac{1}{2} \Pr(S_p = S_n) = \frac{U}{n_p n_n}, $$ where $S_p$ and $S_n$ are the scores of positive and negative instances, $n_p$ and $n_n$ their counts, and $U$ the Mann–Whitney statistic — the number of correctly ordered positive–negative pairs, ties counting half. The two readings are the same number: with positive scores $\{0.9, 0.7, 0.4\}$ and negative scores $\{0.8, 0.3, 0.2\}$, exactly $7$ of the $9$ pairs are correctly ordered, and the trapezoid area under the ROC curve is likewise $7/9 \approx 0.78$.

Three landmarks calibrate the scale: a perfect ranking has AUC $1$; scores unrelated to the label give the diagonal and AUC $1/2$; an AUC below $1/2$ means the ranking is inverted — negating the score beats the classifier. Because both rates are computed within a class, the AUC is a property of the ranking alone: it does not depend on the threshold, on the class prevalence, or on whether the scores are calibrated probabilities. Those are also its limits. It says nothing about calibration, and under heavy imbalance a small FPR can still correspond to many false positives in absolute terms — the regime where the precision–recall curve, built from the precision of the previous section, is the sharper instrument.

ROC, Computed

The sweep above, run. Sixty negatives score $\mathcal{N}(0, 1)$ and sixty positives $\mathcal{N}(d, 1)$ (seed 20261124, the same draws at every $d$), with every score rounded to one decimal, the way a real classifier's output arrives — the rounding manufactures genuine ties, so the $\tfrac12$ in the section's formula does real work. The slider sets the separation $d$; Run or Step lowers the threshold one score level at a time, and at each level the ROC point jumps — diagonally whenever a level holds both classes, which is the tie term happening. At the end the AUC is read out both ways at once: the trapezoid area under the traced curve, and the pair count $U/(n_p n_n)$.

● positives ■ negatives — threshold / traced curve ● current operating point
The ROC square. The shaded region is the trapezoid area accumulated so far — the AUC, built level by level.
The scores themselves. Everything right of the threshold line is called positive; the line drops one level per Step.

At every separation the two readings agree to the last printed digit — at the default $d = 1.5$, trapezoid $0.8756$ and pairs $3152/3600 = 0.8756$, with $58$ tied pairs contributing their halves through the diagonal jumps. The empirical values run a little above the unrounded normal model's $\Phi(d/\sqrt{2})$ ($0.856$ at $d = 1.5$): rounding costs almost nothing, but $60$ scores a class is a small sample — at $d = 0$, where the ranking is pure noise, this sample still scores $0.554$, and the AUC's own standard error at that size is about $0.05$. The curve is a property of the ranking; the number read off a finite sample is an estimate of it.

IV — Clustering

Finally, the labels come off. With no target to predict, the problem is to discover structure in the points themselves: partition them around moving centers (k-means), follow the density and let the clusters take whatever shape they like (DBSCAN), or follow the density at every level at once and keep the clusters that persist (HDBSCAN).

K-Means Clustering

k-Means Algorithm is one of the earliest methods developed for clustering problems, and is still the most popular partitioning algorithm today.

  1. Choose the number of centroids $k$, and select a distance function d.
  2. Initialize $k$ starting centroids (randomized or with some deterministic criteria)
  3. Assign each point to the closest cluster
  4. Update centroids by reevaluating the mean for each cluster
  5. Repeat the previous two steps until convergence

Applications

DBSCAN

K-means partitions by distance to a center, so its clusters are convex and every point is assigned — including points that belong nowhere. DBSCAN (Ester, Kriegel, Sander & Xu, 1996) replaces the center with a density test. Fix a radius $\epsilon$ and a count MinPts. A point is a core point if at least MinPts points lie within distance $\epsilon$ of it; a point within $\epsilon$ of a core point but not itself core is a border point; anything else is noise. A cluster is a maximal set of points chained together through overlapping core neighborhoods — density-connected, in the paper's term — so a cluster may bend, branch, or wrap around another one, and noise is left unassigned instead of being forced into a cluster.

The demo below makes the contrast concrete: its data are two concentric rings. No choice of two centers separates them — k-means with $k = 2$ cuts both rings roughly in half, since each center attracts the nearer half of each ring. DBSCAN follows the density along each ring and recovers both. The same experiment, run offline with $\epsilon = 0.12$ and MinPts $= 5$ on 300 points per ring plus 40 uniform noise points, labels every ring point correctly and rejects most of the noise (26 of 40; the rest happen to fall within $\epsilon$ of a ring and are absorbed as border points).

The price is the two parameters, and one global density threshold. MinPts is the smoothing choice: the usual heuristic is MinPts $\ge d + 1$ in dimension $d$, with larger values suppressing noise at the cost of thinning sparse clusters. Given MinPts, $\epsilon$ is commonly read off a $k$-distance plot — the sorted distance to each point's MinPts-th nearest neighbor — at the knee where the sparse tail takes off. Because a single $(\epsilon, \text{MinPts})$ pair fixes one density level, clusters of very different densities defeat it: an $\epsilon$ small enough to split two tight clusters also dissolves a diffuse one. Distances themselves degrade in high dimensions, which thins the neighborhoods the test counts. With a spatial index the neighborhood queries cost $O(n \log n)$ overall; without one, $O(n^2)$.

  1. Parameter Selection: Choose $\epsilon$ (epsilon) and MinPts.
  2. Select a Starting Point: Begin with an arbitrary unvisited point.
  3. Examine the Neighborhood:
    • If fewer than MinPts neighbors, label as noise (temporarily).
    • If at least MinPts neighbors, mark as a core point and form a new cluster.
  4. Expand the Cluster:
    • Add all neighbors to the cluster.
    • Recursively expand for core point neighbors.
    • Mark non-core neighbors as border points.
  5. Repeat: Move to the next unvisited point and repeat steps 3-4.
  6. Finalize Clusters: Identify all clusters and reclassify some noise points as border points if applicable.

HDBSCAN

DBSCAN's one global density level is the thing to give up. HDBSCAN (Campello, Moulavi & Sander, 2013) keeps the density idea and drops the fixed $\epsilon$: instead of asking which clusters exist at one threshold, it builds the clusters at every threshold and keeps the ones that persist. The construction starts by softening the metric itself. With MinPts fixed as before, each point's core distance is its distance to its MinPts-th nearest neighbor — small in dense regions, large in sparse ones — and the mutual reachability distance between two points is $d_{\text{mreach}}(a, b) = \max\{\text{core}(a), \text{core}(b), d(a, b)\}$. Nearby points in a dense region keep their true distance; any pair touching a sparse point is pushed apart to at least that point's core distance, so sparse points join the structure late instead of bridging two clusters early.

A minimum spanning tree of the complete graph under $d_{\text{mreach}}$, cut edge by edge from the longest down, is exactly the DBSCAN hierarchy: at cut level $\epsilon$ its components are the DBSCAN clusters for that $\epsilon$ (with single-linkage's chaining tamed by the reachability metric). Reparametrize the cut by $\lambda = 1/\epsilon$, so clusters are born at low $\lambda$ and split or dissolve as $\lambda$ grows, and prune the resulting tree with a second size parameter, MinClusterSize: a split in which a child keeps fewer than MinClusterSize points is not a split at all — those points simply fall out of the parent as noise. What remains is the condensed tree, whose nodes are the candidate clusters and whose edges record at which $\lambda$ each point left its cluster.

Selection is then a persistence contest. A candidate cluster $C$ born at $\lambda_{\text{birth}}$ earns stability $S(C) = \sum_{p \in C} (\lambda_p - \lambda_{\text{birth}})$, where $\lambda_p$ is the level at which point $p$ leaves $C$ — the total lifetime of its membership, summed over its points. Choose the non-overlapping set of candidates maximizing total stability: a parent is selected only if its stability beats the sum of its children's, otherwise the children win and the parent dissolves into them. The winners are the flat clustering — tight and diffuse clusters side by side, each found at its own density, which is precisely the configuration the single $(\epsilon, \text{MinPts})$ pair above cannot express. Points in no winning cluster are noise, as in DBSCAN.

The costs are honest ones. There are now two size parameters instead of a radius and a count, and while both are more forgiving than $\epsilon$ — the answer moves slowly as they vary — neither is automatic. The tree is built from all pairwise structure, so memory and time grow faster than DBSCAN's indexed neighborhood queries on large data. And stability is a global contest: a small cluster nested in the skirt of a large one can lose to its parent even when a reader would call it real. What the extra machinery buys is the removal of the one choice DBSCAN could not defend — the density level itself.

V — Applications

Two applications close the page, each reusing the machinery above: a time series regressed on its own past (ARIMA), and a rating matrix factorized into user and item embeddings (recommender systems).

ARIMA Models

An ARIMA$(p, d, q)$ model describes a time series $y_t$ through its own past values and past shocks. With $B$ the backshift operator ($B y_t = y_{t-1}$) and $\varepsilon_t$ white noise with variance $\sigma^2$, $$\phi(B)(1-B)^d y_t = c + \theta(B)\varepsilon_t, \qquad \phi(B) = 1 - \phi_1 B - \cdots - \phi_p B^p, \quad \theta(B) = 1 + \theta_1 B + \cdots + \theta_q B^q.$$

The three orders are:

The AR part is stationary iff every root of $\phi(z) = 0$ lies outside the unit circle, and the MA part is invertible iff every root of $\theta(z) = 0$ does.

Identifying the Orders

The sample ACF (autocorrelation function) and PACF (partial autocorrelation function) fingerprint the orders:

The Box–Jenkins loop: identify $(p, d, q)$ from the ACF/PACF → estimate by maximum likelihood → check that the residuals are indistinguishable from white noise → forecast, and iterate if the residuals still carry structure.

Example — the yearly sunspot counts (309 observations, 1700–2008) are already close to stationary, so $d = 0$. An AR(2) fit, with estimated mean $\mu = 49.75$, gives $$(y_t - \mu) = 1.391\, (y_{t-1} - \mu) - 0.689\, (y_{t-2} - \mu) + \varepsilon_t, \qquad \sigma^2 = 274.7,$$ whose characteristic roots are complex with modulus $1.205$ — outside the unit circle, as stationarity requires — and complex roots mean the fitted dynamics oscillate: the implied pseudo-period is $\approx 10.9$ years, the celebrated sunspot cycle. A longer memory does even better on AIC: AR(9) scores $2570.6$ against the AR(2)'s $2622.6$, while differencing the series (ARIMA(1, 1, 1), AIC $2722.5$) only hurts — there was no trend to remove.


import statsmodels.api as sm
from statsmodels.tsa.arima.model import ARIMA

# Yearly sunspot counts, 1700-2008
y = sm.datasets.sunspots.load_pandas().data["SUNACTIVITY"]

# d = 0: model the (near-)stationary levels
res2 = ARIMA(y, order=(2, 0, 0)).fit()
print(res2.params)   # const (the mean) 49.75, ar.L1 1.391, ar.L2 -0.689
print(res2.aic)      # 2622.6

# A longer AR memory wins on AIC
res9 = ARIMA(y, order=(9, 0, 0)).fit()
print(res9.aic)      # 2570.6

# Forecast the next 5 years
print(res2.get_forecast(5).predicted_mean)

Recommender Systems

$$ \begin{array}{l|cccccc} \text { Movie } & \text { Alice(1) } & \text { Bob(2) } & \text { Carol(3) } & \text { Dave(4) } & \begin{array}{c} \mathbf{x}_1 \\ \text { (romance) } \end{array} & \begin{array}{c} \mathbf{x}_2 \\ \text { (action) } \end{array} \\ \hline \text { Love at last } & 5 & 5 & 0 & 0 & 0.9 & 0 \\ \text { Romance forever } & 5 & ? & ? & 0 & 1.0 & 0.01 \\ \text { M3} & ? & 4 & 0 & ? & 0.99 & 0 \\ \text { Nonstop car chases } & 0 & 0 & 5 & 4 & 0.1 & 1.0 \\ \text { Swords vs. karate } & 0 & 0 & 5 & ? & 0 & 0.9 \end{array} $$ For any movie $M$, assume it can be represented by a vector $$X(M)= \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} \in \mathbb{R}^2$$ For movie $M3$, we have $X(M3)= \begin{bmatrix} 0.99 \\ 0 \end{bmatrix}$. We can try to predict user $j$'s rating for a movie by a model $$Y^j: \mathbb{R}^2 \to \mathbb{R}$$ Suppose that we use a linear model, then we have $$Y^j(X(M))=w^{(j)} \cdot X(M) + b^{(j)}$$ where $w^{(j)} \in \mathbb{R}^2$ and $b^{(j)} \in \mathbb{R}$ are the parameters of the model. Here we assume the $X$ function is known.

Collaborative Filtering

Extending Linear Model
What if the $X$ function is unknown? One approach known as collaborative filtering is to learn the $X$ function from the data, using the ratings of the movies by all the users. $$ \begin{aligned} J(w, b, x)&=\sum_{i,j:R(i,j)\ne0}\|w^{(j)} \cdot x^{(i)}+b^{(j)}-y_{i,j}\|^2+\lambda(\sum_j\|w^{(j)}\|^2+\sum_i\|x^{(i)}\|^2)\\ &=\|R\odot (XW^T\oplus b-Y)\|_F^2+\lambda(\|W\|_F^2+\|X\|_F^2+\|b\|_2^2) \end{aligned} $$ Where $R$ is the indicator matrix of the ratings, $R(i,j)=1$ if user $j$ has rated movie $i$, and $R(i,j)=0$ otherwise; $Y$ is the matrix of the ratings, $Y(i,j)$ is the rating of movie $i$ by user $j$. One can think of Collaborative Filtering as a problem of embedding the users and the movies into a common space, where the dot product of a user's and a movie's embeddings predicts the rating.
Discrete to Binary
What if the ratings are binary? Consider the sigmoid function $$\sigma(z)=\frac{1}{1+e^{-z}}$$ Then we can model the probability of user $j$ liking movie $i$ by $$P(y_{i,j}=1|w^{(j)}, x^{(i)})=\sigma(w^{(j)} \cdot x^{(i)}+b^{(j)})$$ Then we can use the following loss function to learn the parameters of the model: $$ J(w, b, x)=-\sum_{i,j}\left[ y_{i,j}\log P(y_{i,j}=1|w^{(j)}, x^{(i)})+(1-y_{i,j})\log(1-P(y_{i,j}=1|w^{(j)}, x^{(i)}))\right]+\lambda(\sum_j\|w^{(j)}\|^2+\sum_i\|x^{(i)}\|^2) $$
Matrix Factorization & Row Normalization
If we set the intercept terms $b^{(j)}=0$, then denote the rating matrix by $Y$, then we have $$Y \approx XW^T \qquad or\qquad Y \ominus \mu \approx XW^T$$ where $W$ is the matrix of the parameters of the models for all the users, and $\mu$ is the mean of the ratings.

References