Index Ai Academy
Foundation · Vectors and matrices

Tensors, shapes and broadcasting

Axes and shapes, reshape, axis=, broadcasting, and shapes through a small model.

About 43 minutes · Free lesson

What it covers6

Why it matters

Data doesn't stop at two directions. A batch of pictures has three: which picture, which row, which column. A batch of sentences has three too: which sentence, which word, which number in the word's vector. NumPy and PyTorch call any such block of numbers a tensor, and its shape says how long each direction is. Most bugs in model code are shape bugs, so reading shapes, changing them with reshape, collapsing one direction with axis=, and knowing how NumPy broadcasts a small array across a big one are everyday skills. This lesson puts all of them together in one small pipeline, in NumPy and then in PyTorch, where the same shapes carry every model you'll meet.

What you'll be able to do

  • Name scalars, vectors, matrices and tensors by their number of axes, and read a shape
  • Count a tensor's numbers as the product of its shape, and reshape without changing the count
  • Sum or average along one axis with axis=, and predict the shape that's left
  • Use broadcasting to apply one row to a whole table, and follow shapes through a small model in NumPy and PyTorch
Quick check
Have a guess before you start. A batch holds 8 pictures, each 5 × 5 pixels. How many numbers is that?
  1. 40
  2. 200
  3. 25
  4. 18
Show the answer

200

8 × 5 × 5 = 200: multiply the length of every direction.

The math: axes and shapes

Purpose. Data with more than two directions.

Count the directions, called axes:

  • A scalar, like 7, has 0 axes. Shape ().
  • A vector, like (2, 3, 1), has 1 axis. Shape (3,).
  • A matrix has 2 axes, rows and columns. Shape (2, 3).
  • A tensor has 3 or more. Eight 5 × 5 pictures stacked up have shape (8, 5, 5).

The number of entries is the product of the shape: (8, 5, 5) holds 200 numbers. Axes are numbered from 0, so in (8, 5, 5) axis 0 picks the picture, axis 1 the row and axis 2 the column. Model code often names the axes instead: a batch of sentences is (batch, seq, dim), for which sentence, which word in the sequence, and which number of the word's vector.

Quick check
From lesson 53: what is the shape of a data matrix for 60 signs of 25 pixels, one row per sign?
  1. (1500,)
  2. (25, 60)
  3. (60, 25)
  4. (60, 5, 5)
Show the answer

(60, 25)

One row per example, one column per feature. Keep each sign as a grid instead and the shape is (60, 5, 5): the same 1,500 numbers.

Collapsing an axis. Summing or averaging along an axis adds up the entries in that direction and removes it. For T = [[1, 2, 3], [4, 5, 6]], shape (2, 3):

  • along axis 0 (down the rows) leaves one number per column: (5, 7, 9), shape (3,);
  • along axis 1 (across the columns) leaves one number per row: (6, 15), shape (2,);
  • along both leaves one number, 21.

In plain words: the axis you name is the one that disappears.

Try it now

Switch between axis 0 and axis 1 and watch which direction collapses.

The picture. Shapes are how you follow data through a model. Below, a batch of 4 sentences, 6 words each, every word a vector of 16 numbers, goes through a layer, an average and a last layer. The first box is the input x, the middle three are the steps, and each arrow is labeled with the shape that travels along it. Watch which axis each step changes and which ones ride along untouched.

Broadcasting. When NumPy combines arrays of different shapes, it stretches the smaller one to fit, when it can, without copying it. A single row subtracted from a table is reused for every row. Watch the average day taken away from each day of a 3 × 2 table. The picture draws each day as a point, temperature across and hikers up, and the row being taken away as a ring. Each step moves one point by the same arrow.

Symbols and formula. The count and the broadcasting rule:

count=d0×d1×⋯(3,2) with (2,)  →  (3,2)\text{count} = d_0 \times d_1 \times \cdots \qquad (3, 2) \text{ with } (2,) \;\to\; (3, 2)

In plain words: to broadcast, line the two shapes up from the right. Each pair of sizes must be equal, or one of them must be 1 (or missing); the 1s are stretched to match.

So (3, 2) with (2,) works, and so does (3, 2) with (3, 1), a column reused for each column. But (3, 2) with (3,) fails: lined up from the right, 2 meets 3.

