A spreadsheet of houses and a rotation of a picture look like two different things. Yet both are written as the same object: a rectangle of numbers. In machine learning that one rectangle plays two roles. It can be a table of data, one row for each example. Or it can be a machine that takes a vector in and gives a vector out, stretching and turning space as it goes. This lesson teaches you to read a matrix in both roles.
What a matrix is
A matrix is a rectangular grid of numbers, written in brackets:
This one has 2 rows and 3 columns, so its shape is , read “2 by 3”. Always say rows first, then columns. The set of all real matrices with rows and columns is written , so here .
A single number in the grid is an entry. The entry in row and column is written , row first. So (row 1, column 2) and . Mathematicians count from 1. NumPy counts from 0, so is A[0, 1] in code. Keep that off-by-one in mind whenever you move between a formula and a program.
A vector is a special matrix: a column vector with entries is an matrix. (A plain NumPy array like np.array([3, 1]) has shape (2,), which is neither a row nor a column; P1.B1 explained this.)
A few matrices have names, and you will meet them again and again:
| Name | What it is | Example |
|---|---|---|
| Square | as many rows as columns () | |
| Zero matrix | every entry is 0 | |
| Diagonal | square, and every entry off the main diagonal is 0 | |
| Identity | diagonal with 1s on the diagonal |
(The main diagonal runs from the top-left entry down to the bottom-right.) The identity is the matrix that does nothing, as you will see in a moment: .
Two matrices of the same shape can be added, and a matrix can be scaled, entry by entry, just like vectors (P1.B2):
Adding a matrix to a one is not defined, for the same reason that is not.
Job 1: a matrix holds data
Here are five houses, each described by three numbers: area in square metres, number of bedrooms, and age in years. (The numbers are invented.) Put one house on each row and you get a matrix:
This is the machine-learning convention, and you will see it on every dataset:
- Each row is one example (one house, one image, one sentence).
- Each column is one feature (one measured quantity, the same for every example).
- With examples and features, the data matrix has shape . Here .
(The thing you want to predict, such as the price, is usually kept apart as a separate list ; P3.A1.) Try picking out rows and columns:
Two different pieces of the matrix matter:
- A row is one example as a vector. Row 1 is : the house, a point in (P1.B1). In NumPy it is
X[0]. - A column is one feature across all examples. Column 1 is : the area of every house. In NumPy it is
X[:, 0](the colon means “all rows”). This is what you take the average of when you ask “what is the typical area?”: the mean of that column is 102.
X.shape tells you (5, 3), and X[1, 2] is one entry: house 2 (row 1 counting from zero), feature 3 (column 2 from zero), age 40.
The clash between column vectors and data rows
You now have two habits that point in opposite directions, so be careful here.
- In the maths, a vector is a column by default (P1.B1). One example is , a column.
- In the data matrix, that same example is stored as a row. Written with the transpose (which turns a column into a row), is the stack of rows .
In code the clash mostly disappears: X[i] is a plain 1-D array of numbers (neither row nor column), and you use it directly as . The shapes only matter when you multiply. The second Go deeper box near the end of this lesson shows what that means for applying a layer to a whole dataset. The transpose itself gets its own lesson (P1.B10); for now, read as “swap rows and columns”. Tick the checkbox in the widget to see the swap: the matrix becomes a one, with features as rows.
A grayscale image is a matrix too
A black-and-white picture is a grid of brightness numbers, so it is a matrix. The tiny plus sign from P1.B1 is a matrix:
Its shape is height by width (rows by columns). The entry in row 1, column 2 (counting from zero) is img[1, 2], which is 1: the right-hand pixel of the middle row. A image (the size of the MNIST digits) is a matrix with 784 entries. Reading it row by row into one long list gives the 784-entry vector from P1.B1. A colour image needs a third axis for the colour channels, which is why P5.1 and P1.B14 talk about tensors rather than matrices.
The same idea gives embedding tables: a language model keeps one learned vector for every token in its vocabulary and stores them as the rows of one big matrix, so that token number is simply row (P4.21).
Job 2: a matrix acts on a vector
Now the second role. A matrix can act on a vector and produce a new vector. Take
The result is written (no symbol between them). There are two ways to compute it, and you need both.
Way 1: rows dotted with . Each entry of the output is the dot product (P1.B3) of one row of with :
Way 2: a combination of the columns. The entries of are weights, and the columns of are the vectors being mixed (a linear combination, P1.B2):
Same answer, because they are the same sum arranged differently: every output entry is or either way. This is the preview that P1.B2 promised. Way 1 is good for computing one output entry. Way 2 is good for seeing what the matrix does, as you will see in a moment.
For a matrix with columns, Way 2 reads , where is column . Way 1 reads .
The shape rule
For the product to exist, must have as many columns as has entries. Each entry of is a weight for one column (Way 2), and each row of is dotted with (Way 1), which needs equal lengths (P1.B3). If is and has entries, then
The matching ‘s cancel, and what is left is : the number of rows is the size of the output. So a matrix needs a 3-entry input and gives a 2-entry output; given a 2-entry input it fails. (Written as an column, the rule is . P1.B6 extends it to a matrix times a matrix.)
Read the columns: where the arrows land
Here is the most useful fact in the lesson. What does do to the two arrows along the axes, and ? Use Way 2:
So column 1 is where lands, and column 2 is where lands. Every other point is built from those two arrows: . After the map it becomes . So the whole plane is carried along with the two arrows: the grid of squares you started with becomes a grid of parallelograms whose sides are the two columns.
Now play. The faint grey grid, the dashed unit square and the outlined “F” are the plane before the map. The blue grid, the grey parallelogram and the solid “F” are the plane after it. The F is there so that flips and turns are easy to see.
Things to try:
- Press Identity, then drag the blue tip (column 1) to . The whole grid is stretched to twice its width, because now lands at .
- Press Rotate 30°. The columns are the old axis arrows, turned by 30°. Check the F: it turned and nothing else happened.
- Set and . The F is upside down: a half turn.
- Press Project. The whole plane collapses onto a line, and the status line says so. Drag around: the output only slides along that line.
- Tick “Show Ax as col 1 and col 2 added tip to tail” and drag . You see Way 2: copies of the blue arrow, then copies of the pink arrow.
Intuition
Think of a matrix as a machine. A vector goes in, a vector comes out. To find out what a machine does, you do not need to test every input. Two test inputs are enough: feed in and and write down what comes out. Those two outputs are the two columns. Every other input is a mix of the two test inputs, and the machine treats a mix of inputs as the same mix of outputs.
The analogy has a weak spot: a real machine can do anything to its inputs, such as a lookup or a bend. These machines are special. They can only stretch, turn, flip, slide sideways and squash, and they never bend a straight line. That restriction is exactly what “linear” means, and it is why two test inputs are enough.
Math
For with columns and :
The standard basis vector has a 1 in position and 0 elsewhere, so : column is the image of . For the identity matrix, , so .
Code
import numpy as np
A = np.array([[1, 2],
[3, 4]])
x = np.array([2, 3])
A @ x # array([ 8, 18])
x[0] * A[:, 0] + x[1] * A[:, 1] # the same, column by column
A[:, 0] # array([1, 3]): where (1, 0) landsA @ x is the matrix-vector product. The runnable cells further down use it a lot.
What “linear” means
The matrix maps in the widget all share a property. A map from vectors to vectors is linear if it obeys two rules, for any vectors and any number :
In words: adding then mapping is the same as mapping then adding, and scaling then mapping is the same as mapping then scaling. Check with from above, and .
And . Every matrix map is linear, because it is built from adding and scaling (Way 2). What does that look like?
- The origin stays put. : take in the second rule. In the widget the origin never moves.
- Straight lines stay straight lines. (A line is , and it maps to , which is again a line, or a single point if .)
- Parallel, evenly spaced grid lines stay parallel and evenly spaced. The grid is stretched or tilted, but it never bends or bunches up unevenly. (One exception: a map that squashes the plane, like the projection below, piles every grid line onto a single line.)
The test for yourself: if the warped grid in the widget could ever show a curve, a moved origin or lines bunching up, the map would not be linear. It never does.
A gallery of 2×2 maps
Each of these is a matrix. To get it, ask where and should land, and write those two points as the columns.
| Map | Matrix |
|---|---|
| Scaling: stretch by 2, squeeze by half | |
| Reflection: mirror in the -axis | |
| Rotation counter-clockwise by | |
| Shear: | |
| Projection onto the line |
A few notes on each.
Scaling uses a diagonal matrix: each diagonal entry scales one axis, so here. A negative entry also flips that axis. Scaling by the same number on both axes is the matrix .
Rotation. Turning by puts it at on the unit circle, and turning by puts it at . Those are the two columns. For they are and , and goes to . Its length stays : rotations do not change lengths (P1.B10 studies this). For a quarter turn, , the matrix is . The widget’s preset uses 0.866 for , which is rounded.
Reflection in the -axis sends to , and the F comes out backwards.
Shear. Each row slides sideways in proportion to its height. stays at and lands at , so the square becomes a leaning parallelogram. Its area does not change (P1.B8).
Projection is the one that loses something. Every point is dropped straight onto the line (P1.B11). But and both land on , and lands on . Different inputs give the same output, so no matrix can undo it: you cannot tell from where you started. The whole plane has been squashed onto a line, which is what the status line in the widget reports as “det = 0”. The determinant is the number that measures how the map scales areas (P1.B8), and “can it be undone?” is the question of the inverse (P1.B9).
One more preview. If you apply one matrix and then another, the combined effect is again a matrix, and finding it is what matrix multiplication means (P1.B6).
A shift is not linear, so layers add a bias
What about sliding the whole plane, say by ? Call it . Is it linear? No:
- It moves the origin: .
- It breaks the addition rule: , but .
So no matrix can shift the plane: a matrix always leaves the origin where it is. A shift is a different kind of map. The combination “linear map, then a shift” is called an affine map:
This is what a neural-network layer computes, and the vector is called the bias. Without it, a layer could never move the origin. A full layer then squashes the result with an activation function (sigmoid, , and so on; P1.A5), applied to each entry separately:
Here are small numbers. Let , and .
(using the sigmoid , so and ). That is one layer of a network. P4.1 and P4.10 build it for real, and P4.3 shows why the squashing step is needed.
Matrices that are not square
Everything above works for any shape. The matrix is . It takes a 2-entry vector and gives a 3-entry one:
It maps the plane into 3-D space. The outputs do not fill 3-D: they all lie on one flat sheet (the plane ), a copy of the plane sitting inside 3-D. In the other direction, is : it takes 3-D vectors to 2-D ones by dropping the third entry, so . That squashes 3-D space onto a plane, and many inputs share one output.
The rule from before says it all: columns = size of the input, rows = size of the output. A layer that turns 784 pixel values into 128 numbers has a weight matrix with 128 rows and 784 columns, which is entries, plus 128 bias entries. (This size is just an example.) The widget in this lesson is because a flat screen can draw a plane to a plane.
Matrices in NumPy
Run these cells and read each line against the text above. The first one is about data.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The second cell is about matrices as functions. It also shows the most common trap: * is not the matrix product. A * x multiplies entry by entry (NumPy stretches the shorter array to match, a trick called broadcasting, P1.B14), while A @ x is the matrix-vector product.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The last line prints an error that begins “matmul: Input operand 1 has a mismatch in its core dimension 0”. That is NumPy saying the shapes do not match: the matrix has 3 columns but the vector has only 2 entries. (The rest of the message is technical, and its wording can differ between NumPy versions.) When you see an error like this, print the .shape of both sides first.
Common mistakes
Go deeper Every linear map is a matrix
We showed that every matrix gives a linear map. The reverse also holds: every linear map from to is some matrix. Write . Linearity lets you push through the sum:
This is Way 2 with the columns . So the matrix whose columns are the images of the basis vectors does exactly what does. That is why the two test inputs and are enough in the plane, and why “linear map” and “matrix” are two names for one idea (in finite dimensions).
Go deeper Homogeneous coordinates: a shift as one matrix
A shift cannot be a matrix, but it can be a one if you add a fixed extra entry 1 to every vector. For the layer above, put in a new last column and add a bottom row :
The first two entries of the result, , are exactly , and the last entry stays 1. This trick is called homogeneous coordinates. Computer graphics uses it to rotate and move objects with one kind of matrix. In machine learning, the same idea shows up as “add a constant feature 1 to every example, and the bias becomes just one more weight”. The transformation is still affine in the original space: only the bookkeeping is linear.
Go deeper Rows as examples in code: X @ W.T
A layer is for one example written as a column. But your data matrix has the examples as rows. To apply the layer to every example at once you need the transpose. A preview, with and two examples and stacked as the rows of :
Row 1 of the result, , equals for the first example, and row 2, , equals . So one matrix product handles the whole dataset, and the results come out again as rows, one per example. (This is a matrix times a matrix, which P1.B6 explains; here it is only a preview.) In code you write X @ W.T. PyTorch’s nn.Linear follows this layout: it stores its weight as a matrix of shape (out, in), the same shape as , and computes on rows. Some other code stores the weights as (in, out) and writes X @ W. Both are fine, and the shapes tell you which one you are looking at. This is why the first thing to do with any matrix in code is to print its shape.
Check your understanding
A matrix has 3 rows and 5 columns. What is its shape?
Shape is always rows by columns, rows first, so 3 rows and 5 columns is 3 × 5. It has 15 entries in total, but the shape records the two counts separately.
What is ?
By rows: 2·1 + 0·1 = 2 and 0·1 + 3·1 = 3. By columns: 1·(2, 0) + 1·(0, 3) = (2, 3). The result of a matrix times a vector is a vector, not a single number.
A matrix has first column and second column . Where does the arrow land?
The second column is where (0, 1) lands, so it lands at (5, 7). The first column, (2, 1), is where (1, 0) lands. The pair (2, 5) is the first row, which is not where an arrow lands.
Which of these maps of the plane is NOT linear?
Moving every point 3 to the right sends the origin (0, 0) to (3, 0), but a linear map always keeps the origin fixed. The other three are matrix maps.
A matrix with 4 rows and 7 columns is multiplied by a vector. What must the vector look like, and what do you get?
The columns count the inputs (each entry of x weights one column) and the rows count the outputs (one dot product per row). Shape rule: (4 × 7)(7) → (4).
Exercises
- What is the shape of , and what is ?
Show answer
The shape is . is row 2, column 3, which is 6. - Compute both ways, by rows and by columns.
Show answer
By rows: and . By columns: . Both give . - Write the matrix that sends to and to . Where does it send ?
Show answer
The columns are the landing points: . Then . - Write the matrix that doubles and flips (so becomes ).
Show answer
: lands at and lands at . - Write the matrix for a counter-clockwise quarter turn (90°). Check it on .
Show answer
, from and . Check: lands at its first column, , which is the arrow turned a quarter turn left. - Is linear? Is ?
Show answer
is linear: it is the matrix . is not: , but a linear map must send the origin to the origin. - You have 1000 images of size , and each is flattened into a vector of 784 numbers. What is the shape of the data matrix ?
Show answer
: one row per image (example) and one column per pixel (feature). In NumPy,X.shapeis(1000, 784). - A layer turns 784 inputs into 128 outputs. What is the shape of its weight matrix, and how many numbers does the layer have in total, counting the bias?
Show answer
is (rows are outputs), which has entries. The bias has 128 entries. The total is . - In the matrix-warp widget (the second one), find a matrix that sends to and to . What does it do to the F?
Show answer
The columns are and , so (set and ). It swaps and : a mirror in the line , so the F comes out as a mirror image. The status line says det is negative. - Code: with
A = np.array([[1, 2], [3, 4]])andx = np.array([10, 100]), predictA * xandA @ x, then run them.Show answer
A * xis[[10, 200], [30, 400]](each row multiplied entry by entry byx).A @ xis[210, 430]: and .