Notes AI Security Foundations

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 xx is a list of failed login counts for each hour of the day, x1x_1 is the first hour, x2x_2 the second, and xtx_t is hour tt, whichever hour you are looking at. In code, xtx_t is x[t].

Subscripts with arithmetic point at neighbours: xt−1x_{t-1} is the hour before tt, and xt+1x_{t+1} the hour after. Sequence models, such as the RNNs in AI, Machine Learning, and Deep Learning, are written this way: the state at step tt is computed from the input at tt and the state at t−1t-1.

The ellipsis (…\ldots) means “continue the pattern”. x1+x2+⋯+xnx_1 + x_2 + \cdots + x_n is every item from the first to the nnth added together, where nn is the length of the list.

Summation (Σ)

Σ\Sigma (capital sigma) is a compact way to write that same sum:

∑i=1nxi=x1+x2+⋯+xn\sum_{i=1}^{n} x_i = x_1 + x_2 + \cdots + x_n

Read it as a loop. The bottom says where the counter ii 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 x=(3,5,2,6)x = (3, 5, 2, 6), the sum is 3+5+2+6=163 + 5 + 2 + 6 = 16.

The mean (average) is the sum divided by the count:

xˉ=1n∑i=1nxi=164=4\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i = \frac{16}{4} = 4

1n\frac{1}{n} is the reciprocal of nn, and multiplying by it is the same as dividing by nn. 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 Σ\Sigma, and divide by the number of examples.

Functions

f(x)f(x) is a rule that takes an input xx and returns an output. With f(x)=2x+1f(x) = 2x + 1, f(3)=7f(3) = 7 and f(10)=21f(10) = 21. A function can take several inputs, written f(x,y)f(x, y).

A trained model is a function. A spam filter is f(email)=f(\text{email}) = the probability the email is spam, and training is the process of adjusting ff until its outputs match the labels.

max, min, and argmax

max⁡\max returns the largest value and min⁡\min the smallest: max⁡(0.2,0.9,0.5)=0.9\max(0.2, 0.9, 0.5) = 0.9.

Machine learning also uses arg⁡max⁡\arg\max, which returns which input produced the largest value instead of the value itself. A classifier that outputs these probabilities:

LabelProbability
benign0.15
phishing0.80
malware0.05

has max⁡=0.80\max = 0.80 and arg⁡max⁡=phishing\arg\max = \text{phishing}. 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:

U={alice,bob,carol,dave,erin}every employeeA={alice,bob,carol}logged in MondayB={bob,dave}logged in Tuesday\begin{aligned} U &= \{\text{alice}, \text{bob}, \text{carol}, \text{dave}, \text{erin}\} && \text{every employee} \\ A &= \{\text{alice}, \text{bob}, \text{carol}\} && \text{logged in Monday} \\ B &= \{\text{bob}, \text{dave}\} && \text{logged in Tuesday} \end{aligned}
NotationNameResultMeaningPython
∣A∣\lvert A \rvertcardinality3how many itemslen(A)
A∪BA \cup Bunion{alice, bob, carol, dave}in A or B or bothA | B
A∩BA \cap Bintersection{bob}in bothA & B
AcA^ccomplement{dave, erin}in U but not in AU - A

The complement always depends on UU, the full set being considered. Probability uses the same idea: the probability that an event does not happen is 1−P(A)1 - P(A), the probability of its complement.

Exponents and Logarithms

An exponent says how many times to multiply a number by itself: 23=2×2×2=82^3 = 2 \times 2 \times 2 = 8. A logarithm runs the other way. It answers “what power do I raise the base to, to get this number?”

ExponentLogarithmBase
210=10242^{10} = 1024log⁡21024=10\log_2 1024 = 102
e3≈20.09e^3 \approx 20.09ln⁡20.09≈3\ln 20.09 \approx 3ee

Base 2: bits

2x2^x counts the combinations of xx bits. A byte has 8 bits, so it holds 28=2562^8 = 256 values. A 128-bit key has 21282^{128} possible values.

