Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsLinear Algebra

Matrices as data and as transformations

P1.B530 min●○○ BeginnerReviewed Nov 30, 2026

Why this matters for machine learning

A matrix is how machine learning stores a whole dataset and how a neural network layer transforms its input: the same rectangle of numbers does both jobs.

  • A dataset is one matrix with a row per example and a column per feature, and every training algorithm starts from that table. (P3.A1: The supervised learning setup, coming soon)
  • A neural-network layer computes Wx + b: a matrix warps the input, a bias shifts it, and an activation function squashes it. (P4.10: Build an MLP from scratch (NumPy), coming soon)
  • A grayscale image is a matrix of brightness numbers. (P5.1: Images as tensors, coming soon)
  • An embedding table is a matrix with one row per token, and attention uses learned matrices to turn each token vector into a query, a key and a value. (P7.3: Queries, keys and values step by step, coming soon)

Before this: Scalars, vectors and spaces, Vector operations, Dot product and cosine similarity

After this lesson you can

  • Read a matrix (shape, entries, identity, diagonal) and pick out one example or one feature from a data matrix in NumPy
  • Compute a matrix times a vector in two ways, by rows and by columns, and say which shapes are allowed
  • Read the columns of a 2 by 2 matrix as the places where (1, 0) and (0, 1) land, and sketch what the matrix does to the plane
  • Say what linear means, why a shift is not linear, and how a neural-network layer fixes that with a bias

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:

A=(123456)\mathbf{A}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix}

This one has 2 rows and 3 columns, so its shape is 2×32\times3, read “2 by 3”. Always say rows first, then columns. The set of all real matrices with mm rows and nn columns is written Rm×n\mathbb{R}^{m\times n}, so here A∈R2×3\mathbf{A}\in\mathbb{R}^{2\times3}.

A single number in the grid is an entry. The entry in row ii and column jj is written AijA_{ij}, row first. So A12=2A_{12}=2 (row 1, column 2) and A23=6A_{23}=6. Mathematicians count from 1. NumPy counts from 0, so A12A_{12} 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 nn entries is an n×1n\times1 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:

NameWhat it isExample
Squareas many rows as columns (m=nm=n)(1234)\begin{pmatrix}1&2\\3&4\end{pmatrix}
Zero matrixevery entry is 0(0000)\begin{pmatrix}0&0\\0&0\end{pmatrix}
Diagonalsquare, and every entry off the main diagonal is 0(2003)\begin{pmatrix}2&0\\0&3\end{pmatrix}
Identity I\mathbf{I}diagonal with 1s on the diagonal(1001)\begin{pmatrix}1&0\\0&1\end{pmatrix}