Quick check
Which pair of shapes can NumPy broadcast together?
  1. (4, 3) and (4,)
  2. (4, 3) and (2, 3)
  3. (4, 3) and (3, 4)
  4. (4, 3) and (3,)
Show the answer

(4, 3) and (3,)

From the right, 3 matches 3, and the missing axis is filled by reusing the row.

In your own words
In your own words: what does "the axis you name is the one that disappears" mean for a (5, 3) table summed along axis 0?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: shape, reshape, axis= and broadcasting

Purpose. Change and collapse shapes in one call each.

import numpy as np

v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
M = v.reshape(3, 4)
T = v.reshape(2, 2, 3)
print(v.shape, M.shape, T.shape, T.size)
print(T[1].tolist())
It runs right here in your browser, with nothing to install.

reshape lays the same numbers out in a new shape, row by row; the count must stay 12. .size is the count. T[1] picks along axis 0, leaving a 2 × 3 matrix. A named mistake: a reshape whose count doesn't match, like v.reshape(5, 3), stops with "cannot reshape array of size 12 into shape (5,3)".

Code flow. Step through six lines that use every idea so far: a reshape, a sum along each axis, and an average row taken away by broadcasting. Watch the boxes as you go. T holds v's six numbers in two rows, down has one box per column, across one per row, and C keeps T's shape.

axis= and broadcasting. Most NumPy reductions take an axis:

import numpy as np

T = np.array([[1, 2, 3], [4, 5, 6]])
print(T.sum(axis=0).tolist(), T.sum(axis=1).tolist(), T.sum())
X = np.array([[20, 4], [25, 2], [30, 6]])
mean = X.mean(axis=0)
print(mean.tolist(), (X - mean).tolist())

X.mean(axis=0) is the average day, one number per feature. X - mean broadcasts it over every row in one line, centering the table, which lesson 63's PCA needed and did with a loop. Broadcasting also covers the earliest case of all: P + 0.1 in lesson 54 was a single number stretched over a whole picture.

Worked example

Worked example: the mean pixel per sign

A batch of 8 signs has shape (8, 5, 5). Find how much ink each sign has, and the average picture.

import numpy as np

cross = np.array([[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]])
arrow = np.array([[0,0,1,0,0],[0,1,1,1,0],[1,0,1,0,1],[0,0,1,0,0],[0,0,1,0,0]])
box = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]])
batch = np.array([cross, arrow, box, cross, arrow, box, cross, arrow])
print(batch.shape, batch.size)
ink = batch.reshape(8, 25).mean(axis=1)
print(ink.tolist())
avg = batch.mean(axis=0)
print(avg.shape, np.round(avg[2], 2).tolist())
In the lesson you can change this and run it.

Stacking 8 grids gives shape (8, 5, 5). Reshaping to (8, 25) unrolls each sign into a row; the mean along axis 1 is each sign's share of inked pixels: 0.36 for the cross and the arrow (9 of 25), 0.64 for the box (16 of 25). The mean along axis 0 averages the 8 signs pixel by pixel, leaving one 5 × 5 average picture; its middle row is shown.

Quick check
What does this print?
import numpy as np

A = np.array([[1, 2], [3, 4]])
print((A + np.array([10, 20])).tolist(), (A * np.array([[1], [10]])).tolist())
  1. [[11, 12], [23, 24]] [[1, 2], [30, 40]]
  2. [[11, 22], [13, 24]] [[1, 20], [3, 40]]
  3. [[11, 22], [13, 24]] [[1, 2], [30, 40]]
  4. An error: the shapes differ
Show the answer

[[11, 22], [13, 24]] [[1, 2], [30, 40]]

A row (10, 20) is added to each row. A column (1, 10) multiplies each column: row 1 by 1, row 2 by 10.

Drill

Center a table in one line

Fix the lines so means is each column's average, centered is the table with each column's average taken away (by broadcasting), and ink is each sign's mean pixel from the (3, 5, 5) batch.

import numpy as np

X = np.array([[18, 70, 3], [22, 55, 5], [27, 40, 4], [33, 35, 8]])
means = X.mean(axis=1)
centered = X
cross = np.array([[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]])
box = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]])
batch = np.array([cross, box, box])
ink = batch.mean()
print(means, centered, ink)
In the lesson, your code is checked as you write it.
In your own words
Why is X - X.mean(axis=0) right for centering, while X - X.mean(axis=1) usually isn't?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML: real inputs are tensors

