IAE Academy

The whole Machine Learning formula sheet, to print

103 formulas in 7 topics, each with when to use it. Each is explained in the topic notes.

Simple, multiple and ridge regression

Read the notes

MEAN SQUARED ERROR (MSE)

Average squared residual; the sum of squared errors (SSE) is the same without the factor . Minimising either gives the same .

LEAST-SQUARES SLOPE AND INTERCEPT

Needs at least two distinct values (). The fitted line always passes through .

COEFFICIENT OF DETERMINATION

The two forms agree for least squares with an intercept on the training data, where SST = SSR + SSE; then (assuming SST ). For simple regression . On new (test) data, or for a model without an intercept, can be negative.

NORMAL EQUATIONS AND THE OLS SOLUTION

The inverse form requires to be invertible, i.e. the columns of (including the column of ones, if present) are linearly independent. This needs to be at least the number of columns. If one column is a linear combination of others (exact collinearity, or more columns than samples), is singular: minimisers still exist, but there are infinitely many.

RIDGE OBJECTIVE

Sum of squared errors plus times the squared Euclidean norm of the weights. gives OLS. For the objective is strictly convex, so the minimiser is unique. Equivalent constrained form: minimise subject to , for a that depends on .

RIDGE CLOSED FORM

For the matrix is always invertible (positive definite), even when is singular. Here is the identity of size equal to the number of weights.

GRADIENT DESCENT UPDATE FOR MSE

is the learning rate. The iterates converge from any starting point if , where is the largest eigenvalue of . If they generally diverge.

Logistic regression, k-nearest neighbour and naive Bayes

Read the notes

SIGMOID (LOGISTIC FUNCTION)

The output lies in (0, 1). ; as and as .

SIGMOID IDENTITIES

The derivative is at most 0.25, reached at . This identity is what makes the gradient of the cross-entropy loss so simple.

LOGISTIC REGRESSION MODEL

Binary classification. The prediction is class 1 when this probability exceeds the chosen threshold, which is 0.5 unless the question states another.

LOG-ODDS (LOGIT) IS LINEAR

With the other features fixed, each unit increase in adds to the log-odds, which multiplies the odds by .

DECISION BOUNDARY

The boundary is a hyperplane, so logistic regression is a linear classifier. is normal to the boundary and points towards the class-1 side. Changing moves the hyperplane parallel to itself.

LOG-LIKELIHOOD

Each sample contributes . Maximising and minimising give the same weights.

CROSS-ENTROPY LOSS (NATURAL LOG)

For one sample the loss is if and if . Using instead only multiplies the loss by a constant.

THE SAME LOSS WITH LABELS IN {−1, +1}

This is identical to the cross-entropy above, rewritten for labels using . Check which label convention a question uses before you substitute.

GRADIENT OF THE LOSS

Labels in . This has the same form as linear regression's gradient when that loss is written , with in place of the linear prediction. For a single sample, drop the and the sum.

L2-REGULARISED LOSS AND GRADIENT

sets the strength of the penalty. The bias is usually not penalised, so is unchanged. Books scale differently (with or without or ), so use the form the question gives.

GRADIENT DESCENT UPDATE

is the learning rate. With the squared-error loss per sample instead, the gradient picks up an extra factor . Learning then slows when the sigmoid saturates, and the loss is no longer convex in .

EUCLIDEAN, MANHATTAN, MINKOWSKI AND CHEBYSHEV DISTANCE

Euclidean is , Manhattan is , and Chebyshev is the limit . is a metric for . The order is written here because means a predicted probability in these notes. The nearest neighbour can change from one metric to another, so always use the one the question names.

K-NN REGRESSION

is the set of the nearest training points. A distance-weighted version uses weights proportional to . A query that coincides with a training point () is usually given that point's value.

MIN-MAX AND Z-SCORE SCALING

and are the mean and standard deviation of the feature. Compute , , and from the training data, and apply the same values to the query.

NAIVE BAYES POSTERIOR

This assumes the features are conditionally independent given the class. The denominator is the same for every class, so you need it only when the question asks for an actual probability.

NAIVE BAYES DECISION RULE (MAP)

Compare the unnormalised scores. In practice the logs are summed, , to avoid numerical underflow. With equal priors, the rule reduces to picking the class with the largest likelihood (maximum likelihood).

ESTIMATES FROM COUNTS

is the number of training samples in class , and is how many of them have feature equal to . These are maximum-likelihood estimates and can be zero. Priors are smoothed only if the question says so.

LAPLACE (ADD-$\ALPHA$) SMOOTHING