log⁡2x\log_2 x counts the bits needed to represent xx options, which is also how entropy is measured. A password of 4 random lowercase letters has 264=456,97626^4 = 456{,}976 possibilities, and log⁡2456,976≈18.8\log_2 456{,}976 \approx 18.8, so it carries about 18.8 bits of entropy. A fair coin flip carries exactly 1 bit.

Base e: growth and probabilities

ee is a constant, about 2.718, in the same way that π\pi is about 3.14. exe^x is always positive: it grows quickly as xx grows and gets close to zero as xx becomes negative (e3≈20.09e^3 \approx 20.09, e0=1e^0 = 1, e−3≈0.05e^{-3} \approx 0.05).

Neural networks use exe^x 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:

σ(x)=11+e−x\sigma(x) = \frac{1}{1 + e^{-x}}

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:

The sigmoid curve: flat near 0 for inputs below -4, rising steeply through 0.5 at input 0, and flat near 1 for inputs above 4

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.

ln⁡x\ln x is the logarithm with base ee, called the natural logarithm: ln⁡20.09≈3\ln 20.09 \approx 3 because e3≈20.09e^3 \approx 20.09. Machine learning uses it to score how wrong a classifier is, which is called log loss. If the model gave the correct label probability pp, the loss is:

loss=−ln⁡p\text{loss} = -\ln p

The log loss curve: loss is near 0 when p is close to 1, and climbs steeply as p approaches 0. p = 0.9 gives 0.11, p = 0.1 gives 2.30

A confident correct answer (p=0.9p = 0.9) costs 0.11. A confident wrong answer, where the correct label only got p=0.1p = 0.1, 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: ln⁡(a×b)=ln⁡a+ln⁡b\ln(a \times b) = \ln a + \ln b. 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) =(3,7,450)= (3, 7, 450). 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:

x=(3,1,2)w=(0.5,−1,2)x⋅w=3×0.5+1×(−1)+2×2=1.5−1+4=4.5\begin{aligned} \mathbf{x} &= (3, 1, 2) \qquad \mathbf{w} = (0.5, -1, 2) \\ \mathbf{x} \cdot \mathbf{w} &= 3 \times 0.5 + 1 \times (-1) + 2 \times 2 = 1.5 - 1 + 4 = 4.5 \end{aligned}

This is what a single neuron computes. x\mathbf{x} is the input, w\mathbf{w} holds the neuron’s weights, and the output is x⋅w\mathbf{x} \cdot \mathbf{w} 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 ∥v∥\lVert \mathbf{v} \rVert. There are three common ones. For v=(3,4)\mathbf{v} = (3, 4):

NormFormulaFor (3, 4)
L2 (Euclidean)∥v∥2=v12+v22+⋯+vn2\lVert \mathbf{v} \rVert_2 = \sqrt{v_1^2 + v_2^2 + \cdots + v_n^2}9+16=5\sqrt{9 + 16} = 5
L1 (Manhattan)∥v∥1=∣v1∣+∣v2∣+⋯+∣vn∣\lVert \mathbf{v} \rVert_1 = \lvert v_1 \rvert + \lvert v_2 \rvert + \cdots + \lvert v_n \rvert3+4=73 + 4 = 7
L∞ (max)∥v∥∞=max⁡(∣v1∣,…,∣vn∣)\lVert \mathbf{v} \rVert_\infty = \max(\lvert v_1 \rvert, \ldots, \lvert v_n \rvert)44

When ∥v∥\lVert \mathbf{v} \rVert is written with no subscript, it means L2.

The distance between two vectors is the norm of their difference. For a=(2,1)\mathbf{a} = (2, 1) and b=(8,9)\mathbf{b} = (8, 9), the difference is (6,8)(6, 8):