Purpose. Follow the shapes through a model.

Model inputs come in batches, so they're tensors: a batch of 8 signs is (8, 5, 5), and a batch of 4 sentences of 6 words, each word a vector of 16, is (4, 6, 16), the x of the math part's picture.

Here's lesson 56's sign layer on a batch, with the shape written after every step:

(8,5,5)→reshape(8,25)→@ W (25,3)(8,3)→+ b (3,)(8,3)→argmax(8,)(8, 5, 5) \xrightarrow{\text{reshape}} (8, 25) \xrightarrow{@\,W\,(25, 3)} (8, 3) \xrightarrow{+\,\mathbf{b}\,(3,)} (8, 3) \xrightarrow{\text{argmax}} (8,)

In plain words: unroll each picture, score it three ways, add the biases by broadcasting, and pick the best score in each row.

import numpy as np

cross = np.array([[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]])
arrow = np.array([[0,0,1,0,0],[0,1,1,1,0],[1,0,1,0,1],[0,0,1,0,0],[0,0,1,0,0]])
box = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]])
batch = np.array([cross, arrow, box, cross, arrow, box, cross, arrow])
W = np.array([cross.flatten(), arrow.flatten(), box.flatten()]).T
b = np.array([0, 0, -5])
Z = batch.reshape(8, 25) @ W + b
print(batch.shape, W.shape, Z.shape)
print(np.argmax(Z, axis=1).tolist())

np.argmax(Z, axis=1) gives the position of the biggest number in each row: 0, 1, 2, … names cross, arrow, box. The bias −5 on the box score is broadcast to every row, a small handicap the box still overcomes.

Quick check
A batch of 4 sentences, 6 words each, every word a vector of 16, goes through a layer W of shape (16, 64). What shape comes out?
  1. (4, 6, 64)
  2. (64, 6, 4)
  3. (4, 64)
  4. (4, 6, 16)
Show the answer

(4, 6, 64)

@ acts on the last axis: 16 meets 16 and becomes 64. The batch and word axes ride along unchanged, as they did for the (16, 32) layer in the math part's picture.

Shapes are the first thing to check. Model code is full of comments like # (batch, words, 64), because a shape error, a wrong axis or an accidental broadcast is the most common bug in ML. Broadcasting is the sneakiest: (8, 1) minus (8,) quietly becomes (8, 8) instead of failing. When a result has a surprising shape, print .shape at each step, just as the pipeline above does. A comment with the expected shape on each line turns a surprise into an obvious mismatch.

Quick check
A column and a row broadcast together. What does this print?
import numpy as np

col = np.ones((4, 1))
row = np.array([1, 2, 3])
print((col + row).shape, (col + row)[0].tolist())
  1. (4, 3) [2.0, 3.0, 4.0]
  2. (4, 1) [2.0]
  3. An error: the shapes differ
  4. (3,) [2.0, 3.0, 4.0]
Show the answer

(4, 3) [2.0, 3.0, 4.0]

Lined up from the right: (4, 1) and (3,). The 1 stretches to 3 and the missing axis to 4, so the result is (4, 3), each row 1 + (1, 2, 3).

In PyTorch. The same pipeline on tensors. PyTorch says dim= where NumPy says axis=, and torch.stack piles tensors along a new first axis, as np.array did with the list of grids:

import torch

cross = torch.tensor([[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]])
arrow = torch.tensor([[0,0,1,0,0],[0,1,1,1,0],[1,0,1,0,1],[0,0,1,0,0],[0,0,1,0,0]])
box = torch.tensor([[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]])
batch = torch.stack([cross, arrow, box, cross, arrow, box, cross, arrow])
W = torch.stack([cross.flatten(), arrow.flatten(), box.flatten()]).T
b = torch.tensor([0, 0, -5])
Z = batch.reshape(8, 25) @ W + b
print(batch.shape, W.shape, Z.shape)
print(Z.argmax(dim=1).tolist())
print(batch.reshape(8, 25).sum(dim=1).tolist())
one = cross.unsqueeze(0)
print(one.shape, (one.reshape(1, 25) @ W + b).argmax(dim=1).tolist())

