Foundations
Math for Machine Learning
Introduction
Machine learning formulas use a small set of operations written in compact notation: adding up lists, multiplying grids of numbers, measuring the distance between lists of numbers, and working with probabilities. Every one of them can also be written as a few lines of Python, and the code form is often easier to read than the symbols.
Reading the Notation
Subscripts and the ellipsis
A subscript picks one item out of a list. If is a list of failed login counts for each hour of the day, is the first hour, the second, and is hour , whichever hour you are looking at. In code, is x[t].
Subscripts with arithmetic point at neighbours: is the hour before , and the hour after. Sequence models, such as the RNNs in AI, Machine Learning, and Deep Learning, are written this way: the state at step is computed from the input at and the state at .
The ellipsis () means “continue the pattern”. is every item from the first to the th added together, where is the length of the list.
Summation (Σ)
(capital sigma) is a compact way to write that same sum:
Read it as a loop. The bottom says where the counter starts, the top says where it stops, and the expression on the right is what gets added each time:
total = 0
for i in range(1, n + 1):
total += x[i]
With , the sum is .
The mean (average) is the sum divided by the count:
is the reciprocal of , and multiplying by it is the same as dividing by . Mean squared error, a standard way to score a model’s predictions, is written this way: compute the error on each training example, square it, sum the squares with , and divide by the number of examples.
Functions
is a rule that takes an input and returns an output. With , and . A function can take several inputs, written .
A trained model is a function. A spam filter is the probability the email is spam, and training is the process of adjusting until its outputs match the labels.
max, min, and argmax
returns the largest value and the smallest: .
Machine learning also uses , which returns which input produced the largest value instead of the value itself. A classifier that outputs these probabilities:
| Label | Probability |
|---|---|
| benign | 0.15 |
| phishing | 0.80 |
| malware | 0.05 |
has and . The argmax is the prediction.
Sets
A set is a collection of distinct items written in braces. Suppose these are the accounts that logged in on two days, and the company has five employees:
| Notation | Name | Result | Meaning | Python |
|---|---|---|---|---|
| cardinality | 3 | how many items | len(A) | |
| union | {alice, bob, carol, dave} | in A or B or both | A | B | |
| intersection | {bob} | in both | A & B | |
| complement | {dave, erin} | in U but not in A | U - A |
The complement always depends on , the full set being considered. Probability uses the same idea: the probability that an event does not happen is , the probability of its complement.
Exponents and Logarithms
An exponent says how many times to multiply a number by itself: . A logarithm runs the other way. It answers “what power do I raise the base to, to get this number?”
| Exponent | Logarithm | Base |
|---|---|---|
| 2 | ||
Base 2: bits
counts the combinations of bits. A byte has 8 bits, so it holds values. A 128-bit key has possible values.
counts the bits needed to represent options, which is also how entropy is measured. A password of 4 random lowercase letters has possibilities, and , so it carries about 18.8 bits of entropy. A fair coin flip carries exactly 1 bit.
Base e: growth and probabilities
is a constant, about 2.718, in the same way that is about 3.14. is always positive: it grows quickly as grows and gets close to zero as becomes negative (, , ).
Neural networks use to turn raw outputs into probabilities. A network’s raw output can be any number, such as -3 or 250, but a probability has to be between 0 and 1. The sigmoid function does that conversion:
Large positive inputs come out close to 1, large negative inputs come out close to 0, and an input of 0 comes out as exactly 0.5:
Softmax does the same job for several outputs at once and makes them add up to 1. That is how a classifier produces probabilities like the three in the argmax table above.
is the logarithm with base , called the natural logarithm: because . Machine learning uses it to score how wrong a classifier is, which is called log loss. If the model gave the correct label probability , the loss is:
A confident correct answer () costs 0.11. A confident wrong answer, where the correct label only got , costs 2.30, about 20 times more. Training lowers the average loss, so the steep left side of the curve pushes the model hardest to fix its confident mistakes.
Logs also turn multiplication into addition: . A language model scores a sentence by multiplying the probability of each word, and multiplying hundreds of numbers below 1 gives a result too small for a computer to store. Adding their logs carries the same information in a number of normal size.
Vectors and Norms
A vector is an ordered list of numbers, and in machine learning it describes one thing. A login event could be the vector (hour, failed attempts, MB downloaded) . Every input a model sees is turned into a vector first.
Dot product
The dot product of two vectors multiplies them item by item and adds the results:
This is what a single neuron computes. is the input, holds the neuron’s weights, and the output is plus a constant called the bias. Training adjusts the weights.
Norms: the size of a vector
A norm measures how big a vector is, written . There are three common ones. For :
| Norm | Formula | For (3, 4) |
|---|---|---|
| L2 (Euclidean) | ||
| L1 (Manhattan) | ||
| L∞ (max) |
When is written with no subscript, it means L2.
The distance between two vectors is the norm of their difference. For and , the difference is :
L2 is the straight-line distance. L1 is the distance along the grid lines, like walking city blocks. L∞ is the largest single difference.
Machine learning uses norms in three places:
- Similarity: models that find similar items, such as nearest-neighbour classifiers or search over embeddings (vectors a model produces to represent a piece of text or an image), rank items by the distance between vectors.
- Regularization: during training, the norm of the weight vector is added to the error, so large weights cost more. This discourages a model from fitting the training data too closely (overfitting). An L1 penalty pushes many weights to exactly zero, and an L2 penalty keeps all of them small.
- Normalizing: dividing a vector by its norm gives a vector of length 1 pointing the same way: .
Norms also appear in attacks on models. An adversarial example changes an input slightly so that a model gets it wrong, and “slightly” is defined as a norm limit on the change, for example no pixel changed by more than 8 out of 255 (an L∞ limit).
Matrices
A matrix is a grid of numbers. Its shape is written rows × columns, so a matrix with 2 rows and 3 columns is 2×3.
Matrix times vector
Multiplying a matrix by a vector takes the dot product of each row with the vector. Each row produces one number in the output:
The vector’s length must equal the matrix’s number of columns. A 2×3 matrix takes a vector of length 3 and returns a vector of length 2.
This is one layer of a neural network. Each row of holds the weights of one neuron, so this layer has 2 neurons, each reading 3 inputs. A deep network is a chain of these multiplications.
Matrix times matrix
Multiplying two matrices takes the dot product of each row of the first with each column of the second:
The shapes must line up: an matrix times an matrix gives an matrix. Order changes the result. With the same matrices:
Neural networks use this to process many inputs at once. Stack 1,000 input vectors as the rows of one matrix, and a single multiplication runs all of them through a layer. GPUs are designed to run this kind of operation in parallel.
Transpose
The transpose turns rows into columns:
A 2×3 matrix becomes 3×2. It is mostly used to make shapes line up for a multiplication. The dot product of two column vectors is often written .
Determinant, inverse, and trace
These apply to square matrices (same number of rows and columns). For a 2×2 matrix with entries , using the same as above:
| Name | Notation | 2×2 formula | For |
|---|---|---|---|
| Determinant | |||
| Inverse | |||
| Trace |
- Determinant: how much the matrix stretches area. A determinant of 6 means a shape’s area grows six times. A determinant of 0 means the matrix squashes everything onto a line, and the information cannot be recovered. has determinant , because its second column is double the first.
- Inverse: the matrix that undoes . Multiplying by gives the identity matrix , the matrix equivalent of 1. A matrix with determinant 0 has no inverse, since the formula divides by the determinant. Linear regression has a direct solution that uses an inverse: .
- Trace: the sum of the diagonal from top left to bottom right. It equals the sum of the matrix’s eigenvalues.
Eigenvectors and eigenvalues
Multiplying a vector by a matrix usually changes its direction. An eigenvector is a vector whose direction does not change: the matrix only stretches it. The stretch factor is the eigenvalue, written (lambda):
With the same :
The eigenvalues are 3 and 2. Their sum, 5, is the trace, and their product, 6, is the determinant.
Principal component analysis (PCA), a dimensionality reduction method, is built on this. It computes the eigenvectors of the data’s covariance matrix (covered below). Each eigenvector is a direction in the data, and its eigenvalue says how much the data spreads out along it. Keeping the few directions with the largest eigenvalues keeps most of the information in far fewer columns.
Probability and Statistics
Probability and conditional probability
is the probability that happens, from 0 (never) to 1 (always). is the probability of given that is known to be true. The vertical bar reads “given”.
If 2% of a company’s incoming email is phishing, . If 60% of emails containing the phrase “urgent wire transfer” are phishing, . Knowing changes the probability.
Model outputs are conditional probabilities. A classifier outputs , and a language model outputs , then picks or samples a word from that distribution.
Expected value
is the average value of , weighting each possible value by its probability:
If a server raises 0 alerts in 50% of hours, 1 alert in 30%, and 4 alerts in 20%:
No single hour has 1.1 alerts. The expected value is the long-run average.
Variance and standard deviation
Two servers both average 100 ms per response:
Server 1: 100, 100, 100, 100
Server 2: 50, 150, 50, 150
Variance measures how far values spread from the mean:
Take each value’s distance from the mean, square it, and average the squares. Server 1 has variance 0. Server 2’s values are each 50 away from the mean, so its variance is .
Squaring makes the units ms², which is hard to read. The standard deviation returns to the original unit:
Server 2 has ms. A simple anomaly detector flags any value more than 3 standard deviations from the mean.
Covariance and correlation
Covariance measures whether two variables rise and fall together:
Take the data below, with failed logins on four accounts and the alerts each account raised:
| Account 1 | Account 2 | Account 3 | Account 4 | Mean | |
|---|---|---|---|---|---|
| X (failed logins) | 1 | 2 | 3 | 4 | 2.5 |
| Y (alerts) | 2 | 4 | 5 | 9 | 5 |
A positive covariance means they rise together, and a negative one means one falls as the other rises. The size of the number depends on the units, so 2.75 alone does not say how strong the link is.
Correlation fixes that by dividing by both standard deviations:
Correlation is always between -1 and 1:
| Meaning | |
|---|---|
| 1 | both rise together, exactly on a straight line |
| 0 | no straight-line relationship |
| -1 | one falls as the other rises, exactly on a straight line |
A correlation of 0.96 says the two rise together. It does not say failed logins cause alerts; something else could drive both.
Before training, correlation is used to find features that duplicate each other. Two features with a correlation near 1 carry almost the same information, and one of them can usually be dropped.