is the number of distinct values feature can take (2 for a binary feature). is Laplace smoothing. It stops a single unseen value from forcing the whole product to zero.

MULTINOMIAL NAIVE BAYES (WORD COUNTS)

Used for text classification. is the number of times word appears across the training documents of class , is the vocabulary size, and is how often occurs in the document being classified.

GAUSSIAN NAIVE BAYES

For continuous features. and are the mean and variance of feature within class (here is a standard deviation, not the sigmoid). The maximum-likelihood variance divides by and the unbiased one by ; use the one the question states. The result is a density, so it can exceed 1. Multiply the terms together as before.

NUMBER OF PARAMETERS (D BINARY FEATURES, K CLASSES)

The independence assumption makes the parameter count grow linearly in instead of exponentially. The term counts the priors, since they sum to 1.

Linear discriminant analysis, support vector machines and decision trees

Read the notes

DISTANCE OF A POINT FROM A HYPERPLANE

Euclidean distance from to the hyperplane , for .

LDA PARAMETER ESTIMATES (POOLED COVARIANCE)

Class means, priors and the pooled within-class covariance, where is the number of samples in class . Dividing by instead of only rescales . With equal priors the decisions are unchanged. With unequal priors the term gets a slightly different relative weight, so borderline decisions can change.

LINEAR DISCRIMINANT FUNCTION

Assign to the class with the largest ; is the natural logarithm. This assumes Gaussian classes with a common .

TWO-CLASS LDA RULE

This is . The boundary is a hyperplane with normal vector . It passes through the midpoint of the means when . Unequal priors shift it away from the more probable class.

FISHER CRITERION (TWO CLASSES)

Here are the projected means and the projected scatters. Maximise over . depends only on the direction of , not on its length.

FISHER'S OPTIMAL DIRECTION

The same direction as the two-class LDA weight vector, because is proportional to the pooled covariance. must be invertible.

MARGIN WIDTH

The distance between the hyperplanes . Valid only under the canonical scaling (closest points at ). The bias does not affect it.

HARD-MARGIN SVM (PRIMAL)

Requires linearly separable data. Maximising is the same as minimising .

HARD-MARGIN SVM (DUAL)

Only points with contribute to ; these are the support vectors. By complementary slackness, , so every support vector lies exactly on .

SOFT-MARGIN SVM (PRIMAL)

In the dual, the only change from the hard margin is the box constraint .

SOFT-MARGIN SVM AS HINGE LOSS

At the optimum , which turns the constrained problem into this unconstrained one.

COMMON KERNELS

Polynomial kernel: degree a positive integer and . RBF (Gaussian) kernel: , often written . RBF values lie in and equal 1 only when .

KERNELISED DECISION FUNCTION

Only the support vectors () contribute to the sum.

ENTROPY (IN BITS)

is the fraction of class in node . Entropy ranges from (a pure node) to (all classes equally likely), which is bit for two balanced classes.

GINI INDEX

Ranges from (pure) to (equal classes), which is for two balanced classes. For two classes with proportions : .

MISCLASSIFICATION ERROR

Ranges from to . For two classes, . Entropy and Gini respond more strongly to changes in node purity, so they are the usual criteria for growing a tree.

INFORMATION GAIN OF A SPLIT

is the subset sent to child by the test . The same weighted-average pattern with in place of gives the Gini reduction. Choose the split with the largest gain.

GAIN RATIO

Divides the gain by the entropy (in bits) of the split proportions themselves. This penalises tests that break the node into many small branches.

Bias–variance trade-off and cross-validation

Read the notes

BIAS OF AN ESTIMATOR AT $X_0$

Systematic error: how far the average prediction over training sets is from the truth.

VARIANCE OF AN ESTIMATOR AT $X_0$

Sensitivity: how much the prediction changes from one training set to another.

BIAS-VARIANCE DECOMPOSITION OF EXPECTED SQUARED ERROR

Valid for squared-error loss, with zero-mean noise in the test response that is independent of the training data. The term is irreducible: no model can remove it.

RIDGE REGRESSION ESTIMATE

Convention: is with samples in its rows, holds the responses, and the weights. The bias (intercept) is not penalised: and each column of are centred first, so drops out and is recovered afterwards. For , is always invertible. gives ordinary least squares (when is invertible), the lowest-bias and highest-variance member of the ridge family. drives (high bias, low variance). The penalty depends on the scale of each feature, so features are usually standardised first.

EXPECTED SQUARED ERROR OF $K$-NN REGRESSION AT $X_0$