The shapes (PyTorch writes them torch.Size([8, 5, 5])) and the predictions are the ones NumPy printed: 0, 1, 2, 0, 1, 2, 0, 1. .sum(dim=1) counts each sign's ink: 9 for the cross and the arrow, 16 for the box. .unsqueeze(0) adds an axis of size 1 at the front, so one sign becomes a batch of one, (1, 5, 5), and the layer reads it as a cross, [0]. A model always expects the batch axis first, even for a single example.

The picture's shapes, in code. torch.zeros makes tensors of any shape, which is all you need to check shapes before any real numbers exist. These are the four boxes of the math part's picture:

import torch

x = torch.zeros(4, 6, 16)          # (batch, seq, dim)
W = torch.zeros(16, 32)
h = x @ W
pooled = h.mean(dim=1)
scores = pooled @ torch.zeros(32, 3)
print(x.shape, h.shape, pooled.shape, scores.shape)
print(torch.einsum("bsd,dh->bsh", x, W).shape)

An aside: einsum. The last line writes x @ W with a letter for every axis: b for batch, s for seq, d for dim and h for the 32 outputs. The letter d is in both inputs but not after the arrow, so it's the axis that gets multiplied and added away; the rest come through. You'll meet einsum in model code, and reading its letters is just reading shapes.

Drill

Shapes through a pipeline

A batch of 6 pictures, each 4 × 4, goes through a layer with 5 outputs. Set flat_shape, W_shape, Z_shape and pred_shape to the shape (as a tuple) at each step: after reshaping, the weights, after @ W + b, and after argmax along axis 1. Then build the arrays with zeros to check them.

import numpy as np

flat_shape = (6, 4, 4)
W_shape = (5, 16)
Z_shape = (6, 16)
pred_shape = (5,)
batch = np.zeros((6, 4, 4))
W = np.zeros(W_shape)
print(flat_shape, W_shape, Z_shape, pred_shape)
In the lesson, your code is checked as you write it.
In your own words
Why does the layer W only care about the last axis of its input?

Write a sentence or two, then compare it with a good answer in the lesson.

Goes deeper in

  • Tensors: tensors and their shapes for ML.
  • NumPy: arrays, axes and broadcasting in more depth.
  • PyTorch tensors: the same ideas in PyTorch.

Practice what you just read

  • 6 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What shape is left when an array of shape (10, 4) is summed along axis 1?

  1. (10,)
  2. (4,)
  3. (10, 4)
  4. ()

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Foundation · about 96 hours of study

Foundation math

