How this course works
In Mathematics for Machine Learning you learned to read the symbols: a bold for a vector, , , the transpose . This course is about what those objects do. Linear algebra is the mathematics of vectors and matrices, and nearly every model in machine learning is built from it. An image is a vector, a layer of a neural network is a matrix, and training a model means moving one very long vector of parameters around.
You don't need any linear algebra to start. Each idea arrives geometry first (a picture you can drag), then as algebra (rules you can compute with), then with a derivation or a proof (why the rules are true), and always with a link back to machine learning.
Every chamber runs the research loop you met in the first course:
Discover
Meet the idea in the wild, before it has a name.
Learn
Notation, definitions, derivations and proofs.
Read beyond
Go past the course: books, notes and articles.
Papers & lectures
Find it in real research, and watch the experts.
Your turn
Prove it, code it, test yourself. Then repeat.
Each chamber has an interactive lab with a challenge, proofs to assemble and to write, three coding problems in the style of Project Euler, and at least one decoder for an equation from a real paper. The checkpoint at the end clears the chamber. Nine chambers from now, Talos, the bronze giant who guarded Crete, is waiting.
Discover: arithmetic with words
In 2013, three researchers at Microsoft Research looked closely at the numbers a language model had learned. The model had turned every word in its vocabulary into a list of numbers (up to 1,600 of them) only to help it predict the next word in a sentence. But when the researchers did arithmetic with those lists, the arithmetic made sense.
Spotted in the wild
To answer the analogy “ is to as is to what?”, the paper takes the lists for the three words, computes , and looks for the word whose list is closest to . With = man, = king and = woman, the abstract reports that king − man + woman gives a vector very close to queen.
How do you subtract a word? You can't. But you can subtract one list of numbers from another, entry by entry. That is the first idea of this chamber: a vector is a list of numbers that you can add, subtract and scale, and it is also an arrow you can draw. (The paper writes its vectors in plain italics, . This course writes them in bold, , as the first course did.)
Try the arithmetic on vectors small enough to do by hand.
Here are toy word vectors in : , and . Working one entry at a time, what is ?
Learn: two views of one object
A vector has two faces, and much of the power of linear algebra comes from switching between them.
The arrow. A physicist's vector is an arrow: it has a length and a direction, and nothing else. Slide it anywhere and it's the same vector. In linear algebra we usually start every arrow at the origin, the point where the axes cross, so the arrow is pinned down by where its tip lands.
The list. A programmer's vector is an ordered list of numbers, like [3, 1]. Order matters: and are different vectors.
The bridge between the two is coordinates. The list says: from the origin, walk 3 units along the first axis and 1 unit along the second. The arrow ends there. We write vectors as columns,
read “v is the column vector three, one, in R two”. In running text we save space and write . The numbers and are the vector's components, or entries.
is the plane: every list of two real numbers. is ordinary three-dimensional space, and is every list of real numbers. You can't draw an arrow in , but you don't need to. Every rule in this chamber works one entry at a time, so it works in 784 dimensions exactly as it does in 2. Draw in 2D, then trust the algebra in any number of dimensions.
An arrow doesn't have to start at the origin. The arrow from point to point is written , and its components are “destination minus start”. From to , it's : three right and two down.
- “R n”Every list of real numbers: the space the vectors live in. is the plane, ordinary space.
- “the column vector v one, v two”A vector written as a column. Its entries are the arrow's coordinates. In running text it's written to save space.
- “vector P Q”The arrow from point to point : “destination minus start”.
- “u plus v”Add entry by entry. As arrows: put the tail of at the tip of (tip to tail).
- “c times v”Scalar multiplication: multiply every entry by the number . Stretches or shrinks the arrow by , and flips it if .
- “minus v”The negative of : the same length, pointing the opposite way. It equals .
- “u minus v”. Drawn from the origin, it's the arrow from the tip of to the tip of .
- “the zero vector”Every entry zero. Adding it changes nothing, and it has no direction.
- “e i”The -th standard basis vector: 1 in position , 0 everywhere else. In machine learning it's called a one-hot vector.
- “the sum of c i times v i”A linear combination: scale each vector by its coefficient , then add the results.
- “x king”A word embedding: the learned vector for one word. Here the subscript names the word, not a position.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “R n” | Every list of real numbers: the space the vectors live in. is the plane, ordinary space. | ||
| “the column vector v one, v two” | A vector written as a column. Its entries are the arrow's coordinates. In running text it's written to save space. | ||
| “vector P Q” | The arrow from point to point : “destination minus start”. | ||
| “u plus v” | Add entry by entry. As arrows: put the tail of at the tip of (tip to tail). | ||
| “c times v” | Scalar multiplication: multiply every entry by the number . Stretches or shrinks the arrow by , and flips it if . | ||
| “minus v” | The negative of : the same length, pointing the opposite way. It equals . | ||
| “u minus v” | . Drawn from the origin, it's the arrow from the tip of to the tip of . | ||
| “the zero vector” | Every entry zero. Adding it changes nothing, and it has no direction. | ||
| “e i” | The -th standard basis vector: 1 in position , 0 everywhere else. In machine learning it's called a one-hot vector. | ||
| “the sum of c i times v i” | A linear combination: scale each vector by its coefficient , then add the results. | ||
| “x king” | A word embedding: the learned vector for one word. Here the subscript names the word, not a position. |
Learn: adding, scaling and subtracting
Adding two vectors means one thing in each view, and the two agree.
- As lists: add entry by entry, so .
- As arrows: put the tail of the second arrow at the tip of the first, tip to tail. The sum runs from the start of the first to the tip of the second.
Why do they agree? Walking along takes you 3 right and 1 up. Walking along from there takes you 1 more right and 2 more up. In total you've gone right and up. Walking the two arrows in the other order traces the other two sides of a parallelogram and ends at the same corner, which is why .
Scaling a vector by a number multiplies every entry by : . Geometrically it stretches the arrow by a factor and turns it round if is negative. So is twice as long, is half as long, and has the same length but points the opposite way. Ordinary numbers like are called scalars, because they scale.
Two more pieces complete the kit. The zero vector is the arrow that goes nowhere, and adding it changes nothing. Subtraction is adding a negative: .
Subtraction has a picture worth memorising. Draw and from the origin. Then is the arrow from the tip of to the tip of , because . It's the “destination minus start” rule again. A difference of two vectors tells you how to get from one to the other, and that's what the word-vector paper measures: is the step from “man” to “king”.
A worked example, with and :
Draw and as arrows from the origin. Which vector is the arrow that starts at the tip of and ends at the tip of ?
Learn: linear combinations
Put scaling and adding together and you get the central construction of linear algebra. A linear combination of and is any vector of the form
where the scalars and are called coefficients. With more vectors the idea is the same, written with the sum notation from Chamber 5 of the first course:
It's called linear because you only scale and add: no squaring, and no multiplying vectors together. Think of the vectors as ingredients and the coefficients as how much of each goes in.
Here's the question the lab asks. Given , and a target point, which coefficients land on it exactly? Steer with the sliders first, then read on for the algebra.
Interactive lab
Vector navigator
Slide a and b to steer the violet arrow a·u + b·v. Drag the heads of u and v to change the ingredients.
Combination
1·(3, 1)
+0·(1, 3)
=(3, 1)
Targets
- ○(4, 4)
- ○(−1, 5)
- ○(−3, −5)
Vectors (or drag the heads)
Things to try:
- Reach all three targets. One of them needs a coefficient that isn't a whole number.
- Drag until it lies along the same line as , for example . How much of the grid can you reach now?
- Make the zero vector. What's left?
Learn: finding the coefficients
Guessing is fine in a lab, but not in a space with 784 dimensions. So let's derive the coefficients once and for all in . We want numbers and with
- 1
One equation per component
Two vectors are equal when every component is equal, so the vector equation is two ordinary equations:
- 2
Eliminate b
Multiply the first equation by and the second by :
Subtract the second from the first. The terms cancel, leaving
- 3
Eliminate a
Now multiply the first equation by and the second by , and subtract the first from the second. This time the terms cancel:
- 4
Divide, if you can
Both results contain the same number, . If , divide by it:
Check it on , and the target . Here , so and . Indeed, .
And when is ? You can check that it happens exactly when one vector is a multiple of the other, so that both lie on one line through the origin. Then every combination stays on that line, and targets off it can't be reached: the lab showed you this. Hold on to the number . It returns in Chamber 5 as the determinant, where it measures the area of the parallelogram that and span.
Learn: the standard basis
Two vectors in deserve names of their own:
They are one step along each axis. Every vector is a combination of them, and the coefficients are simply its components:
has of them: has a 1 in position and 0 everywhere else. Together they're called the standard basis (Chamber 3 explains what a basis is in general), and they reveal what the list view of a vector really is:
The components of are its coefficients in the standard basis. That deserves a proof, because it's really two promises.
Claim. Every vector can be written as a linear combination of , and in exactly one way.
We need one fact about the basis vectors. The -th entry of is the Kronecker delta from Chamber 4 of the first course: 1 if , and 0 otherwise.
Proof. Existence. Use the components of as the coefficients. The -th entry of is . Every term of that sum is zero except the one with , so the -th entry is . That holds for every , so .
Uniqueness. Now suppose some numbers also work: . By the same calculation, the -th entry of the right-hand side is . Two vectors are equal only when all their entries are equal, so for every . Any combination that works uses exactly the coefficients we already had.
Notice the shape of the argument. “There is one” and “there is only one” are separate claims, and each needs its own proof. Uniqueness proofs nearly always go like the second half: suppose there's another answer, then show it's forced to equal the first.
Which combination of standard basis vectors equals ?
Learn: the rules of the game
Everything you've done with vectors rests on a short list of rules. For all vectors , , and scalars , :
| Rule | In symbols |
|---|---|
| Order doesn't matter | |
| Grouping doesn't matter | |
| Zero changes nothing | |
| Every vector has a negative | |
| Scaling by one changes nothing | |
| Scaling twice multiplies the scalars | |
| A scalar spreads over a sum of vectors | |
| A vector spreads over a sum of scalars |
For lists of numbers, each rule follows from the matching rule for ordinary numbers, applied one entry at a time. For example, the -th entry of is , which is the -th entry of .
Now the mathematician's move. Any collection of objects that can be added and scaled while obeying these eight rules is called a vector space, and every theorem proved from the rules alone holds in all of them at once. Polynomials qualify: you can add two polynomials and scale one, and the rules hold. So do sound recordings and images, added sample by sample or pixel by pixel. That's why one body of theory serves so many kinds of data. You'll use the rules, lightly, in this chamber's proofs.
Learn: data as vectors
Machine learning's first move, almost always, is to turn data into vectors, so that everything above applies.
- Images. A greyscale MNIST digit is 28 by 28 pixels, each a brightness value. Read the pixels row by row into one list and the image becomes a vector in . Brightening an image scales it, blending two images is a linear combination, and the “average digit” is the combination with every coefficient equal to .
- Ratings. If a streaming service has 10,000 films, a user can be a vector in : their rating of each film. Chamber 2 shows how a recommender system learns a much shorter vector for every user and every film, and predicts ratings from them.
- Features. A house can be . A table of data is a stack of such feature vectors, one per row.
- Words. A word has no natural numbers attached, so we learn some. An embedding gives each word a vector, and training adjusts the vectors until words used in similar ways end up with similar vectors. The pre-trained vectors released with Google's word2vec tool give each of 3 million words and phrases a vector of 300 numbers.
Each image in the CIFAR-10 dataset is 32 pixels wide and 32 pixels tall, with three numbers per pixel (red, green and blue). Flattened into one long list, an image is a vector in . What is ?
Now the analogy from the start of the chamber makes sense. Suppose the step from “man” to “woman” is roughly the same wherever you take it, so that
Add to both sides and you get , which is exactly . The four words sit at the corners of a rough parallelogram. The paper's first example is grammatical rather than royal: , one offset for “singular to plural”.
Read beyond the course
Each of these takes the ideas of this chamber a little further, and each is free.
Book · free online · ~30 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Chapter 2: opening pages (17–19) and Section 2.4.2, Vector Spaces
The book you met in the first course. Chapter 2 opens by asking what a vector is, and answers with arrows, polynomials, audio signals and lists of numbers. Section 2.4.2 states the vector-space rules formally. Skip Section 2.4.1 on groups for now.
Interactive · free online · ~30 min
Immersive Linear AlgebraJ. Ström, K. Åström & T. Akenine-Möller · Chapter 2: Vectors, Sections 2.1–2.5
A whole textbook with interactive figures: drag the vectors in the pictures and watch sums, scalings and coordinates change. It covers this chamber from a slightly different angle, with bases and coordinates in Section 2.5.
Book · free online · ~40 min
Introduction to Applied Linear Algebra: Vectors, Matrices, and Least SquaresStephen Boyd & Lieven Vandenberghe · Chapter 1, Sections 1.1–1.3
A book built around applications. Its first chapter is full of data as vectors: word counts, images, customer purchases, time series. Read it to see how many things this chamber's operations already describe.
Article · free online · ~25 min
The Illustrated Word2vecJay Alammar
A gentle, heavily illustrated walk from “describe a person with a few numbers” to real word embeddings, including king − man + woman on real vectors. The second half explains how the vectors are trained, which is the equation decoded below.
Papers and lectures
The paper from the start of this chamber is short (six pages) and more readable than most. Read the abstract, then the paragraph of Section 1 that begins “In this work”, with the apples and cars. Then read Section 5, “The Vector Offset Method”, which is half a column long, and look at Figure 2, which draws the offsets as arrows. Skip Section 3, which describes the recurrent neural network that produced the vectors, and glance at Table 2 only to see that the network's longer vectors answered more analogies correctly. Section 5 contains one formula you can't read yet, a cosine similarity. You'll meet it in Chamber 2.
Linguistic Regularities in Continuous Space Word RepresentationsTomas Mikolov, Wen-tau Yih, Geoffrey Zweig · NAACL-HLT, 2013The paper that showed relationships between words become constant offsets between their vectors, and made king − man + woman ≈ queen famous.
Later that year, Mikolov and colleagues at Google published a faster way to train word vectors, the word2vec method. Its Equation 2 shows where the vectors come from. Read Section 1 and the first page of Section 2, up to and including Equation 2. The rest of Section 2 (hierarchical softmax and negative sampling) is engineering you can come back to.
Distributed Representations of Words and Phrases and their CompositionalityTomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, Jeffrey Dean · NeurIPS, 2013The word2vec paper. Its largest model was trained on about 33 billion words of text, and word2vec vectors became a standard starting point for language tasks for years, until models such as BERT learned vectors that change with context.
Decode the paper · Eq. (2), Section 2
Distributed Representations of Words and Phrases and their CompositionalityTomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, Jeffrey Dean · NeurIPS, 2013
The skip-gram model learns word vectors by predicting, for each word in a text, the words that appear near it. Equation 2 gives the probability that word appears near word . Each word gets two vectors: an “input” vector and an “output” vector . Match each symbol to its meaning.
Options
Watch
Grant Sanderson's Essence of linear algebra is the classic visual introduction to the subject, and this first episode covers this chamber in ten minutes. Watch for his three perspectives on what a vector is (the physics student's, the computer science student's and the mathematician's), and for how he pictures addition and scaling as movements.
Your turn
If you haven't cleared the lab's challenge yet, it's waiting in the Learn section. Here, match arrows to lists and maths to code, assemble a proof and write one, then solve three problems in code.
Match · Arrow ↔ Vector
Arrows and lists
Match each description of an arrow to its list of components.
Options
Match · Maths ↔ NumPy
From symbols to NumPy
NumPy arrays add and scale entry by entry, exactly like vectors. Match each expression to the NumPy that computes it. Assume u, v are 1D arrays, V holds one vector per row, and remember that Python counts from 0.
Options
Proofs
The first proof shows that combining combinations never gets you anything new, an idea Chamber 3 builds on. The second is a classic of geometry that vectors make short.
Proof puzzle
Combinations of combinations
Claim
If and are both linear combinations of and , then so is .
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
The diagonals of a parallelogram
Claim
The two diagonals of any parallelogram cut each other in half.
Put one corner at the origin, so the corners are , , and . You may use that the midpoint of the segment from point to point is : start at and go half of the way to .
Your typeset proof appears here.
Code it up
Each problem has exactly one answer. Write a few lines of Python, on your own machine or in the runner under each problem, and submit the number. The second applies the vector offset method from the paper; the third rewards the uniqueness proof from this chamber.
Problem 1·Warm-up
Back to the entrance
Theseus enters the labyrinth at the origin of and makes 1000 moves. Move , for , is the vector
Moves add tip to tail, so after moves he stands at
For how many in is he back at the entrance, that is, ?
Problem 2·Standard
Analogies by parallelogram
In the vector offset method of Mikolov, Yih and Zweig (2013), the analogy “ is to as is to ?” is answered by computing and looking for the word whose vector is closest to . In a toy vocabulary with whole-number vectors we can look for exact hits instead.
The vocabulary has 50 words, numbered to . Word has the embedding
and all 50 embeddings are different. Count the ordered triples of three different words for which is exactly the embedding of some word , where is different from , and .
Problem 3·Challenge
Counting combinations
Take these seven vectors in :
In how many ways can be written as a linear combination
whose coefficients are non-negative integers? Two ways count as different if at least one coefficient differs.
For a small example, can be written in exactly 5 ways: , , , and . Check that your code agrees before trusting it on .
Key takeaways
- A vector is an arrow and a list. Coordinates are the bridge: means 3 along the first axis and 1 along the second, and the same rules work in for any .
- Add tip to tail or entry by entry; scale by multiplying every entry. A negative scalar flips the arrow, and is the arrow from the tip of to the tip of .
- A linear combination only scales and adds. In you can solve for and by elimination, unless and the vectors share a line.
- , in exactly one way. Components are coefficients in the standard basis, and one-hot vectors are standard basis vectors.
- Data becomes vectors: images, ratings, features and learned word embeddings, where relationships can show up as roughly constant offsets.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
What are the components of the arrow from to ?
Let and . What is the second component of ?
Compared with , the vector is…
Find the numbers and with . What is ?
Which of these vectors is not a linear combination of and ?
Mikolov, Yih and Zweig (2013) found that relationships appear as “constant vector offsets”. What does that mean?
Which expression is undefined?
Why can't be written as in two different ways?
End of the chamber
Clear this chamber
- Questions in this chamber (0/12 solved)Next unsolved
- Bonus: Navigator (+40 XP)
- Bonus: Problem 1: Back to the entrance (+20 XP)
- Bonus: Problem 2: Analogies by parallelogram (+35 XP)
- Bonus: Problem 3: Counting combinations (+50 XP)
- Bonus: Proof: Combinations of combinations (+25 XP)
- Bonus: Proof: The diagonals of a parallelogram (+40 XP)
- Bonus: Decode the paper (+30 XP)
- Bonus: Match: Arrows and lists (+25 XP)
- Bonus: Match: From symbols to NumPy (+25 XP)