Index Ai Academy
Foundation · Numbers

Ratios, rates and proportion

Sharing in a ratio, rates per unit, scaling, and splitting data 80/10/10.

About 35 minutes · Free lesson

What it covers6

Why it matters

Ratios compare amounts, rates turn "per" into a number, and proportion says how one amount moves when another does. Together they scale recipes, plan trips and share money. In machine learning they split a dataset into training, validation and test sets, and they price and time every job a language model runs, in tokens per second and dollars per thousand tokens.

What you'll be able to do

  • Read a ratio part to part and part to whole, simplify it, and share an amount in it
  • Find a rate by dividing, and use it to scale up and down
  • Tell direct proportion (y = kx) from inverse proportion (y = k/x), and find k
  • Split a dataset 80/10/10 in whole examples, and work out speed and cost from a rate
Quick check
Have a guess before you start. Pancakes for 4 people take 3 cups of flour. How much flour for 6 people?
  1. 2 cups
  2. 5 cups
  3. 6 cups
  4. 4.5 cups
Show the answer

4.5 cups

Each person needs 3 ÷ 4 = 0.75 cups, so 6 people need 6 × 0.75 = 4.5 cups. Or: 6 people is 1.5 times as many, so 1.5 times the flour.

The math: comparing amounts

Purpose. A ratio compares two or more amounts by how many times bigger one is than another. Recipes, maps, mixes and money all use them.

The ratio 2:3, read "2 to 3", says: for every 2 of the first, there are 3 of the second. That's part to part. The same mix can be read part to whole: there are 2 + 3 = 5 parts in all, so the first is 2/5 of the whole and the second is 3/5.

Like fractions, ratios simplify. 6:9 is the same mix as 2:3, since both sides divide by 3.

Sharing in a ratio. Add the ratio's numbers to count the portions. Divide the total to find one portion. Then give each part its count of portions.

Watch it for 450 dollars shared by Ana, Ben and Cai in the ratio 2:3:4. In the picture, the top bar is the money cut into equal portions. The bar under it groups those same portions by person, so each share sits right under the portions that make it.

Try it now

Each share is its part's count of portions. Then set the amount to share to 1000 and the ratio to 8, 1, 1 and press Use these numbers: the bar is cut 8:1:1, the split you'll use on data in the AI part.

Quick check
From the last lesson: what is 80% of 1,250?
  1. 1,170
  2. 100
  3. 1,000
  4. 1,562.5
Show the answer

1,000

80% is 0.8, and 0.8 × 1,250 = 1,000. You'll meet this exact split again in the AI part.

Symbols and formula. For a ratio a:b:c of a total T:

one portion=Ta+b+cshare of a=a×one portion\text{one portion} = \frac{T}{a + b + c} \qquad \text{share of } a = a \times \text{one portion}

In plain words: count the portions, divide the total by that count, then hand out each part's portions.

A quick check: the shares must add back to the total. 100 + 150 + 200 = 450.

Rates. A rate is a ratio with units, read with "per": 60 miles per hour, 3 dollars per pound. You find a rate by dividing. 150 miles in 3 hours is 150 ÷ 3 = 50 miles per hour. To scale, multiply a rate by an amount: in 5 hours at 50 miles per hour you go 250 miles.

Quick check
Share 60 in the ratio 1:2. What does the 2 part get?
  1. 120
  2. 40
  3. 20
  4. 30
Show the answer

40

1 + 2 = 3 portions, so one portion is 60 ÷ 3 = 20, and the 2 part gets 2 × 20 = 40.

Direct proportion. Two amounts are in direct proportion when one is always the same multiple of the other. Double one and the other doubles too. The multiple, k, is the constant of proportion, found by dividing. For the pancakes, k = 3 ÷ 4 = 0.75 cups per person, so 6 people need 0.75 × 6 = 4.5 cups.

y=kxy=kxy = kx \qquad y = \frac{k}{x}

