Preface
This book is a personal study log for Mathematics for Machine Learning by Marc Peter Deisenroth, A. Aldo Faisal and Cheng Soon Ong. It is not a textbook and it is not a substitute for one: it is a record of working through the book section by section, with the reasoning, the dead ends and the corrections left visible.
Who these notes are for
The notes are written for a reader with an applied-mathematics and professional background — school and additional mathematics, ACCA, and hands-on implementation of Oracle MRP — who wants the formalism of the book connected to practice rather than left floating. Concretely, that means:
- Formal statements are kept, but always attached to an interpretation. A system is described both as a matrix equation and as a resource-consumption ledger.
- Operational framings are compared explicitly. When the book’s model differs from how a real planning or optimisation system behaves, the differences are tabulated rather than glossed over.
- Claims are checked. Numerical claims in a note are backed by a runnable script in
scripts/, and mistakes are corrected in place with a dated Corrections and additions section instead of being quietly edited away.
How each note is built
Every note follows the same shape, described in detail in docs/note-format.md:
- The question — the question that motivated the note, reproduced as asked.
- Screenshots — the page or pages of the book under discussion, so the note is self-contained.
- Response — the answer that was given, edited only for formatting.
- Corrections and additions — later fixes, extensions and clarifications, each dated and each stating what it supersedes.
- References — a link back to the exact section of the book.
Attribution
The notes, commentary, explanations and any code in this repository are original work. Quoted excerpts from the book are short and are included for study and criticism; the book text, its figures, and the page images reproduced here remain © the authors and their publisher. See References for the full citation and a link to the book, which is freely available from the authors.
How to read these notes
This page is a short orientation. The Preface explains why the book exists; this page explains how to find things.
One note per book section
Each note covers exactly one section of Mathematics for Machine Learning and is named after it, so the table of contents mirrors the book:
| Book section | Note |
|---|---|
| 2.1 Systems of Linear Equations | 2.1 Systems of Linear Equations |
Further notes are added as the corresponding sections are read. Coverage at any moment is
tracked in docs/state.md in the repository.
Each note is self-contained
A note contains the substance of the question that triggered it, any page images it rests on, the answer, how the idea is used in practice, and a worked example with concrete numbers. You should be able to read a single note in isolation without the conversation it came from.
Notes are compact and applied
Notes are study aids, not transcripts. Each one is expected to answer four things: what was
asked, the answer, where it shows up in real systems (MRP, ERP, scheduling,
optimisation), and a worked example with actual numbers rather than abstract
coefficients throughout. Numbers are reproducible from the scripts under scripts/.
Notes may be revised in place
Since 2026-09-30 a note may be rewritten into its best current form rather than keeping a layered history on the page — git history is the archive. When a later insight would confuse the main line, it can instead go in a dated Corrections and additions section that says what it supersedes. The first note has one of these, which is worth reading as an example of that convention: the original response contained an incorrect numerical illustration, and the correction states exactly what was wrong and what the verified result is.
Runnable claims
Where a note makes a numerical claim, a script under scripts/ reproduces it. The
scripts require only a Python 3 with numpy. See scripts/README.md.
python3 scripts/explore_example_2_1.py
Building this book locally
The book is built with mdBook and the
mdbook-katex preprocessor (which is what renders the mathematics):
make serve # live preview at http://localhost:3000
make build # static output in ./book
make check # build, then confirm ./book stays out of git
make help # all targets
Build through make (or plain mdbook build / mdbook serve). Nothing is
vendored: mdbook-katex injects the <link> for the KaTeX build it renders with,
so the page loads that one stylesheet from a CDN and the mathematics always
matches the stylesheet.
Linear Algebra
Notes on Chapter 2, Linear Algebra, of Mathematics for Machine Learning — the first chapter of Part I, Mathematical Foundations.
Chapter 2 builds the vocabulary that the rest of the book leans on: systems of linear equations, matrices, solving systems, vector spaces, linear independence, bases and rank, linear mappings and affine spaces. It closes with further reading; norms, inner products and orthogonality — the tools of Chapter 3’s analytic geometry — come next.
Notes in this part
| Section | Note | Status |
|---|---|---|
| 2.1 Systems of Linear Equations | 2.1 Systems of Linear Equations | done |
| 2.2 Matrices | 2.2 Matrices | done |
| 2.3 Solving Systems of Linear Equations | 2.3 Solving Systems of Linear Equations | done |
| 2.4 Vector Spaces | — | not started |
| 2.5 Linear Independence | — | not started |
| 2.6 Basis and Rank | — | not started |
| 2.7 Linear Mappings | 2.7 Linear Mappings | done |
| 2.8 Affine Spaces | — | not started |
| 2.9 Further Reading | — | not started |
The authoritative, machine-readable version of this table is docs/state.md in the
repository. Section titles were checked against the book’s own table of contents
(2024 free PDF at mml-book.com): Chapter 2 runs 2.1–2.8, and 2.9 is “Further
Reading” — there is no affine-mappings section in this chapter. The prose above
mentions affine mappings only because they appear later, in the context of affine
spaces.
A note on the ordering
Notes follow the book’s own section numbering rather than a reading order chosen here, so a note for Section 2.7 can be added before Section 2.5 without renumbering anything. The first note was prompted by a question about the production-plan model in Example 2.1, which is why Chapter 1 (Introduction and Motivation) has no notes yet.
The book is deliberately read out of order. Nuggets — short forward notes capturing how a concept gets applied, written before the chapter is reached — live in later chapters alongside the full section notes, and are marked on the page as unchecked against the book. See the gradient descent nugget for an example.
2.1 Systems of Linear Equations
The question
Reading Example 2.1 (the production-plan model) with a background of SPM/additional mathematics, ACCA and a hands-on Oracle MRP implementation:
The question (in substance), 2026-09-29:
These are from Mathematics for Machine Learning. Having studied SPM math and additional math, ACCA and implemented Oracle MRP, this production plan doesn’t make sense. Is it listing out each individual resource?
The instinct to push back is correct, and the mismatch is structural rather than a misreading of the algebra.
Screenshots
The two pages the question refers to, from Section 2.1 “Systems of Linear Equations”.
Answer
Short answer: yes — but only in the accounting sense, and that is exactly why it does not line up with MRP.
Attention to the indices is what makes (2.3) readable:
- runs over resources (steel, machine hours, labour, …)
- runs over products
- = units of resource needed for one unit of product
- = the unknown decision variable: how many units of product to make
- = units of resource available
Each row is one resource’s conservation statement:
Each column is one product’s recipe — its resource-consumption vector . So is with rows = resources, columns = products, and is the -dimensional resource-availability vector.
Two things the framing leaves loose:
- “Optimal” does no work in (2.3). The system is only the feasibility constraint set: consume exactly what is available, leaving nothing over. Optimality needs a separate objective (max profit, min cost), which is where linear programming enters. (2.3) alone just says “don’t waste material.”
- The row/column reading is the whole content. Reading a row gives one resource’s demand ledger; reading a column gives one product’s bill of materials.
Why only two indices. is the simplest version of the model. It assumes every unit of resource is interchangeable regardless of when it is bought or where it is stored, and every unit of product is identical regardless of which factory makes it or which customer buys it. Drop either assumption and one index is not enough — resource in factory during week for customer is , and stops being a matrix. It becomes a tensor, which is exactly what deep-learning frameworks manipulate (and part of why the book’s 2-D framing is deliberately a simplification). The general structure survives — resources still balance against supply — but the object is no longer a matrix and the algebra is no longer matrix multiplication.
In practice
The gap between (2.3) and a real MRP run is the point of the example, not a defect in it:
| Textbook (2.3) | Oracle MRP / ERP | |
|---|---|---|
| Structure | one flat level, all products independent | multi-level BOM explosion, parent → component |
| Coefficients | fixed for the whole problem | per-item, per-BOM quantity-per-assembly, often phantom/optional |
| Time | a single static period | time-phased buckets, lead times, offsets |
| Quantities | any real number | order quantities, lot-sizing rules, sometimes integer |
| Resource | an equation to satisfy exactly | a capacity check you may violate (overload/underload) |
In MRP terms, is roughly the quantity-per-assembly, is roughly available supply/capacity, and solving is a single-level, infinite-capacity, exact-satisfaction feasibility question. Oracle MRP instead performs recursive netting (gross requirement → on-hand → scheduled receipts → net requirement → planned orders), which is why the example feels incomplete: it captures the arithmetic of resource consumption while dropping all the machinery MRP adds.
The most consequential difference is the last row of that table. (2.3) demands that every resource be consumed exactly. Real planning almost never wants that — it wants to stay feasible under capacity and then optimise. That distinction is what makes §2.3’s free-variable machinery, and later the whole optimisation half of the book, necessary.
Worked example
Two resources, three products. Let resource 1 be plastic and resource 2 be wire:
so each unit of product 1 needs 2 plastic and 1 wire, and so on. Here but there are unknowns, so
The null space is spanned by the exact integer vector
which is easily checked by hand. So the minimum-norm solution is not the only plan: every
is an exact solution of , e.g.
| plan | ||
|---|---|---|
All four consume exactly 100 plastic and 80 wire. No MRP run would ever return a one-parameter family — it returns one plan. That single fact is the crux of the intuition, and it is the question §2.3 answers (the choice is the free variable).
The freedom can be larger. Drop one independent constraint by making resource 2’s row a multiple of resource 1’s:
Now , so and the solution set is a plane through . In general the number of free directions is — this is the single most useful fact for reading the rest of the chapter, and §2.3 shows what the book does with it.
Every number in this section is reproduced by scripts/explore_example_2_1.py.
Corrections and additions
2026-09-30 — the earlier “correction” below was itself wrong; this page now carries the correct result
This page previously argued that because , the matrix has “full row rank” and therefore a trivial null space, making the unique solution. That is false. Full row rank does not imply a unique solution when . With and , , and the null space is — verified above in exact integer arithmetic. The original claim of infinitely many exact plans was right; the correction that retracted it was wrong, and has been removed. The lesson recorded here is the real one: a null-space claim must be checked against , not against whether the rows are independent.
References
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning, Section 2.1 (“Systems of Linear Equations”), Example 2.1 and Equations (2.2)–(2.3). See References for the full citation and link.
- Reproducibility script:
scripts/explore_example_2_1.py.
2.2 Matrices
The question
Three related questions that came up around the end of §2.1 and the start of §2.2:
The questions (in substance):
- Why does the book talk about a “transformation” instead of just solving the system?
- Going back to the simple example, how do you decide what goes into which part of — what are the rows, the columns, and ?
- If you scale up production by 10×, does resource consumption scale by 10×? If you rotate your perspective, does the system look simpler?
All three are really the same question: what are the objects in , beyond being an array of numbers?
Answer
A matrix is a transformation, not just a table
A matrix is a function that takes a vector and returns a vector. Writing says “apply the map to and get ”. Solving is then inverting the map: given the output, recover the input. Both readings are the same equation — which is exactly why the same algebra models planning and prediction.
What makes it a linear map is two properties, and they are worth stating precisely because “linear” does not mean “a straight line”:
Homogeneity is what answers question 3’s first half: yes, scaling the plan by 10× scales every resource total by exactly 10×. That is the defining property, not a coincidence of the example. (Note with is not linear in this sense — it is affine, because . §2.7 returns to that distinction.)
What goes where
| Object | How to decide | In the factory |
|---|---|---|
| Rows of | every distinct thing that must be balanced or tracked | resources: plastic, wire, dye |
| Columns of | every distinct thing you control or every feature you have | products: blue, lavender |
| the relationship — how much of row one unit of column consumes | the BOM / recipe | |
| what you are solving for — the free decision | production plan | |
| the known side — outcome or constraint | inventory limits |
This is a modelling choice, not a mathematical one, and it is where the domain knowledge lives.
The same equation read in two directions
The knobs flip depending on which side is known:
| MRP / planning | Weather / prediction | |
|---|---|---|
| Input | unknown production plan | known current atmospheric state |
| Transformation | known recipe (BOM) | learned model weights |
| Output | known inventory limits | unknown predicted future state |
In MRP you know the limits and hunt for the plan, so is unknown. In weather prediction you know today’s state and apply a learned map to get tomorrow’s, so is the input and is what you predict. Identical algebra, and this is the sense in which §2.2’s “transformation” framing is the more general one: it survives the change of which side is known.
“Rotating your perspective” = choosing a different basis
This does not mean spinning the factory. It means asking whether a different set of variables makes the system easier to read — a change of basis. For the factory, the natural alternative coordinates are how much in total and in what ratio:
In practice
The basis question is not academic. Which coordinates you pick is often the difference between a model that works and one that does not, because it decides which structure is visible to the algebra. In the worked example below the change of basis does not change the answer — the same plan still consumes the same resources — but it separates two business questions that were tangled together:
- is the volume problem: how much do we make in total?
- is the mix problem: what ratio of blue to lavender?
Real planning systems make exactly this separation, because volume is driven by demand and capacity while mix is driven by margin and promotion. Principal component analysis (Chapter 10) is the machine-learning version of the same move: find the coordinates in which the data’s structure is simplest. This note stops at the mechanism; §2.7 gives the general language for linear maps.
Worked example
A four-resource, two-product factory. Rows are resources, columns are products:
Making 7 blue and 3 lavender consumes — 20 plastic, 10 wire, 21 blue dye, 12 lavender dye.
Now change to the volume/mix basis. Since and ,
The system becomes , i.e. the new matrix is :
Look at what happened to the mix column. Plastic and wire have a there: they depend only on total volume, so the “how much” question is fully decoupled from the “in what ratio” question. Only the dyes care about the mix. The same plan expressed in the new coordinates, blue and lavender , gives — identical to , as it must be.
The matrix is not diagonalised: it is , not square, so diagonalisation is not even defined. What the change of basis achieved is weaker and more useful — a column of structural zeros.
All numbers above are reproduced by scripts/explore_example_2_2.py.
References
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning, Sections 2.1–2.2 (Systems of Linear Equations; Matrices). See References for the full citation and link.
- Reproducibility script:
scripts/explore_example_2_2.py. - Related notes: 2.1 Systems of Linear Equations, 2.3 Solving Systems of Linear Equations, 2.7 Linear Mappings.
2.3 Solving Systems of Linear Equations
The question
Two things are being asked here: a complaint about how the book introduces the free variable, and two concrete questions about it.
The complaint, in substance:
The authors do that thing again — dropping a formula or concept when it will not be used until way later. Equation (2.7) appears with no explanation of why it looks like that.
The follow-up questions:
- Could any of the variables have been chosen as the free variable?
- Can there only ever be one free variable?
The complaint is fair, with a caveat worth stating precisely (see below): the book does define the free variable, but it does not say where the number of free variables comes from, nor that the choice of which one is free is arbitrary — and both are exactly what the two questions are about.
Screenshots
The passage under discussion — Equations (2.6)–(2.7) from §2.3, and the sentence that closes the example.
Answer
What the book actually does
Equation (2.6) is three equations in three unknowns:
Adding (1) and (2) gives , which is exactly (3). So (3) is redundant — it carries no information — and the system has only 2 independent constraints for 3 unknowns. The book then fixes and writes the solution set as
This is all correct. What it does not say is the reason the formula has one free parameter, or what would happen if you chose differently.
The reason: the count is
Write the system as . The number of free variables is the dimension of the null space of , and for an -column matrix that is
Here and the redundant third row leaves , so : exactly one free variable. That is the whole content of (2.7), and it is the fact the book defers — it is the language of §2.6 (basis and rank) and §2.7. The deferral is real, and it is why the formula looks unmotivated at this point.
This also gives a clean answer to both follow-up questions:
- Could any variable have been the free one? Yes. The free variable is a choice of basis for the null space, not a property of any particular column. Parameterising by instead gives a different-looking formula for the same solution set.
- Can there be only one? No — there are of them. Change the matrix and the count changes.
Why the choice is genuinely arbitrary
Solving with and with must describe the same set, because both are parameterisations of the same affine subspace. For (2.6):
They coincide whenever . At (so ) both give exactly . The factory does not care which variable you declare free — it is bookkeeping about which decision you make first.
In practice
This is the point where the book stops describing planning and starts needing optimisation, and the free variable is the hinge.
In MRP terms the free variable is “the one you decide first”: “I’ll decide how many red ones to make, then blue and lavender follow.” In the hairpin factory of 2.1 the same structure separates the volume decision from the mix decision. Real planning systems pick one of these and optimise around it, because an underdetermined system is not an answer — it is a family of answers, and something must break the tie.
That tie-breaker is where the whole optimisation half of the book comes from. The book’s own remark about finding “the solution with the smallest weights” is the same idea, and it splits into two well-known rules:
- L2 / Ridge — minimise : shrink everything smoothly, no weight dominates. This is the minimum-norm solution of an underdetermined system.
- L1 / Lasso — minimise : drive most weights to exactly zero, leaving a sparse, interpretable solution.
Choosing which free-variable combination to keep is therefore not a mathematical detail; it is the modelling decision, and it reappears throughout Chapters 7–12.
Worked example
The system (2.6) above, verified end to end:
- Redundancy: row 3 = row 1 + row 2 exactly, and . So the third equation is discarded.
- Rank: singular values give , hence .
- Book’s parameterisation satisfies exactly for every — checked at , each with residual .
- Alternative also satisfies it at every tested, and the two parameterisations agree as shown above.
The count generalises, and the script checks it against real matrices rather than asserting it:
| System | Shape | Rank | Free variables | Outcome |
|---|---|---|---|---|
| 5 unknowns, 2 constraints | 2 | infinitely many solutions | ||
| 5 unknowns, 5 constraints | 5 | unique solution | ||
| 6 constraints, one redundant | 5 | unique solution | ||
| 6 constraints, one incompatible | 5 | no solution |
The last two rows are the useful lesson: free variables are governed by rank, but whether a solution exists at all also depends on . Having more equations than unknowns does not by itself make a system inconsistent — it makes it likely to be.
All numbers are reproduced by scripts/explore_example_2_3.py.
References
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning, Section 2.3 (“Solving Systems of Linear Equations”), Equations (2.6)–(2.7). See References for the full citation and link.
- Reproducibility script:
scripts/explore_example_2_3.py. - Related notes: 2.1 Systems of Linear Equations, 2.2 Matrices.
2.7 Linear Mappings
The question
Two questions that both come down to what the word “linear” is actually claiming:
The questions (in substance):
- “Linear” in linear algebra doesn’t mean a straight line, does it?
- Not all functions are vectors — is that right?
The short answer to both is no, not in the everyday sense and right, but with a precise caveat. This note is about the precise version.
Answer
The two rules
A map is linear when it satisfies exactly two properties:
In words: adding inputs then mapping gives the same result as mapping then adding, and scaling the input scales the output by the same factor. A matrix map satisfies both by the distributivity of matrix multiplication, which is why matrices are the linear maps.
Homogeneity is also the answer to the §2.2 question about scaling production by 10×: the resource totals scale by exactly 10×, and that is the definition, not a property of the particular example.
Why “straight line” is the wrong picture
A line through the origin, , is linear. But so is a great deal that is not a line:
- — a flat plane in 3D. Doubling and doubles ; adding two points adds their values.
- A matrix that rotates, shears, reflects or stretches space. Grid lines stay straight and parallel; a square can become a parallelogram. Still linear.
- The production model : make twice as much, consume twice as much.
What is not linear:
That last one is affine, not linear. The test is immediate: a linear map must send zero to zero, because . Since , it fails. This is why the book is careful to separate linear mappings (§2.7) from affine mappings (§2.8) — and it is the same distinction, one dimension down, as “why doesn’t the straight line count”.
Are functions vectors?
The word “function” is doing two different jobs here, and separating them resolves the question:
| Sense | What it is | A vector? |
|---|---|---|
| A function as an object | a point in a function space, e.g. | Yes, if its set satisfies the vector-space axioms |
| A function as a transformation | an operation that acts on vectors, e.g. | No — it acts on the space rather than living in it |
Functions-as-objects can be added and scaled in the obvious way:
so the collection of such functions is a vector space and each individual function is a vector in it. A function is essentially a very long (often infinite) list of values. The caveat is that a set of functions is only a vector space if it satisfies the axioms: all continuous functions do, polynomials of degree do, but functions taking only positive values do not (no zero, no additive inverses). The axioms themselves are §2.4; the point here is only that “function” and “vector” are not mutually exclusive categories.
In practice
This is the distinction that machine learning runs on, and it is why the notation gets confusing:
- Data points are vectors — an image is a vector of pixel values.
- Model parameters are vectors — the weights you learn.
- A model is a function — it maps input vectors to output vectors.
Training searches a vector space of functions for the function that best maps inputs to outputs. So the model is simultaneously a point in a space (a vector) and a transformation (an operator), which is exactly the ambiguity above.
The concrete payoff is embeddings. Word and image embeddings live in spaces of hundreds to thousands of dimensions, and we cannot visualise them — but we can compute with them, because the rules are identical to the 2D case, just with more arithmetic. A learned embedding is in effect a rotation of the space: an orthogonal matrix, whose columns are mutually perpendicular and unit length, so relative distances and angles are preserved while the axes are chosen to make structure visible. That is the same change-of-basis idea as 2.2, scaled up — and it is why “the model learned a rotation” is often a more useful description than “the model learned weights”.
Worked example
Both rules hold for a matrix map. With , , , :
Failure modes, with numbers. For componentwise, at and :
so additivity fails. For the affine : , so it cannot be linear — homogeneity fails on the constant term.
A rotation is linear and preserves length. With ,
Both linearity rules hold, and lengths are preserved — a pure rotation with no stretching. The identical construction in 5D (a orthogonal matrix, 25 entries) also preserves the norm, which is the sense in which “rotation” still means something once you can no longer draw it.
All numbers are reproduced by scripts/explore_example_2_7.py.
References
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning, Section 2.7 (“Linear Mappings”); the function-space axioms are §2.4 and affine mappings §2.8. See References for the full citation and link.
- Reproducibility script:
scripts/explore_example_2_7.py. - Related notes: 2.2 Matrices.
Continuous Optimization
Chapter 7, Continuous Optimization, is where the book stops asking “where do these equations intersect?” and starts asking “where is the bottom of the valley?”. The exact algebra of Chapter 2 gives way to iterative methods, because real models have far too many parameters and far too much noise for a closed-form answer to exist.
Notes in this chapter
| Section | Note | Status |
|---|---|---|
| 7.1 Optimization Using Gradient Descent | — | not started |
| 7.2 Constrained Optimization and Lagrange Multipliers | — | not started |
| 7.3 Convex Optimization | — | not started |
| 7.4 Further Reading | — | not started |
Nuggets (captured ahead of reading)
Forward notes, scribbled on hearing how the idea gets applied. They are not checked against the book yet and are marked as such on the page itself.
| Nugget | Captured |
|---|---|
| Nugget: gradient descent — walking downhill when there is no closed form | 2026-09-30 |
Nugget: gradient descent
Captured ahead of reading. This is a nugget — an application sketched before reaching the chapter, the kind of thing a student scribbles down on hearing about it. It has not been checked against §7.1 yet, and the numbers come from
scripts/explore_nugget_gradient_descent.py, not from the book. Treat it as a pointer, not as verified notes.
The nugget
When you cannot solve for the answer in one algebraic move, you can still walk towards it. Stand somewhere on the loss surface, look at the slope under your feet, take a step downhill, and repeat. That is gradient descent.
The reason this matters for machine learning is not that it is elegant — it is that it is the only thing that scales. A linear system can be solved directly, but a model with millions of parameters and noisy data has no closed form, and the “answer” does not exist anyway: there is no exact intersection to find, only a valley to descend into.
The whole idea fits in one update rule:
where is the learning rate — how big a step to take.
In practice
Every practical training loop is this rule wearing different clothes. What changes is how the step size is chosen, because a fixed is fragile:
- Too small — correct but agonisingly slow; you run out of patience or budget before you arrive.
- Too large — the iterates overshoot and diverge; the loss grows instead of falls.
- Just right (but only locally) — fast near the start, then it stalls in flat regions or rattles around a narrow valley.
That is why real systems use learning-rate schedules, momentum, and adaptive methods (AdaGrad, RMSProp, Adam) rather than one number. It is also why the loss surface’s shape matters more than its minimum: an elongated valley forces a small step size in the steep direction while the shallow direction would allow a large one.
The same machinery answers the question the book asks later about local minima: a ball rolling downhill stops in the first dip it reaches, which need not be the lowest point in the landscape.
Worked example
Take a 2-D quadratic with a known minimum, so the iterates can be compared against ground truth:
The exact minimum is with . The curvature (eigenvalues of ) is and , so stability requires
Starting from :
| after 25 steps, distance to | outcome | |
|---|---|---|
| correct but still en route — far too slow | ||
| converged | ||
| (8 steps) | diverged |
At the residual falls from to essentially zero in 25 steps. At the loss rises from to in eight steps. The rule never changes; only the step size does.
All numbers above are produced by scripts/explore_nugget_gradient_descent.py.
References
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning, §7.1 “Optimization Using Gradient Descent” (material to read; not yet checked). See References for the full citation and link.
- Reproducibility script:
scripts/explore_nugget_gradient_descent.py. - Related notes: 2.3 Solving Systems of Linear Equations for the exact case this replaces.
When Models Meet Data
Chapter 8, When Models Meet Data, is the hinge between the mathematical foundations and the machine-learning algorithms. It is where the book asks what it means to learn from data: empirical risk minimisation, parameter estimation, probabilistic modelling, and the practical question of how to avoid fitting noise.
Notes in this chapter
| Section | Note | Status |
|---|---|---|
| 8.1 Data, Models, and Learning | — | not started |
| 8.2 Empirical Risk Minimization | — | not started |
| 8.2.3 Regularization to Reduce Overfitting | — | not started |
| 8.3 Parameter Estimation | — | not started |
| 8.4 Probabilistic Modeling and Inference | — | not started |
| 8.5 Directed Graphical Models | — | not started |
| 8.6 Model Selection | — | not started |
Nuggets (captured ahead of reading)
Forward notes, scribbled on hearing how the idea gets applied. They are not checked against the book yet and are marked as such on the page itself.
| Nugget | Captured |
|---|---|
| Nugget: L1 vs L2 regularization — what “smallest weights” actually means | 2026-09-30 |
Nugget: L1 vs L2 regularization
Captured ahead of reading. This is a nugget — an application sketched before reaching the chapter. It has not been checked against §8.2.3 yet, and the numbers come from
scripts/explore_nugget_regularization.py, not from the book. Treat it as a pointer, not as verified notes.
The nugget
This one closes a loop left open by 2.3 Solving Systems of Linear Equations. When a system is underdetermined it has a whole family of exact solutions, and something must break the tie. The book’s phrase for the tie-break is “find the solution with the smallest weights”.
Smallest in which sense? That is not one question but two, and the two answers have completely different characters:
- L2 / Ridge — minimise , the sum of squares.
- L1 / Lasso — minimise , the sum of absolute values.
Both say “keep the weights small”. Only one of them produces zeros.
The geometric reason for the difference: the L2 penalty’s level sets are circles, so the optimum can land anywhere on the smooth boundary. The L1 penalty’s level sets are diamonds with corners on the axes, and an optimum is drawn towards a corner — and a corner means one or more coordinates are exactly zero.
In practice
This is a genuine modelling choice, not a numerical detail, and it maps onto a question a planner already asks: which drivers actually matter?
- L2 (Ridge) — use it when you believe every feature contributes a little. Nothing is discarded; the blame is spread evenly and no single weight dominates.
- L1 (Lasso) — use it when you believe most features are useless. It performs automatic feature selection by killing coefficients outright, giving a sparse and interpretable model.
In MRP terms: a demand model might start with dozens of candidate drivers — season, promotion, price, weather, competitor action. L2 gives you a model where all of them have small non-zero effects; L1 tells you which three actually matter and sets the rest to zero. The second is usually what a human wants to read, and it is the one you can hand to a planner.
The two are often combined as elastic net (), which keeps L1’s sparsity while letting correlated features share weight — L1 alone will arbitrarily pick one of two identical features and discard the other.
Worked example
An underdetermined system — 3 equations, 6 unknowns, so and there are infinitely many exact fits. A tie-break is genuinely forced.
At :
| Solution | exact zeros | fit | ||
|---|---|---|---|---|
| minimum-norm (no penalty) | 0 of 6 | 1.2147 | 2.3844 | exact |
| Ridge / L2 | 0 of 6 | 1.1431 | 2.2573 | approx () |
| Lasso / L1 | 3 of 6 | 1.2088 | 1.9669 | approx () |
The penalised rows fit worse than the unpenalised one — that is the point: they trade a little accuracy for smaller, simpler weights. Ridge shrinks but never selects; Lasso sets half the coefficients to exactly zero.
Sweeping the penalty strength:
| ridge zeros | lasso zeros | |||
|---|---|---|---|---|
| 1.2131 | 0 | 2.1272 | 3 | |
| 1.1431 | 0 | 1.9669 | 3 | |
| 0.7662 | 0 | 0.4953 | 3 | |
| 0.6365 | 0 | 0.0000 | 6 | |
| 0.3894 | 0 | 0.0000 | 6 |
Ridge shrinks smoothly and never reaches exact zero at any strength. Lasso holds a sparse solution across a wide range and then collapses entirely to zero once exceeds the largest entry.
Because the Lasso solution is computed iteratively (ISTA), every reported solution is checked against the subgradient optimality conditions before being quoted — a half-converged iterate would otherwise look like an answer.
All numbers above are produced by scripts/explore_nugget_regularization.py.
References
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning, §8.2.3 “Regularization to Reduce Overfitting” (material to read; not yet checked); see also §9.2.4 “MAP Estimation as Regularization”. See References for the full citation and link.
- Reproducibility script:
scripts/explore_nugget_regularization.py. - Related notes: 2.3 Solving Systems of Linear Equations.
Dimensionality Reduction with PCA
Chapter 10, Dimensionality Reduction with Principal Component Analysis, is the first place the book uses the linear algebra of Part I to do something recognisably machine-learning: take data with many columns, find a smaller set of directions that carries the structure, and discard the rest.
Notes in this chapter
| Section | Note | Status |
|---|---|---|
| 10.1 Problem Setting | — | not started |
| 10.2 Maximum Variance Perspective | — | not started |
| 10.3 Projection Perspective | — | not started |
| 10.4 Eigenvector Computation and Low-Rank Approximations | — | not started |
| 10.5 PCA in High Dimensions | — | not started |
| 10.6 Key Steps of PCA in Practice | — | not started |
| 10.7 Latent Variable Perspective | — | not started |
| 10.8 Further Reading | — | not started |
Nuggets (captured ahead of reading)
Forward notes, scribbled on hearing how the idea gets applied. They are not checked against the book yet and are marked as such on the page itself.
| Nugget | Captured |
|---|---|
| Nugget: PCA as a change of basis — rotating a space so the axes carry the signal | 2026-09-30 |
Nugget: PCA as a change of basis
Captured ahead of reading. This is a nugget — an application sketched before reaching the chapter, on hearing how PCA gets used. It has not been checked against §10.2–§10.3 yet, and the numbers come from
scripts/explore_nugget_pca.py, not from the book. Treat it as a pointer, not as verified notes.
The nugget
PCA is not “delete some columns”. It is the same change of basis idea as 2.2 Matrices, applied to data: keep every colour, but re-express the data on new axes chosen so that the first axis carries as much of the variation as possible, the second carries as much of what is left, and so on.
Then — and only then — you throw away the last axes, because by construction they carry almost nothing but noise.
The payoff is that you can compress, denoise and visualise data without losing the signal, and the new axes often turn out to be interpretable summaries that nobody explicitly programmed:
That is the “nugget” worth scribbling down: the axes PCA finds are frequently the business questions you would have asked anyway, discovered rather than specified.
In practice
This is why PCA shows up almost everywhere data has many columns:
- Compression and storage — keep the leading components and reconstruct approximately; the discarded directions are mostly measurement noise.
- Visualisation — project a space you cannot draw down to two or three dimensions that you can.
- Denoising — the small-variance directions are where the noise lives, so dropping them removes noise and keeps signal.
- A change of coordinates for modelling — a regression on components instead of raw columns can be far better conditioned, because the components are uncorrelated.
The scale of modern embeddings is the reason this is computed rather than drawn: word embeddings of a few hundred dimensions, image embeddings of or , and language-model representations in the thousands. None of them can be plotted. All of them can be rotated, because the arithmetic is identical to the 2-D case.
One honest caveat, which the worked example below demonstrates rather than hides: PCA finds directions of maximum variance, not causes. A component that explains a lot of variance may be a mixture of several real effects, and a small component may still be the one you care about. It is a compression tool that is sometimes interpretable — not an explanation engine.
Worked example
Fifty-two weeks of sales for five hairpin colours, built deliberately from three known latent effects plus noise:
- overall demand — all five colours move together;
- warm/cool mix — blue + lavender against red + green + yellow;
- yellow promotion — yellow on its own.
PCA is run on the data without being told any of that. Because the true effects are known (they generated the data), it is then possible to ask honestly whether PCA recovered them:
| Component | variance explained | cumulative | best-matching true effect (cosine) |
|---|---|---|---|
| PC1 | 69.2% | 69.2% | overall demand (0.995) |
| PC2 | 28.4% | 97.6% | warm/cool mix (0.955) |
| PC3 | 1.9% | 99.5% | yellow promotion (0.767) |
| PC4 | 0.2% | 99.8% | — |
| PC5 | 0.2% | 100.0% | — |
Two components carry 97.6% of the variance, so a 5-column problem collapses to 2 columns with 2.4% discarded. The loadings confirm what those two axes are — PC1 has all five colours with the same sign (everything moves together), while PC2 has blue + lavender opposing red + green + yellow:
| blue | lavender | red | green | yellow | |
|---|---|---|---|---|---|
| PC1 | |||||
| PC2 | |||||
| PC3 |
The interesting part is PC3. It matches the yellow promotion only partially (0.767), because yellow participates in both the warm/cool effect and the promotion. The third real effect is entangled with the second, so PCA cannot cleanly separate it — even though we, who built the data, know it is there. That is the caveat above, made concrete: PC1 and PC2 recovered the strong effects almost exactly, and PC3 did not.
All numbers above are produced by scripts/explore_nugget_pca.py.
References
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning, §10.2 “Maximum Variance Perspective” and §10.3 “Projection Perspective”, with §4.5 (SVD) and §4.6 (Matrix Approximation) as the machinery underneath. (Material to read; not yet checked.) See References for the full citation and link.
- Reproducibility script:
scripts/explore_nugget_pca.py. - Related notes: 2.2 Matrices for the change-of-basis idea in its simplest form.
References
The book
This repository contains notes on the following book, which is freely available from the authors:
Marc Peter Deisenroth, A. Aldo Faisal, and Cheng Soon Ong. Mathematics for Machine Learning. Cambridge University Press, 2020. ISBN 978-1-108-47004-9 (hardback), 978-1-108-45514-5 (paperback). DOI: 10.1017/9781108679930. Free PDF: https://mml-book.github.io/
Please cite the book, not these notes, for the mathematics itself.
Sections covered in these notes
| Book section | Note |
|---|---|
| 2.1 Systems of Linear Equations | 2.1 Systems of Linear Equations |
| 2.2 Matrices | 2.2 Matrices |
| 2.3 Solving Systems of Linear Equations | 2.3 Solving Systems of Linear Equations |
| 2.7 Linear Mappings | 2.7 Linear Mappings |
Nuggets (captured ahead of reading)
Forward notes on how a concept gets applied, written before the relevant chapter is read. They are marked on the page as not yet checked against the book, and are not counted as covered sections.
| Intended section | Nugget |
|---|---|
| §7.1 Optimization Using Gradient Descent | Nugget: gradient descent |
| §8.2.3 Regularization to Reduce Overfitting | Nugget: L1 vs L2 regularization |
| §10.2–§10.3 Maximum Variance / Projection Perspective | Nugget: PCA as a change of basis |
Standing conventions
- Page images. Screenshots of book pages live under
src/images/ch<NN>/and are referenced only from the note that needs them. They are included as short excerpts for study; copyright remains with the authors and publisher. - Numbering. Note filenames use the book’s own section numbers (for example
ch02/01-systems-of-linear-equations.mdis Section 2.1), so a cross-reference in a note can always be traced back to the book by number alone. - Reproducibility. Numerical claims are backed by scripts in
scripts/, which use onlynumpy(and optionallyscipy). - Attribution. Mathematics is attributed to the book by section and equation number. The reader’s own prior DeepSeek conversations prompted some questions and produced earlier draft answers, but they are not cited here — no chat URLs, no “a conversation with DeepSeek” references.