(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: Ix=x\mathbf{I}\mathbf{x}=\mathbf{x}.

Two matrices of the same shape can be added, and a matrix can be scaled, entry by entry, just like vectors (P1.B2):

(1234)+(10203040)=(11223344)2(1234)=(2468)\begin{gathered} \begin{pmatrix}1&2\\3&4\end{pmatrix}+\begin{pmatrix}10&20\\30&40\end{pmatrix}=\begin{pmatrix}11&22\\33&44\end{pmatrix} \\ 2\begin{pmatrix}1&2\\3&4\end{pmatrix}=\begin{pmatrix}2&4\\6&8\end{pmatrix} \end{gathered}

Adding a 2×22\times2 matrix to a 2×32\times3 one is not defined, for the same reason that (1,2)+(3,4,5)(1,2)+(3,4,5) 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:

X=(12031585240150456013095310)\mathbf{X}=\begin{pmatrix}120&3&15\\85&2&40\\150&4&5\\60&1&30\\95&3&10\end{pmatrix}

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 NN examples and dd features, the data matrix has shape N×dN\times d. Here X∈R5×3\mathbf{X}\in\mathbb{R}^{5\times3}.

(The thing you want to predict, such as the price, is usually kept apart as a separate list yy; P3.A1.) Try picking out rows and columns:

A dataset is a matrix: rows are examples, columns are features

120315
85240
15045
60130
95310
X.shape = (5, 3): 5 rows (examples) and 3 columns (features)
X[0] → (120, 3, 15)
House 1 as one vector: 3 numbers, a point in ℝ³. One example.

Click a row label to pick one example, or a column label to pick one feature. The numbers are invented. NumPy counts from 0, so house 1 is row 0.

A data matrix with 5 houses (rows) and 3 features (columns). Click a row label to select one example, or a column label to select one feature, and read the NumPy expression that picks it out. The checkbox shows the transpose, where rows and columns swap places.

Two different pieces of the matrix matter:

  • A row is one example as a vector. Row 1 is (120,3,15)(120, 3, 15): the house, a point in R3\mathbb{R}^3 (P1.B1). In NumPy it is X[0].
  • A column is one feature across all examples. Column 1 is (120,85,150,60,95)(120, 85, 150, 60, 95): 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 xi∈Rd\mathbf{x}_i\in\mathbb{R}^d, a column.
  • In the data matrix, that same example is stored as a row. Written with the transpose ⊤^\top (which turns a column into a row), X\mathbf{X} is the stack of rows x1⊤,…,xN⊤\mathbf{x}_1^\top,\dots,\mathbf{x}_N^\top.
X=(x1⊤x2⊤⋮xN⊤)∈RN×d\mathbf{X}=\begin{pmatrix}\mathbf{x}_1^\top\\ \mathbf{x}_2^\top\\ \vdots\\ \mathbf{x}_N^\top\end{pmatrix}\in\mathbb{R}^{N\times d}

In code the clash mostly disappears: X[i] is a plain 1-D array of dd numbers (neither row nor column), and you use it directly as xi\mathbf{x}_i. 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 ⊤^\top as “swap rows and columns”. Tick the checkbox in the widget to see the swap: the 5×35\times3 matrix becomes a 3×53\times5 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 3×33\times3 matrix:

(010111010)\begin{pmatrix}0&1&0\\1&1&1\\0&1&0\end{pmatrix}

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 28×2828\times28 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 tt is simply row tt (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

A=(1234),x=(23)\mathbf{A}=\begin{pmatrix}1&2\\3&4\end{pmatrix},\qquad \mathbf{x}=\begin{pmatrix}2\\3\end{pmatrix}

The result is written Ax\mathbf{A}\mathbf{x} (no symbol between them). There are two ways to compute it, and you need both.

Way 1: rows dotted with x\mathbf{x}. Each entry of the output is the dot product (P1.B3) of one row of A\mathbf{A} with x\mathbf{x}:

Ax=(1⋅2+2⋅33⋅2+4⋅3)=(818)\mathbf{A}\mathbf{x}=\begin{pmatrix}1\cdot2+2\cdot3\\3\cdot2+4\cdot3\end{pmatrix}=\begin{pmatrix}8\\18\end{pmatrix}

Way 2: a combination of the columns. The entries of x\mathbf{x} are weights, and the columns of A\mathbf{A} are the vectors being mixed (a linear combination, P1.B2):

Ax=2(13)+3(24)=(26)+(612)=(818)\begin{aligned} \mathbf{A}\mathbf{x}&=2\begin{pmatrix}1\\3\end{pmatrix}+3\begin{pmatrix}2\\4\end{pmatrix}\\ &=\begin{pmatrix}2\\6\end{pmatrix}+\begin{pmatrix}6\\12\end{pmatrix}=\begin{pmatrix}8\\18\end{pmatrix} \end{aligned}

Same answer, because they are the same sum arranged differently: every output entry is 1⋅2+2⋅31\cdot2+2\cdot3 or 3⋅2+4⋅33\cdot2+4\cdot3 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 nn columns, Way 2 reads Ax=x1a1+⋯+xnan\mathbf{A}\mathbf{x}=x_1\mathbf{a}_1+\dots+x_n\mathbf{a}_n, where aj\mathbf{a}_j is column jj. Way 1 reads (Ax)i=∑jAijxj(\mathbf{A}\mathbf{x})_i=\sum_j A_{ij}x_j.

The shape rule

For the product to exist, A\mathbf{A} must have as many columns as x\mathbf{x} has entries. Each entry of x\mathbf{x} is a weight for one column (Way 2), and each row of A\mathbf{A} is dotted with x\mathbf{x} (Way 1), which needs equal lengths (P1.B3). If A\mathbf{A} is m×nm\times n and x\mathbf{x} has nn entries, then

(m×n)⏟A (n)⏟x ⟶ (m)⏟Ax\underbrace{(m\times n)}_{\mathbf{A}}\ \underbrace{(n)}_{\mathbf{x}}\ \longrightarrow\ \underbrace{(m)}_{\mathbf{A}\mathbf{x}}

The matching nn‘s cancel, and what is left is mm: the number of rows is the size of the output. So a 2×32\times3 matrix needs a 3-entry input and gives a 2-entry output; given a 2-entry input it fails. (Written as an n×1n\times1 column, the rule is (m×n)(n×1)→(m×1)(m\times n)(n\times1)\to(m\times1). 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 A\mathbf{A} do to the two arrows along the axes, e1=(1,0)\mathbf{e}_1=(1,0) and e2=(0,1)\mathbf{e}_2=(0,1)? Use Way 2:

A(10)=1(13)+0(24)=(13),A(01)=(24)\begin{aligned} \mathbf{A}\begin{pmatrix}1\\0\end{pmatrix}&=1\begin{pmatrix}1\\3\end{pmatrix}+0\begin{pmatrix}2\\4\end{pmatrix} \\ &=\begin{pmatrix}1\\3\end{pmatrix}, \\ \mathbf{A}\begin{pmatrix}0\\1\end{pmatrix}&=\begin{pmatrix}2\\4\end{pmatrix} \end{aligned}

So column 1 is where (1,0)(1,0) lands, and column 2 is where (0,1)(0,1) lands. Every other point is built from those two arrows: (x1,x2)=x1 e1+x2 e2(x_1,x_2)=x_1\,\mathbf{e}_1+x_2\,\mathbf{e}_2. After the map it becomes x1⋅(column 1)+x2⋅(column 2)x_1\cdot(\text{column 1})+x_2\cdot(\text{column 2}). 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.

Edit the matrix and watch the plane move

−2−112−2−112col 1col 2xAx
A = 10 01 col 1 = (1, 0) (where (1, 0) lands), col 2 = (0, 1) (where (0, 1) lands)
x = (2, 1)
row 1 · x: 1×2 + 0×1 = 2
row 2 · x: 0×2 + 1×1 = 1
columns: 2×(1, 0) + 1×(0, 1) = (2, 1)
Ax = (2, 1)
area of the unit square after the warp: |det| = |1×1 − 0×0| = 1

Identity: nothing moves. The columns are (1, 0) and (0, 1) themselves.

Dashed circle: the input x. Black arrow: the output Ax. Thin grey lines: the original grid and unit square. The solid shape is the same square and the same "F" after the warp. Drag the blue and pink tips (the two columns) to edit the matrix directly.

A 2 by 2 matrix warping the plane. Use the four sliders, or drag the blue and pink tips (the two columns), or press a preset. Drag the dashed circle (the input x) and read the output Ax and how it is computed. Keyboard: Tab to a handle and use the arrow keys.

Things to try:

  1. Press Identity, then drag the blue tip (column 1) to (2,0)(2, 0). The whole grid is stretched to twice its width, because (1,0)(1,0) now lands at (2,0)(2,0).
  2. Press Rotate 30°. The columns are the old axis arrows, turned by 30°. Check the F: it turned and nothing else happened.
  3. Set A11=−1A_{11}=-1 and A22=−1A_{22}=-1. The F is upside down: a half turn.
  4. Press Project. The whole plane collapses onto a line, and the status line says so. Drag x\mathbf{x} around: the output Ax\mathbf{A}\mathbf{x} only slides along that line.
  5. Tick “Show Ax as col 1 and col 2 added tip to tail” and drag x\mathbf{x}. You see Way 2: x1x_1 copies of the blue arrow, then x2x_2 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 (1,0)(1,0) and (0,1)(0,1) 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 A∈Rm×n\mathbf{A}\in\mathbb{R}^{m\times n} with columns a1,…,an∈Rm\mathbf{a}_1,\dots,\mathbf{a}_n\in\mathbb{R}^m and x∈Rn\mathbf{x}\in\mathbb{R}^n:

Ax=x1a1+x2a2+⋯+xnan(Ax)i=∑j=1nAij xj\begin{aligned} \mathbf{A}\mathbf{x}&=x_1\mathbf{a}_1+x_2\mathbf{a}_2 \\ &\quad+\dots+x_n\mathbf{a}_n \\ (\mathbf{A}\mathbf{x})_i&=\sum_{j=1}^{n}A_{ij}\,x_j \end{aligned}

The standard basis vector ej\mathbf{e}_j has a 1 in position jj and 0 elsewhere, so Aej=aj\mathbf{A}\mathbf{e}_j=\mathbf{a}_j: column jj is the image of ej\mathbf{e}_j. For the identity matrix, Iej=ej\mathbf{I}\mathbf{e}_j=\mathbf{e}_j, so Ix=x\mathbf{I}\mathbf{x}=\mathbf{x}.

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) lands

A @ 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 ff from vectors to vectors is linear if it obeys two rules, for any vectors x,y\mathbf{x},\mathbf{y} and any number cc:

f(x+y)=f(x)+f(y)f(c x)=c f(x)\begin{aligned} f(\mathbf{x}+\mathbf{y})&=f(\mathbf{x})+f(\mathbf{y})\\ f(c\,\mathbf{x})&=c\,f(\mathbf{x}) \end{aligned}

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 A\mathbf{A} from above, x=(2,3)\mathbf{x}=(2,3) and y=(1,−2)\mathbf{y}=(1,-2).

A(x+y)=A(31)=(513)Ax+Ay=(818)+(−3−5)=(513)\begin{aligned} \mathbf{A}(\mathbf{x}+\mathbf{y})&=\mathbf{A}\begin{pmatrix}3\\1\end{pmatrix}=\begin{pmatrix}5\\13\end{pmatrix}\\ \mathbf{A}\mathbf{x}+\mathbf{A}\mathbf{y}&=\begin{pmatrix}8\\18\end{pmatrix}+\begin{pmatrix}-3\\-5\end{pmatrix}=\begin{pmatrix}5\\13\end{pmatrix} \end{aligned}

And A(2.5 x)=A(5,7.5)=(20,45)=2.5 (8,18)\mathbf{A}(2.5\,\mathbf{x})=\mathbf{A}(5,7.5)=(20,45)=2.5\,(8,18). Every matrix map is linear, because it is built from adding and scaling (Way 2). What does that look like?

  • The origin stays put. A0=0\mathbf{A}\mathbf{0}=\mathbf{0}: take c=0c=0 in the second rule. In the widget the origin never moves.
  • Straight lines stay straight lines. (A line is p+tv\mathbf{p}+t\mathbf{v}, and it maps to Ap+t Av\mathbf{A}\mathbf{p}+t\,\mathbf{A}\mathbf{v}, which is again a line, or a single point if Av=0\mathbf{A}\mathbf{v}=\mathbf{0}.)
  • 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.

Each of these is a 2×22\times2 matrix. To get it, ask where (1,0)(1,0) and (0,1)(0,1) should land, and write those two points as the columns.

MapMatrix
Scaling: stretch xx by 2, squeeze yy by half(2000.5)\begin{pmatrix}2&0\\0&0.5\end{pmatrix}
Reflection: mirror in the yy-axis(−1001)\begin{pmatrix}-1&0\\0&1\end{pmatrix}
Rotation counter-clockwise by θ\theta(cos⁡θ−sin⁡θsin⁡θcos⁡θ)\begin{pmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{pmatrix}
Shear: (x,y)↦(x+y, y)(x,y)\mapsto(x+y,\,y)(1101)\begin{pmatrix}1&1\\0&1\end{pmatrix}
Projection onto the line y=xy=x(0.50.50.50.5)\begin{pmatrix}0.5&0.5\\0.5&0.5\end{pmatrix}

A few notes on each.

Scaling uses a diagonal matrix: each diagonal entry scales one axis, so (3,1)↦(6,0.5)(3,1)\mapsto(6,0.5) here. A negative entry also flips that axis. Scaling by the same number ss on both axes is the matrix sIs\mathbf{I}.

Rotation. Turning (1,0)(1,0) by θ\theta puts it at (cos⁡θ,sin⁡θ)(\cos\theta,\sin\theta) on the unit circle, and turning (0,1)(0,1) by θ\theta puts it at (−sin⁡θ,cos⁡θ)(-\sin\theta,\cos\theta). Those are the two columns. For θ=30°\theta=30° they are (0.866,0.5)(0.866, 0.5) and (−0.5,0.866)(-0.5, 0.866), and (3,1)(3,1) goes to (2.098,2.366)(2.098, 2.366). Its length stays 10≈3.162\sqrt{10}\approx3.162: rotations do not change lengths (P1.B10 studies this). For a quarter turn, θ=90°\theta=90°, the matrix is (0−110)\begin{pmatrix}0&-1\\1&0\end{pmatrix}. The widget’s preset uses 0.866 for cos⁡30°\cos30°, which is rounded.

Reflection in the yy-axis sends (3,1)(3,1) to (−3,1)(-3,1), and the F comes out backwards.

Shear. Each row slides sideways in proportion to its height. (1,0)(1,0) stays at (1,0)(1,0) and (0,1)(0,1) lands at (1,1)(1,1), 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 y=xy=x (P1.B11). But (3,1)(3,1) and (1,3)(1,3) both land on (2,2)(2,2), and (1,−1)(1,-1) lands on (0,0)(0,0). Different inputs give the same output, so no matrix can undo it: you cannot tell from (2,2)(2,2) 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 (1,2)(1,2)? Call it T(v)=v+(1,2)T(\mathbf{v})=\mathbf{v}+(1,2). Is it linear? No:

  • It moves the origin: T(0)=(1,2)≠0T(\mathbf{0})=(1,2)\neq\mathbf{0}.
  • It breaks the addition rule: T(1,0)+T(0,1)=(2,2)+(1,3)=(3,5)T(1,0)+T(0,1)=(2,2)+(1,3)=(3,5), but T(1,1)=(2,3)T(1,1)=(2,3).

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:

x ⟼ Wx+b\mathbf{x}\ \longmapsto\ \mathbf{W}\mathbf{x}+\mathbf{b}

This is what a neural-network layer computes, and the vector b\mathbf{b} is called the bias. Without it, a layer could never move the origin. A full layer then squashes the result with an activation function σ\sigma (sigmoid, tanh⁡\tanh, and so on; P1.A5), applied to each entry separately:

x → warp: Wx  ⋅ → shift: +b  z→ squash: σ  σ(z)\begin{gathered} \mathbf{x}\ \xrightarrow{\ \text{warp: }\mathbf{W}\mathbf{x}\ }\ \cdot\ \xrightarrow{\ \text{shift: }+\mathbf{b}\ }\ \mathbf{z} \\ \xrightarrow{\ \text{squash: }\sigma\ }\ \sigma(\mathbf{z}) \end{gathered}

Here are small numbers. Let W=(1−121)\mathbf{W}=\begin{pmatrix}1&-1\\2&1\end{pmatrix}, x=(1,2)\mathbf{x}=(1,2) and b=(1,−2)\mathbf{b}=(1,-2).

Wx=(1−22+2)=(−14)z=Wx+b=(02)σ(z)≈(0.50.881)\begin{aligned} \mathbf{W}\mathbf{x}&=\begin{pmatrix}1-2\\2+2\end{pmatrix}=\begin{pmatrix}-1\\4\end{pmatrix}\\ \mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}&=\begin{pmatrix}0\\2\end{pmatrix}\\ \sigma(\mathbf{z})&\approx\begin{pmatrix}0.5\\0.881\end{pmatrix} \end{aligned}

(using the sigmoid σ(z)=1/(1+e−z)\sigma(z)=1/(1+e^{-z}), so σ(0)=0.5\sigma(0)=0.5 and σ(2)≈0.881\sigma(2)\approx0.881). 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 B=(100111)\mathbf{B}=\begin{pmatrix}1&0\\0&1\\1&1\end{pmatrix} is 3×23\times2. It takes a 2-entry vector and gives a 3-entry one:

B(23)=2(101)+3(011)=(235)\mathbf{B}\begin{pmatrix}2\\3\end{pmatrix}=2\begin{pmatrix}1\\0\\1\end{pmatrix}+3\begin{pmatrix}0\\1\\1\end{pmatrix}=\begin{pmatrix}2\\3\\5\end{pmatrix}

It maps the plane into 3-D space. The outputs do not fill 3-D: they all lie on one flat sheet (the plane z=x+yz=x+y), a copy of the plane sitting inside 3-D. In the other direction, (100010)\begin{pmatrix}1&0&0\\0&1&0\end{pmatrix} is 2×32\times3: it takes 3-D vectors to 2-D ones by dropping the third entry, so (2,3,5)↦(2,3)(2,3,5)\mapsto(2,3). 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 128×784=100,352128\times784=100{,}352 entries, plus 128 bias entries. (This size is just an example.) The widget in this lesson is 2×22\times2 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.

Try it: a data matrix, rows and columns

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.

Try it: a matrix times a vector

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 ff from Rn\mathbb{R}^n to Rm\mathbb{R}^m is some matrix. Write x=x1e1+⋯+xnen\mathbf{x}=x_1\mathbf{e}_1+\dots+x_n\mathbf{e}_n. Linearity lets you push ff through the sum:

f(x)=x1f(e1)+⋯+xnf(en)f(\mathbf{x})=x_1f(\mathbf{e}_1)+\dots+x_nf(\mathbf{e}_n)

This is Way 2 with the columns f(e1),…,f(en)f(\mathbf{e}_1),\dots,f(\mathbf{e}_n). So the matrix whose columns are the images of the basis vectors does exactly what ff does. That is why the two test inputs (1,0)(1,0) and (0,1)(0,1) 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 2×22\times2 matrix, but it can be a 3×33\times3 one if you add a fixed extra entry 1 to every vector. For the layer above, put b\mathbf{b} in a new last column and add a bottom row (0,0,1)(0,0,1):

(1−1121−2001)(121)=(021)\begin{pmatrix}1&-1&1\\2&1&-2\\0&0&1\end{pmatrix}\begin{pmatrix}1\\2\\1\end{pmatrix}=\begin{pmatrix}0\\2\\1\end{pmatrix}

The first two entries of the result, (0,2)(0,2), are exactly Wx+b\mathbf{W}\mathbf{x}+\mathbf{b}, 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 Wx\mathbf{W}\mathbf{x} 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 W=(123456)\mathbf{W}=\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix} and two examples (1,0,−1)(1,0,-1) and (2,1,0)(2,1,0) stacked as the rows of X\mathbf{X}:

XW⊤=(10−1210)(142536)=(−2−2413)\begin{aligned} \mathbf{X}\mathbf{W}^\top&=\begin{pmatrix}1&0&-1\\2&1&0\end{pmatrix}\begin{pmatrix}1&4\\2&5\\3&6\end{pmatrix} \\ &=\begin{pmatrix}-2&-2\\4&13\end{pmatrix} \end{aligned}

Row 1 of the result, (−2,−2)(-2,-2), equals Wx1\mathbf{W}\mathbf{x}_1 for the first example, and row 2, (4,13)(4,13), equals Wx2\mathbf{W}\mathbf{x}_2. 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 W\mathbf{W}, and computes xW⊤+b\mathbf{x}\mathbf{W}^\top+\mathbf{b} 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

  1. A matrix has 3 rows and 5 columns. What is its shape?

  2. What is (2003)(11)\begin{pmatrix}2&0\\0&3\end{pmatrix}\begin{pmatrix}1\\1\end{pmatrix}?

  3. A matrix has first column (2,1)(2, 1) and second column (5,7)(5, 7). Where does the arrow (0,1)(0, 1) land?

  4. Which of these maps of the plane is NOT linear?

  5. A matrix with 4 rows and 7 columns is multiplied by a vector. What must the vector look like, and what do you get?

Exercises

  1. What is the shape of (123456)\begin{pmatrix}1&2&3\\4&5&6\end{pmatrix}, and what is A23A_{23}?
    Show answerThe shape is 2×32\times3. A23A_{23} is row 2, column 3, which is 6.
  2. Compute (2103)(4−1)\begin{pmatrix}2&1\\0&3\end{pmatrix}\begin{pmatrix}4\\-1\end{pmatrix} both ways, by rows and by columns.
    Show answerBy rows: 2⋅4+1⋅(−1)=72\cdot4+1\cdot(-1)=7 and 0⋅4+3⋅(−1)=−30\cdot4+3\cdot(-1)=-3. By columns: 4 (2,0)+(−1) (1,3)=(8,0)+(−1,−3)=(7,−3)4\,(2,0)+(-1)\,(1,3)=(8,0)+(-1,-3)=(7,-3). Both give (7,−3)(7,-3).
  3. Write the matrix that sends (1,0)(1,0) to (2,1)(2,1) and (0,1)(0,1) to (−1,3)(-1,3). Where does it send (2,3)(2,3)?
    Show answerThe columns are the landing points: (2−113)\begin{pmatrix}2&-1\\1&3\end{pmatrix}. Then (2,3)↦2(2,1)+3(−1,3)=(4,2)+(−3,9)=(1,11)(2,3)\mapsto2(2,1)+3(-1,3)=(4,2)+(-3,9)=(1,11).
  4. Write the matrix that doubles xx and flips yy (so yy becomes −y-y).
    Show answer(200−1)\begin{pmatrix}2&0\\0&-1\end{pmatrix}: (1,0)(1,0) lands at (2,0)(2,0) and (0,1)(0,1) lands at (0,−1)(0,-1).
  5. Write the matrix for a counter-clockwise quarter turn (90°). Check it on (1,0)(1,0).
    Show answer(0−110)\begin{pmatrix}0&-1\\1&0\end{pmatrix}, from cos⁡90°=0\cos90°=0 and sin⁡90°=1\sin90°=1. Check: (1,0)(1,0) lands at its first column, (0,1)(0,1), which is the arrow (1,0)(1,0) turned a quarter turn left.
  6. Is f(x,y)=(x+y, 2x)f(x,y)=(x+y,\,2x) linear? Is g(x,y)=(x+1, y)g(x,y)=(x+1,\,y)?
    Show answerff is linear: it is the matrix (1120)\begin{pmatrix}1&1\\2&0\end{pmatrix}. gg is not: g(0,0)=(1,0)g(0,0)=(1,0), but a linear map must send the origin to the origin.
  7. You have 1000 images of size 28×2828\times28, and each is flattened into a vector of 784 numbers. What is the shape of the data matrix X\mathbf{X}?
    Show answer1000×7841000\times784: one row per image (example) and one column per pixel (feature). In NumPy, X.shape is (1000, 784).
  8. 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 answerW\mathbf{W} is 128×784128\times784 (rows are outputs), which has 100,352100{,}352 entries. The bias has 128 entries. The total is 100,480100{,}480.
  9. In the matrix-warp widget (the second one), find a matrix that sends (1,0)(1,0) to (0,1)(0,1) and (0,1)(0,1) to (1,0)(1,0). What does it do to the F?
    Show answerThe columns are (0,1)(0,1) and (1,0)(1,0), so (0110)\begin{pmatrix}0&1\\1&0\end{pmatrix} (set A12=1A_{12}=1 and A21=1A_{21}=1). It swaps xx and yy: a mirror in the line y=xy=x, so the F comes out as a mirror image. The status line says det is negative.
  10. Code: with A = np.array([[1, 2], [3, 4]]) and x = np.array([10, 100]), predict A * x and A @ x, then run them.
    Show answerA * x is [[10, 200], [30, 400]] (each row multiplied entry by entry by x). A @ x is [210, 430]: 1⋅10+2⋅100=2101\cdot10+2\cdot100=210 and 3⋅10+4⋅100=4303\cdot10+4\cdot100=430.

Key takeaways

  • A matrix is a rectangular grid of numbers. Its shape is rows by columns, and entries are located row first, then column (row 2, column 3 is written A23A_{23}).
  • As data: each row is one example and each column is one feature, so a dataset with N examples and d features is an N by d matrix. In NumPy, X[i] is one example and X[:, j] is one feature.
  • As a function: A x takes a vector with n entries and gives one with m entries (A has m rows and n columns). Each output entry is a row of A dotted with x.
  • The same result is a linear combination of the columns of A, with the entries of x as weights. So the columns of A are where the arrows (1, 0) and (0, 1) land: read the columns to see the transformation.
  • A map is linear if A(x + y) = Ax + Ay and A(cx) = c·Ax. Then the origin stays put and grid lines stay straight, parallel and evenly spaced (unless the map squashes the plane flat, as a projection does). Scaling, reflection, rotation, shear and projection are all linear.
  • A shift (translation) is not linear, because it moves the origin. A neural-network layer therefore computes W x + b, a linear map followed by a shift, and then a squashing function.
  • In NumPy, A @ x is the matrix-vector product, while A * x multiplies entry by entry. A matrix times a vector fails if the number of columns does not match the length of the vector.
Found a mistake? Tell us