In plain words: on the left, y grows in step with x. On the right, y shrinks as x grows.

Inverse proportion is the right-hand rule: double x and y halves. If 4 painters take 6 hours, k = 4 × 6 = 24 painter-hours, so 8 painters take 24 ÷ 8 = 3 hours. Here k is found by multiplying: the total work stays the same.

Quick check
Which pair is in inverse proportion?
  1. Cups of flour and the pancakes they make
  2. Painters on a job and its hours
  3. Hours worked and pay at a fixed hourly rate
  4. Miles driven and the gas a car uses up
Show the answer

Painters on a job and its hours

More painters share the same work, so the hours fall: double the painters, half the time.

Scale is a ratio too. A map's scale of 1:63,360 means 1 inch on the map stands for 63,360 inches on the ground, which is exactly a mile. Scaling works both ways: map to ground, multiply; ground to map, divide.

Recipes scale the same way. To serve 2 instead of 4, halve every amount, so the 3 cups of flour become 1.5. A ratio stays the same mix however big or small you make it, as long as every part is scaled by the same number. Scale one part and not the others, and the mix changes.

In your own words
In your own words: how can you tell direct proportion from inverse proportion?

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

In Python: shares and rates

Purpose. Sharing and rates are a few lines of division and multiplication. Count the portions, find one, then hand them out:

total = 1000
portion = total / (8 + 1 + 1)
print(portion * 8, portion * 1, portion * 1)
It runs right here in your browser, with nothing to install.

Each share is a float, because / always gives one.

Code flow. Step through a share, then a rate, one line at a time. The first half is the cell above with each share given a name; the second is the math part's 150 miles in 3 hours. Watch portion appear first, then the three shares built from it.

The shares must add back to the total, and that check is worth running every time:

import math

total = 1000
portion = total / 10
a = portion * 8
b = portion * 1
c = portion * 1
print(math.isclose(a + b + c, total))

Whole things can't be cut. You can't put 87.4 pictures in a set. When a total doesn't share out evenly, round the first parts down with // and give what's left to the last part, so nothing is lost:

total = 437
first = total * 8 // 10
second = total * 1 // 10
third = total - first - second
print(first, second, third)

A named mistake: dividing by the number of parts. The ratio 8:1:1 has three parts but 10 portions. Dividing by 3 ignores the ratio:

total = 1000
print(total / 3 * 8)      # wrong: more than the whole total
print(total / 10 * 8)     # right: 8 of the 10 portions

The first answer is bigger than the 1,000 being shared, a sure sign of a slip.

Worked example

Worked example: a road trip

A drive of 336 miles takes 6 hours and uses 12 gallons of gas. Find the speed, the miles per gallon, and the gas needed for a 434-mile trip.

miles = 336
hours = 6
gallons = 12
speed = miles / hours
mpg = miles / gallons
print("speed:", speed)
print("miles per gallon:", mpg)
print("gas for 434 miles:", 434 / mpg)
In the lesson you can change this and run it.

Both rates come from dividing by the thing after "per": miles per hour divides by hours, and miles per gallon divides by gallons. The last line runs a rate backward. Each gallon covers 28 miles, so 434 miles needs 434 ÷ 28 = 15.5 gallons. A sense check: 434 is a bit more than 336, so it should need a bit more than 12 gallons.

Quick check
What does this print?
total = 90
portion = total / (1 + 2)
print(portion, portion * 2)
  1. 45.0 90.0
  2. 30 60
  3. 30.0 45.0
  4. 30.0 60.0
Show the answer

30.0 60.0

1 + 2 = 3 portions, so one portion is 90 / 3 = 30.0, a float because / always gives one. The 2 part is 60.0.

Quick check
Which line gives a speed in miles per hour?
  1. hours / miles
  2. miles - hours
  3. miles * hours
  4. miles / hours
Show the answer

miles / hours

Per hour means divide by the hours.

Drill

Share an amount, price a rate