Holds when the training inputs are fixed and with independent zero-mean noise of variance . Here are the training inputs nearest to , and is the average of their values. The middle term is bias squared, which usually grows with as farther neighbours are averaged in. The variance falls as grows.

ERROR ON ONE FOLD (REGRESSION, SQUARED ERROR)

is the number of samples in fold , and is the prediction of the model trained without fold . For classification, is the misclassification rate on fold .

$K$-FOLD CV ESTIMATE

Assumes equal-sized folds. With unequal folds, use . Number of models trained: , each on about samples.

LEAVE-ONE-OUT (LOO) CV ESTIMATE

LOO is -fold with . is the loss, and is trained on every sample except the -th, so models are trained, each on samples.

LOO SHORTCUT FOR ORDINARY LEAST SQUARES

Valid only for linear least squares with squared error, fitted once on all the data. is the full-data fit. is the -th diagonal entry of the hat matrix , with samples in the rows of . It requires to be invertible and . If an intercept is fitted, includes a column of ones. No refitting is needed.

MODELS TRAINED IN A GRID SEARCH

With several hyperparameters, the number of candidate settings is the product of the grid sizes. The is the refit on all the data. Leave it out if the question asks only about the search.

ACCURACY

Misleading when the classes are very unbalanced.

PRECISION

Of everything predicted positive, the fraction that is truly positive. Undefined if nothing is predicted positive.

RECALL (SENSITIVITY, TRUE POSITIVE RATE)

Of everything truly positive, the fraction found.

SPECIFICITY AND FALSE POSITIVE RATE

Specificity is the fraction of true negatives correctly identified.

F1 SCORE

The harmonic mean of precision and recall . TN does not appear in it.

Multi-layer perceptrons and feed-forward neural networks

Read the notes

PERCEPTRON OUTPUT (STEP ACTIVATION)

Targets are 0 or 1. The tie z = 0 is assigned to class 1 here. A question may use the opposite tie rule or targets of -1 and +1, so read the convention given.

PERCEPTRON LEARNING RULE

Applied sample by sample, where t is the target. If the sample is classified correctly, t - y is 0 and nothing changes. A missed class-1 sample pulls w towards x, and a missed class-0 sample pushes w away from x.

LAYER-WISE FORWARD PROPAGATION

W(l) has one row per unit of layer l and one column per unit of layer l-1. f is applied element-wise, except softmax, which acts on the whole vector.

NUMBER OF PARAMETERS IN A DENSE LAYER

n_l is the number of units in layer l. The network total is the sum over all layers after the input. The first term counts weights, the second counts biases.

SIGMOID AND ITS DERIVATIVE

Write the derivative in terms of the output y = sigma(z), so backpropagation needs no recomputation. Also 1 - sigma(z) = sigma(-z).

TANH AND ITS DERIVATIVE

Valid for all real z.

SOFTMAX

K output units. Outputs are positive and sum to 1. Adding the same constant to every z_i leaves p unchanged.

TWO-CLASS SOFTMAX IS A SIGMOID

Only the difference of the two logits matters, which is why one sigmoid unit is enough for binary classification.

SQUARED-ERROR LOSS (ONE SAMPLE)

The factor 1/2 is a convention that cancels the 2 on differentiation. If a question defines L without it, the gradient is doubled.

BINARY CROSS-ENTROPY (ONE SAMPLE, SIGMOID OUTPUT)

t is 0 or 1 and y = sigmoid(z). The gradient with respect to the output unit's net input z simplifies to y - t.

CATEGORICAL CROSS-ENTROPY WITH SOFTMAX

t is a one-hot vector. With true class c, the loss is -ln p_c.

GRADIENT-DESCENT UPDATE

theta is any weight or bias. All gradients are computed at the old parameter values, and then all parameters are updated together.

OUTPUT-LAYER ERROR SIGNAL FOR SQUARED ERROR

Squared-error loss with factor 1/2, output activation f applied element-wise. For a single output unit this is (y - t) f'(z). For sigmoid output, f' = y(1 - y); for linear output, f' = 1. With cross-entropy and sigmoid or softmax, delta = y - t directly.

HIDDEN-LAYER ERROR SIGNAL

The symbol is the element-wise product. The error of a hidden unit is the weighted sum of the errors of the units it feeds, times its own activation slope. Use the weights as they were before this step's update.

WEIGHT AND BIAS GRADIENTS

For a single weight: dL/dw = delta of the receiving unit times the output of the sending unit.

Clustering: k-means, k-medoids and hierarchical clustering

Read the notes

EUCLIDEAN DISTANCE