A grid with points a at (2, 1) and b at (8, 9). A straight line between them has L2 length 10. A path 6 across then 8 up has L1 length 14. The longest side, 8, is the L-infinity distance.

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: (3,4)/5=(0.6,0.8)(3, 4) / 5 = (0.6, 0.8).

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:

W=[20113−1]x=[123]Wx=[2×1+0×2+1×31×1+3×2+(−1)×3]=[54]W = \begin{bmatrix} 2 & 0 & 1 \\ 1 & 3 & -1 \end{bmatrix} \qquad \mathbf{x} = \begin{bmatrix} 1 \\ 2 \\ 3 \end{bmatrix} \qquad W\mathbf{x} = \begin{bmatrix} 2 \times 1 + 0 \times 2 + 1 \times 3 \\ 1 \times 1 + 3 \times 2 + (-1) \times 3 \end{bmatrix} = \begin{bmatrix} 5 \\ 4 \end{bmatrix}

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 WW 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:

A=[2103]B=[1425]AB=[2×1+1×22×4+1×50×1+3×20×4+3×5]=[413615]A = \begin{bmatrix} 2 & 1 \\ 0 & 3 \end{bmatrix} \qquad B = \begin{bmatrix} 1 & 4 \\ 2 & 5 \end{bmatrix} \qquad AB = \begin{bmatrix} 2 \times 1 + 1 \times 2 & 2 \times 4 + 1 \times 5 \\ 0 \times 1 + 3 \times 2 & 0 \times 4 + 3 \times 5 \end{bmatrix} = \begin{bmatrix} 4 & 13 \\ 6 & 15 \end{bmatrix}

The shapes must line up: an m×nm \times n matrix times an n×pn \times p matrix gives an m×pm \times p matrix. Order changes the result. With the same matrices:

BA=[213417]≠ABBA = \begin{bmatrix} 2 & 13 \\ 4 & 17 \end{bmatrix} \neq AB

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 ATA^T turns rows into columns:

C=[123456]CT=[142536]C = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} \qquad C^T = \begin{bmatrix} 1 & 4 \\ 2 & 5 \\ 3 & 6 \end{bmatrix}

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 aTb\mathbf{a}^T \mathbf{b}.

Determinant, inverse, and trace

These apply to square matrices (same number of rows and columns). For a 2×2 matrix with entries a,b,c,da, b, c, d, using the same AA as above:

NameNotation2×2 formulaFor A=[2103]A = \begin{bmatrix} 2 & 1 \\ 0 & 3 \end{bmatrix}
Determinantdet⁡(A)\det(A)ad−bcad - bc2×3−1×0=62 \times 3 - 1 \times 0 = 6
InverseA−1A^{-1}1ad−bc[d−b−ca]\frac{1}{ad - bc} \begin{bmatrix} d & -b \\ -c & a \end{bmatrix}[0.5−0.16700.333]\begin{bmatrix} 0.5 & -0.167 \\ 0 & 0.333 \end{bmatrix}
Tracetr⁡(A)\operatorname{tr}(A)a+da + d2+3=52 + 3 = 5
  • 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. [2412]\begin{bmatrix} 2 & 4 \\ 1 & 2 \end{bmatrix} has determinant 2×2−4×1=02 \times 2 - 4 \times 1 = 0, because its second column is double the first.
  • Inverse: the matrix that undoes AA. Multiplying AA by A−1A^{-1} gives the identity matrix I=[1001]I = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, 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: w=(XTX)−1XTy\mathbf{w} = (X^T X)^{-1} X^T \mathbf{y}.
  • 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 (lambda):

Av=λvA\mathbf{v} = \lambda \mathbf{v}

With the same AA:

A[11]=[33]=3[11]eigenvector (1,1), eigenvalue 3A[10]=[20]=2[10]eigenvector (1,0), eigenvalue 2A[01]=[13]not a multiple of (0,1), so not an eigenvector\begin{aligned} A \begin{bmatrix} 1 \\ 1 \end{bmatrix} &= \begin{bmatrix} 3 \\ 3 \end{bmatrix} = 3 \begin{bmatrix} 1 \\ 1 \end{bmatrix} && \text{eigenvector } (1, 1)\text{, eigenvalue } 3 \\[4pt] A \begin{bmatrix} 1 \\ 0 \end{bmatrix} &= \begin{bmatrix} 2 \\ 0 \end{bmatrix} = 2 \begin{bmatrix} 1 \\ 0 \end{bmatrix} && \text{eigenvector } (1, 0)\text{, eigenvalue } 2 \\[4pt] A \begin{bmatrix} 0 \\ 1 \end{bmatrix} &= \begin{bmatrix} 1 \\ 3 \end{bmatrix} && \text{not a multiple of } (0, 1)\text{, so not an eigenvector} \end{aligned}

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

P(A)P(A) is the probability that AA happens, from 0 (never) to 1 (always). P(A∣B)P(A \mid B) is the probability of AA given that BB is known to be true. The vertical bar reads “given”.

If 2% of a company’s incoming email is phishing, P(phishing)=0.02P(\text{phishing}) = 0.02. If 60% of emails containing the phrase “urgent wire transfer” are phishing, P(phishing∣"urgent wire transfer")=0.6P(\text{phishing} \mid \text{"urgent wire transfer"}) = 0.6. Knowing BB changes the probability.

Model outputs are conditional probabilities. A classifier outputs P(label∣input)P(\text{label} \mid \text{input}), and a language model outputs P(next word∣all previous words)P(\text{next word} \mid \text{all previous words}), then picks or samples a word from that distribution.

Expected value

E[X]E[X] is the average value of XX, weighting each possible value by its probability:

E[X]=∑ixi P(xi)E[X] = \sum_i x_i \, P(x_i)

If a server raises 0 alerts in 50% of hours, 1 alert in 30%, and 4 alerts in 20%:

E[X]=0×0.5+1×0.3+4×0.2=1.1 alerts per hourE[X] = 0 \times 0.5 + 1 \times 0.3 + 4 \times 0.2 = 1.1 \text{ alerts per hour}

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:

Var⁡(X)=E[(X−E[X])2]\operatorname{Var}(X) = E\big[(X - E[X])^2\big]

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 502=250050^2 = 2500.

Squaring makes the units ms², which is hard to read. The standard deviation returns to the original unit:

σ(X)=Var⁡(X)\sigma(X) = \sqrt{\operatorname{Var}(X)}

Server 2 has σ=50\sigma = 50 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:

Cov⁡(X,Y)=E[(X−E[X])(Y−E[Y])]\operatorname{Cov}(X, Y) = E\big[(X - E[X])(Y - E[Y])\big]

Take the data below, with failed logins on four accounts and the alerts each account raised:

Account 1Account 2Account 3Account 4Mean
X (failed logins)12342.5
Y (alerts)24595
Cov⁡(X,Y)=(−1.5)(−3)+(−0.5)(−1)+(0.5)(0)+(1.5)(4)4=4.5+0.5+0+64=2.75\operatorname{Cov}(X, Y) = \frac{(-1.5)(-3) + (-0.5)(-1) + (0.5)(0) + (1.5)(4)}{4} = \frac{4.5 + 0.5 + 0 + 6}{4} = 2.75

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:

ρ(X,Y)=Cov⁡(X,Y)σ(X) σ(Y)=2.751.12×2.55≈0.96\rho(X, Y) = \frac{\operatorname{Cov}(X, Y)}{\sigma(X)\,\sigma(Y)} = \frac{2.75}{1.12 \times 2.55} \approx 0.96

Correlation is always between -1 and 1:

ρ\rhoMeaning
1both rise together, exactly on a straight line
0no straight-line relationship
-1one falls as the other rises, exactly on a straight line

Three scatter plots of 40 points each. Left: points rise together, correlation 0.95. Middle: no pattern, correlation 0.01. Right: one falls as the other rises, correlation -0.96

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.