Set a, b and c to total shared in the ratio 8:1:1, and cost to the price of 15 pounds of apples at 2.40 dollars per pound. Each starter line has a slip.

total = 1000
portion = total / 3
a = portion * 8
b = portion * 1
c = portion * 1
cost = 15 / 2.40
print(a, b, c, cost)
In the lesson, your code is checked as you write it.
In your own words
Why give what's left over to the last part, instead of rounding every part?

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

In AI and ML: splitting data, and rates for tokens

Purpose. Before training, a dataset is split three ways: a training set to learn from, a validation set to tune choices on, and a test set kept aside for a final, honest score.

A common split is 80/10/10, the ratio 8:1:1. For n examples:

train=0.8nvalidation=0.1ntest=0.1n\text{train} = 0.8n \qquad \text{validation} = 0.1n \qquad \text{test} = 0.1n

In plain words: 8 of every 10 examples go to training, 1 to validation and 1 to test.

n = 1250
train = n * 8 // 10
val = n * 1 // 10
test = n - train - val
print(train, val, test)
Quick check
What does this print?
n = 500
train = n * 8 // 10
print(train, n - train)
  1. 400.0 100.0
  2. 400 100
  3. 80 420
  4. 4000 -3500
Show the answer

400 100

500 × 8 = 4000, and 4000 // 10 = 400, a whole number because // rounds down to one. The rest, 100, is left for validation and test.

In the real tools. In PyTorch, the library most models are built with, a dataset sits in a tensor, a block of numbers, one entry per example. Splitting it 8:1:1 is three slices, cut where the shares end: X[:80] takes the examples before number 80, X[80:90] those from 80 up to 90, and X[90:] the rest. Here are 100 examples, numbered from 0. Real code shuffles the examples first, so each set gets a fair mix: random_split, the name on the map, shuffles and cuts in one call.

Rates for language models. Language models read and write text in small pieces called tokens, often about three-quarters of a word each. Their speed is a rate, tokens per second. Their price is another, dollars per thousand tokens (or per million).

tokens = 6000
seconds = 40
print(tokens / seconds, "tokens per second")
price_per_thousand = 0.002
print(tokens / 1000 * price_per_thousand, "dollars")

To price a job, first count the thousands of tokens, then multiply by the price of each thousand. The same steps work for any rate: count the units the rate is "per", then multiply.

Quick check
A model writes 120 tokens per second. How long does it take to write 3,000 tokens?
  1. 2,880 seconds
  2. 25 seconds
  3. 0.04 seconds
  4. 360,000 seconds
Show the answer

25 seconds

Time is the amount divided by the rate: 3,000 ÷ 120 = 25 seconds.

Ratios hide in the data, too. Say 900 of 1,000 training signs are stop signs and 100 are yield signs: a ratio of 9:1. A lazy model that always answers "stop" is right 900 times in 1,000, so it scores 90% accuracy without learning anything.

stop = 900
yield_signs = 100
print(stop / yield_signs)             # 9 stop signs for every yield sign
print(stop / (stop + yield_signs))    # accuracy of always guessing stop

So before trusting an accuracy, check the ratio of the classes. A score is only good if it beats always guessing the most common answer. (The name yield_signs is used because yield is a word Python keeps for itself.)

Drill

Plan a dataset and a job

Split n examples 80/10/10: train and val rounded down with //, and test getting the rest. Then set seconds to the time for a job of 9,000 tokens at 150 tokens per second, and dollars to its cost at 0.002 dollars per thousand tokens.

n = 3456
train = n * 8 / 10
val = n * 1 / 10
test = n * 1 / 10
seconds = 9000 * 150
dollars = 9000 * 0.002
print(train, val, test, seconds, dollars)
In the lesson, your code is checked as you write it.
In your own words
Why does a model's test set get split off before training, in a fixed share?

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

Goes deeper in

Practice what you just read

  • 8 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

Simplify the ratio 15:25.

  1. 3:5
  2. 1:10
  3. 5:3
  4. 3:25

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