Default distance. k-means is built around its square.

MANHATTAN DISTANCE

Sum of absolute coordinate differences. For (1,1) and (4,5): Manhattan = 3 + 4 = 7, Euclidean = 5.

K-MEANS OBJECTIVE (WCSS)

Squared Euclidean distance of each point to its own cluster's centroid, summed over all points.

ASSIGNMENT STEP

Nearest centroid in Euclidean distance (squaring does not change which centroid is nearest). Ties need a fixed rule: keep the point in its current cluster if that cluster is among the nearest, otherwise take the lowest index.

UPDATE STEP (CENTROID)

Defined for a non-empty cluster. The mean is the point that minimises the sum of squared Euclidean distances to the cluster's points, so this step cannot increase .

WCSS FROM PAIRWISE DISTANCES

The double sum runs over all ordered pairs (each unordered pair counted twice). Useful when only distances are given. Check: for {1, 2, 4} the right side is 28/6 = 4.667, the same as the left.

SILHOUETTE COEFFICIENT OF POINT I

= mean distance from point to the other points of its own cluster; = the smallest, over the other clusters, of the mean distance from to that cluster's points. : near 1 means well placed, negative means is on average closer to another cluster. By convention if is alone in its cluster. A higher average over all points indicates a better .

MEDOID OF A CLUSTER

The member of the cluster with the smallest total dissimilarity to the other members. k-medoids minimises .

SINGLE LINKAGE (NEAREST NEIGHBOUR)

Closest pair across the two clusters. Prone to chaining: a line of nearby points joins distant groups into one long cluster.

COMPLETE LINKAGE (FARTHEST NEIGHBOUR)

Farthest pair across the two clusters. Favours compact clusters of similar diameter.

AVERAGE LINKAGE

Mean of all cross-cluster pairwise distances. For the same pair of clusters it lies between the single-linkage and complete-linkage values.

WARD'S LINKAGE

The increase in total WCSS caused by merging and ; it merges the pair that increases the WCSS least. Needs Euclidean coordinates (centroids). Software scales the reported height differently, but the order of merges is the same.

CENTROID LINKAGE

Distance between the cluster means. Needs Euclidean coordinates, and it can give inversions (a later merge lower than an earlier one).

AVERAGE-LINKAGE UPDATE AFTER MERGING A AND B

Weight the two old distances by cluster size. The plain average of and is wrong unless .

Dimensionality reduction and principal component analysis

Read the notes

SAMPLE MEAN AND CENTRED DATA

Centre each feature (column) to mean zero. denotes the centred matrix, whose rows are .

SAMPLE COVARIANCE MATRIX

Symmetric and positive semi-definite. Diagonal entries are feature variances; off-diagonal entries are covariances. Some texts divide by instead. The eigenvectors and the proportions of variance do not change; every eigenvalue is scaled by the same factor.

PRINCIPAL DIRECTIONS

The eigenvectors of the symmetric matrix are chosen orthonormal. is the -th principal direction (component). A direction is fixed only up to sign.

SPECTRAL DECOMPOSITION AND COVARIANCE OF SCORES

is orthogonal and . The scores (defined below) have the diagonal covariance .

VARIANCE ALONG A PRINCIPAL DIRECTION

Projections onto different components are uncorrelated: for .

VARIANCE ALONG ANY UNIT DIRECTION

The largest possible projected variance is , reached at . The smallest is , reached at .

TOTAL VARIANCE

Total variance is unchanged by rotating to the principal axes. For standardised data it equals .

PROPORTION OF VARIANCE EXPLAINED

Choose the smallest whose cumulative proportion reaches a stated target, such as 90 percent.

PROJECTION (SCORES) ONTO $K$ COMPONENTS

has orthonormal columns. The coordinate along is .

RECONSTRUCTION AND ERROR

The are eigenvalues of with divisor . With divisor , the mean squared error equals the sum of the discarded eigenvalues exactly. Among all -dimensional affine subspaces (all rank- linear reconstructions of the centred data), projecting onto the top components gives the smallest total squared reconstruction error. Maximising the retained variance and minimising the reconstruction error lead to the same components.

SVD OF THE CENTRED DATA

The columns of (right singular vectors) are the principal directions. The are the singular values in decreasing order. The are eigenvalues of with divisor .

SCORES FROM THE SVD

This uses the first columns of and and the top-left block of . The best rank- approximation of is .

GRAM-MATRIX ROUTE (USEFUL WHEN D > N)

The matrix has the same non-zero eigenvalues as . When it is the smaller matrix to decompose.