From whole numbers to the math inside a neural network: each idea by hand, in Python, and in AI 118 lessons All free
  1. Numbers and place value FreeWhat a digit's place is worth, the number line, and Python as a calculator that never tires.36 min
  2. Multiplying and dividing: groups FreeEqual groups, quotient and remainder, and cutting training data into batches.35 min
  3. Order of operations, and names for numbers FreeBrackets, powers, then multiply and divide, then add and subtract; variables hold numbers.36 min
  4. Numbers below zero FreeThe number line through zero, sign rules, distance from zero, and an error's direction and size.37 min
  5. Fractions: equal parts, equal fractions, adding FreePieces of a whole, equal fractions, and re-cutting to add; accuracy as a fraction.45 min
  6. Multiplying and dividing fractions FreeA share of a share, dividing by flipping, and why chances in a row get small.35 min
  7. Decimals and rounding FreeFractions in place value, rounding, and why 0.1 + 0.2 isn't exactly 0.3.36 min
  8. Percentages FreePer hundred, percent change, percentage points, and the accuracy and error rates of models.35 min
  9. Ratios, rates and proportion FreeSharing in a ratio, rates per unit, scaling, and splitting data 80/10/10.35 min
  10. Powers and roots FreeRepeated multiplying, the laws of exponents, square roots, and squared error.43 min
  11. Very big and very small numbers FreePowers of ten, e-notation like 3e-4, orders of magnitude, and a model's size in memory.36 min
  12. Bits, bytes and floats: how numbers are stored FreeBase 2, what n bits can hold, a float as sign, power and digits, and a tensor's memory.35 min
  13. Review: find the slip (numbers) FreeBroken calculations to fix, mixed practice from the whole module, and its formula sheet.34 min
  14. Letters for numbers FreeVariables, terms and like terms, substitution, and a model's formula as a Python function.41 min
  15. Expanding and factoring FreeBrackets as areas, pulling out common factors, and a squared error expanded into a bowl.41 min
  16. Solving equations: keep the balance FreeThe same move on both sides, undoing steps in reverse, and running a model's formula backward.41 min
  17. Rearranging a formula FreeMaking any letter the subject, round-trip checks, and planning a training run.36 min
  18. Inequalities and true-or-false FreeRanges, flipping the sign, if and elif, and the thresholds, clips and ReLU inside a model.42 min
  19. Functions: a rule from input to output Freef(x) notation, tables and graphs, domain and range, loops over lists, and loss as a function.42 min
  20. Chaining and undoing functions Freeg(f(x)), inverses that undo, scaling and unscaling, and a network as a chain.42 min
  21. Straight lines: slope and intercept FreeRise over run, the line through two points, and a model's weight and bias as slope and intercept.42 min
  22. Two equations, two unknowns FreeSubstitution and elimination, where lines cross, and why models are fitted, not solved.42 min
  23. Quadratics: bowls and their lowest point FreeRoots by factoring and by formula, the discriminant, the vertex, and the best weight of a model.42 min
  24. Exponentials: growth and decay FreeThe same factor each step, the number e, and decaying learning rates.43 min
  25. Logarithms: the power question FreeTo what power?, the laws of logs, and adding log-probabilities instead of multiplying.45 min
  26. Sequences and Σ FreeArithmetic and geometric sequences, Σ as a loop that adds, and mean squared error.40 min
  27. Weighted and moving averages FreeWeights that add to 1, a window average, the exponential moving average, and smoothing a loss curve.35 min
  28. Sets, and reading the symbols FreeSets, union and intersection, ℝⁿ and f : ℝⁿ → ℝᵐ, and reading a paper's first equation.41 min
  29. Review: find the slip (algebra) FreeBroken algebra and code to fix, mixed practice from the whole module, and its formula sheet.34 min
  30. Transposing step by step: undo in reverse order FreeA formula's layers, the opposite of each, peeling from the outside in, conditions, and round-trip checks.35 min
  31. Formulas with fractions: clear them first FreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
  32. When the letter appears twice: collect and factor FreeGathering the letter on one side, factoring it out, dividing by the bracket, and rearranging precision and F1.35 min
  33. Squares, roots and powers FreeSquare roots with ±, squaring to undo a root, cube and nth roots, and the √d inside attention.40 min
  34. When the letter is squared and plain: quadratics FreeRearranging into ax² + bx + c = 0, the formula, completing the square, and choosing the root that fits.35 min
  35. Letters in the power: exponentials and logarithms FreeTaking logs to bring a power down, exponentiating to free a letter, and the logit that undoes the sigmoid.40 min
  36. Rearranging inequalities: when the sign flips FreeThe four moves on an inequality, negatives and reciprocals that flip it, logs below 1, and sample sizes.35 min
  37. Inverse functions, lines and scaling FreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
  38. Sequences and sums: find n, a, d and r FreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
  39. Combining formulas: substitute and eliminate FreePutting one formula inside another to remove a letter, and sizing a training run from a time or money budget.35 min
  40. Review: rearrange anything (algebra) FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
  41. Coordinates and distance FreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
  42. Angles, degrees and radians FreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
  43. Sine and cosine FreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
  44. Waves: height, speed and shift FreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
  45. Review: find the slip (shapes and waves) FreeBroken geometry and code to fix, mixed practice from the module, and its formula sheet.29 min
  46. Angles, triangles and waves: rearranging with sin, cos and tan FreeSides and angles from SOH CAH TOA, principal values, arcs, polar coordinates, and a wave's time and period.45 min
  47. Vectors: lists of numbers that point FreeA list, a point and an arrow; components, dimension, NumPy arrays, and data as vectors.42 min
  48. Adding and scaling vectors FreeComponent-wise sums, scalar multiples, mixes, and the weight update w − ηg.43 min
  49. Length and distance: norms FreeL2, L1 and max norms, unit vectors, distance, and the norms inside losses and clipping.42 min
  50. The dot product FreeMultiply in pairs and add; a·a as squared length; a @ b; one neuron as a dot product.43 min
  51. Angle, cosine similarity and projection FreeDirection without length, perpendicular vectors, shadows, and search by meaning.45 min
  52. Perpendicular directions: bases and coordinates FreeOrthonormal directions, coordinates as dot products, rebuilding a vector, and taking a direction out.35 min
  53. Matrices: tables of numbers FreeRows, columns and entries; two-dimensional arrays and slices; a data set as a matrix.41 min
  54. Adding, scaling and transposing matrices FreeEntry-by-entry sums and scalings, the transpose, mean images, and tables turned around.36 min
  55. A matrix times a vector FreeEach row dotted with the vector, the size rule, A @ x, and a layer acting on one example.42 min
  56. Matrix multiplication FreeRow meets column, the size rule, order matters, and a batch through a layer: X W + b.45 min
  57. Identity, diagonal, triangular and symmetric FreeFour patterns and their jobs: rescaling, distance tables, and the causal mask.37 min
  58. Matrices as movements of space FreeStretches, flips, shears and rotations; columns as landing spots; chaining; a layer moving data.42 min
  59. Determinant and inverse FreeThe area factor ad − bc, singular matrices, undoing a matrix, and redundant features.42 min
  60. Solving systems by elimination FreeAugmented matrices, row moves, back-substitution, the three outcomes, and fitting weights.45 min
  61. Independence, span and rank FreeRedundant vectors, span, rank, outer products, and low-rank updates like LoRA.42 min
  62. Eigenvectors: directions that only stretch FreeAv = λv, checking candidates, np.linalg.eig, and the main direction of a data cloud.41 min
  63. SVD and PCA: the important directions first FreeA matrix as pieces by size, the best rank-k copy, compression, and PCA maps of data.45 min
  64. Tensors, shapes and broadcasting FreeAxes and shapes, reshape, axis=, broadcasting, and shapes through a small model.43 min
  65. One-hot vectors and lookup tables: embeddings FreeA one-hot row picks a table's row, a sentence looked up as vectors, and a score for every word.35 min
  66. Sliding dot products: convolution FreeA small pattern slid along a list and over a grid, output sizes, stride and padding, and shared weights.40 min
  67. Review: find the slip (vectors and matrices) FreeShape slips to fix, mixed practice from the module, and its formula sheet with shapes.36 min
  68. Vector equations: rearranging with arrows FreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
  69. Matrix equations: multiply by the inverse, on the correct side FreeNo dividing by a matrix: inverses from the left or right, order, transposes, and the normal equations.40 min
  70. Rates of change FreeChange over change, secants, rates from readings with np.diff, and reading a loss curve.41 min
  71. Limits: what a value heads toward FreeApproaching from both sides, holes, corners and jumps, epsilon, and judging activations.37 min
  72. The derivative: slope at a point FreeShrinking secants, f′(x) and dy/dx, Δy ≈ f′Δx, and which way a weight should move.45 min
  73. Derivative rules FreeConstants, powers, multiples, sums, eˣ and ln x, checked numerically, and a squared error's slope.41 min
  74. The product rule and the chain rule FreeProducts and chains of functions, forward then backward, and one neuron's dL/dw.45 min
  75. Lowest points and curvature Freef′ = 0, the second-derivative test, tables, local and global minima, and convex losses.43 min
  76. Standing in for a curve near a point FreeTangent lines, a curvature term, growing error, and why learning rates must be small.37 min
  77. Partial derivatives FreeOne input at a time, ∂, nudging in Python, and the two slopes of a line's loss.41 min
  78. The gradient FreeAll the slopes as a vector, steepest climb and descent, a numerical gradient, and the loss gradient.42 min
  79. Gradient descent FreeStepping against the gradient, the learning rate, a training loop, and fitting a line.45 min
  80. Faster descent: momentum and Adam FreeMomentum and Adam by hand, the bias correction, and three optimizers down one narrow valley.40 min
  81. The chain rule with many paths: backpropagation by hand FreeGraphs, multiply along paths and add across them, gradient checks, and a 2-2-1 network by hand.45 min
  82. Automatic differentiation: how PyTorch finds every slope FreeA tape of steps walked backward, and requires_grad, backward(), .grad, zero_grad() and no_grad().40 min
  83. Jacobians and Hessians FreeSlopes of vector functions, a layer's Jacobian, second partials, and bowls, domes and saddles.42 min
  84. Integrals: adding up thin slices FreeStrip and trapezoid sums, summing undoes differencing, probability as area, and AUC.43 min
  85. Review: find the slip (calculus) FreeCalculus slips to fix, mixed practice from the module, and its formula sheet.36 min
  86. Rearranging in calculus: slopes, steps and constants FreeSetting a slope to zero, Newton's step, the chain rule turned around, constants from a point, and learning rates.45 min
  87. Counting: choices, orders and groups FreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
  88. Probability: from counts to chances FreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
  89. Combining events: and, or, independent FreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
  90. Conditional probability and Bayes' rule FreeConditionals from tables, why P(A | B) isn't P(B | A), Bayes' rule, and precision and recall.45 min
  91. Random variables and distributions FreeUncertain numbers, the probability of a range, sampling by slices, and sampling versus argmax.42 min
  92. Expected value, variance and standard deviation FreeProbability-weighted averages, spread in the data's own units, and a training loss as an expected value.42 min
  93. Bernoulli, binomial, uniform and normal FreeYes-or-no trials, counts of yeses, the 68-95-99.7 rule, z-scores, and an accuracy's error bar.45 min
  94. Two variables at once: covariance and correlation FreeJoint tables and marginals, covariance, correlation, the covariance matrix, and features that carry the same information.45 min
  95. Review: find the slip (probability) FreeProbability slips to fix, mixed practice from the module, and its formula sheet.36 min
  96. Probability formulas: solve for the missing chance FreeConditionals, Bayes' rule for the prior, the or rule, expected values, variance, and z-scores turned around.45 min
  97. Describing data: center, spread and scale FreeMean, median and mode, variance and standard deviation, percentiles, outliers, and standardizing features.42 min
  98. Samples, the law of large numbers and the central limit theorem FreeSamples and populations, the standard error σ/√n, the bell of averages, and error bars on test scores.43 min
  99. Is the difference real? Comparing two models FreePaired differences, a bootstrap interval, what a p-value is and isn't, and why many tries make lucky wins.40 min
  100. Maximum likelihood FreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
  101. Linear regression: the best line FreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
  102. Logistic regression: a line that answers yes or no FreeThe sigmoid, the log loss, its slope p − y, a training loop, and choosing a threshold.45 min
  103. Scoring a classifier: confusion table, precision, recall, F1 FreeThe four cells, accuracy, precision, recall and F1, and what moving a threshold does to each.35 min
  104. Softmax: scores into probabilities FreeExponentiate and share out, shifting and temperature, the safe softmax, and a classifier's last step.43 min
  105. Surprise, entropy and cross-entropy FreeSurprise in bits, entropy, cross-entropy and KL divergence, perplexity, and a language model's loss.45 min
  106. KL divergence: how far one distribution is from another FreeKL by hand, cross-entropy as entropy plus KL, why it isn't symmetric, and a soft-target loss.35 min
  107. Review: find the slip (statistics and information) FreeStatistics slips to fix, mixed practice from the module, and its formula sheet.38 min
  108. Statistics and information: n, z, logits and bits FreeSample sizes from error bars, inputs from probabilities, logit gaps from softmax, and chances from bits and losses.40 min
  109. One neuron, start to finish FreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
  110. A layer and a small network as matrices FreeTwo layers on a batch, the shape of every matrix, adding a hidden unit, and XOR solved.45 min
  111. Training a small network FreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
  112. The same network in PyTorch Freenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
  113. Attention as matrix math FreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
  114. Residual connections and layer norm FreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
  115. A transformer block, start to finish FreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
  116. Planning a model: rearranging the formulas of a working network FreeLayer widths from parameter counts, sizes from memory and compute, the attention scale, and a training plan.40 min
  117. Final test: transpose any formula FreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
  118. Capstone: a sign reader from the formulas FreeBuild, train and test a trail-sign classifier with NumPy alone, and report its accuracy with an error bar.45 min
Part of a free course 118 lessons

The Foundation Math For Ai & ML: from arithmetic to attention

Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write