Skip to content
LearnAI
PART 1 · FOUNDATIONS/ Math toolkit

1.3Matrices as transformations

A matrix is a machine that moves every point in space at once, rotating, stretching, shearing or flattening it. Every neural-network layer is one, plus a shift.

⏱ 12 minBeginner

From one dot product to many

In the previous lesson a single neuron took one dot product: its weight vector against the input. A real layer has many neurons, each with its own weight vector, all looking at the same input. Stack those weight vectors as the rows of a grid and you have a matrixMatrixA rectangular grid of numbers. Multiplying a vector by a matrix applies a linear transformation such as a rotation, scaling or projection. WW. Multiplying the input vector by it computes all the dot products at once:

Wx=(row1⋅xrow2⋅x⋮).W\mathbf{x} = \begin{pmatrix} \text{row}_1 \cdot \mathbf{x} \\ \text{row}_2 \cdot \mathbf{x} \\ \vdots \end{pmatrix} .

That is the “list of dot products” view, and it is exactly how a GPU computes it. But there is a second view that gives far better intuition: a matrix is a function that moves points. Feed in a vector, get out a new vector. Apply it to every point of the plane, and the plane itself bends, stretches and turns.

ANALOGY· A sheet of rubber with a grid printed on it

Print a square grid on a rubber sheet and pin the center to the table. Now grab the sheet and stretch it, twist it, or slide the top edge sideways. The grid lines stay straight and evenly spaced, the center never moves, but squares become rectangles, diamonds or slanted parallelograms.

Each way of deforming the sheet is a matrix. The pinned center is the origin, which a matrix never moves. Where the two grid arrows along the bottom-left square end up are the columns of the matrix. And how much the area of each little square grows or shrinks is the determinant.

What a matrix does to space

A 2×2 matrix has four numbers:

W=(abcd),W(x1x2)=(ax1+bx2cx1+dx2).W = \begin{pmatrix} a & b \\ c & d \end{pmatrix}, \qquad W\begin{pmatrix} x_1 \\ x_2 \end{pmatrix} = \begin{pmatrix} a x_1 + b x_2 \\ c x_1 + d x_2 \end{pmatrix} .

Here is the key trick for reading one. The two basic arrows ı^=(1,0)\hat\imath = (1, 0) (“one step right”) and ȷ^=(0,1)\hat\jmath = (0, 1) (“one step up”) get sent to

Wı^=(ac),Wȷ^=(bd).W\hat\imath = \begin{pmatrix} a \\ c \end{pmatrix}, \qquad W\hat\jmath = \begin{pmatrix} b \\ d \end{pmatrix} .

The columns of the matrix are where the basis arrows land. And since any vector is a combination of these two, x=x1ı^+x2ȷ^\mathbf{x} = x_1\hat\imath + x_2\hat\jmath, its image is the same combination of the new arrows: Wx=x1(column 1)+x2(column 2)W\mathbf{x} = x_1(\text{column 1}) + x_2(\text{column 2}). Knowing where two arrows go tells you where everything goes. That is why grid lines stay straight and evenly spaced. Functions with this property are called linear transformationsLinear transformationA function on vectors that keeps grid lines straight, parallel and evenly spaced and keeps the origin fixed. Every one can be written as multiplication by a matrix., and every one of them is a matrix.

INTERACTIVEGrid-warping matrix transformer
area 1îĵWxx
Matrix W
det W = 1×1 − 1×0 = 1
x = (1.5, 1) (drag the grey arrow tip)
Wx = (1·1.5 + 1·1, 0·1.5 + 1·1)
   = (2.5, 1)

Slides each row sideways in proportion to its height. Squares become parallelograms with the same area.

Pick a preset or move the four sliders. The blue grid is the transformed plane, the green and orange arrows are where î and ĵ land (the matrix columns), and the shaded parallelogram is the image of the unit square with its area. Drag the grey arrow x to see Wx.

Things to try:

  1. Rotate 30°. The grid turns rigidly. The area of the square stays exactly 1: rotations preserve area, so det⁡=1\det = 1.
  2. Shear. Only one number changed from the identity (b=1b = 1), and the grid leans over. Squares become slanted parallelograms with the same area.
  3. Reflect. The area is still 1, but the parallelogram turns red: det⁡=−1\det = -1. Orientation flipped, like looking in a mirror. Notice that î and ĵ have swapped their clockwise order.
  4. Project to x-axis. The entire plane collapses onto a line, the area goes to 0, and det⁡=0\det = 0. Many different inputs now land on the same output, so there is no way to undo it.
  5. Move slider dd slowly through 0 starting from the shear. Watch the determinant pass through zero exactly when the parallelogram flattens.
  6. Turn on the bias. The whole grid shifts. The origin moves now, so strictly speaking this is no longer linear. It is an affine map, and it is exactly what a neural-network layer computes.

The determinant: how much area changes

The determinantDeterminantA single number computed from a square matrix: the factor by which the transformation scales areas (or volumes). Negative means orientation flips; zero means space is flattened. of a 2×2 matrix is

det⁡W=ad−bc.\det W = ad - bc .

Geometrically it is the area of the parallelogram that the unit square becomes, with a sign. Every region of the plane gets scaled by the same factor: if det⁡W=3\det W = 3, every shape triples in area. A negative determinant means the transformation also flips orientation. A determinant of zero means the matrix squashes space into a lower dimension (a line or a point), and information is destroyed.

In higher dimensions the same idea holds with volumes. You won’t compute determinants much when working with neural networks, but the picture of “does this squash space or not?” comes up often. For example, a layer that maps 4,096 numbers down to 1,024 must lose information, and understanding what it keeps is part of interpretability research.

Layers are matrices (plus a shift)

A fully connected neural-network layer computes

y=Wx+b,\mathbf{y} = W\mathbf{x} + \mathbf{b} ,

where WW is a weight matrix and b\mathbf{b} is a bias vector. In the demo’s language: warp the space with WW, then slide it by b\mathbf{b}. The weights and biases are the parameters that training adjusts.

Real layers are not 2×2. Matrices can be rectangular: a matrix with mm rows and nn columns maps nn-dimensional vectors to mm-dimensional ones. In a mid-sized LLM, the hidden vectors have a few thousand entries. One 4,096×4,096 matrix already holds about 16.8 million numbers, and the feed-forward block of Llama 3 8B maps 4,096 dimensions up to 14,336 and back. Most of an LLM’s parameters live in matrices like these, and most of its running time is spent multiplying by them.

What does training actually do to these matrices? It adjusts every entry, a little at a time, so that each layer warps the space in a way that makes the next layer’s job easier. A helpful picture for classifiers: the raw inputs of two classes may be tangled together, like two interleaved spirals. Layer by layer (with nonlinearities in between), the network stretches and folds the space until the two classes sit in separate regions, and the final layer only has to draw a flat boundary between them. The 2D demo shows a single, fixed step of that process. A trained network chains dozens of them, each one learned.

Changing dimensions

Square matrices warp a space into itself, like the demo. Rectangular ones move vectors between spaces of different sizes, and LLMs use both kinds constantly:

  • Going up. A 3×2 matrix takes 2D vectors to 3D. The output can only fill a flat 2D sheet inside 3D space, since the matrix has only two columns to combine, but that sheet can be tilted in any way. Transformer feed-forward blocks expand each token’s vector to a wider space (often about 3 to 4 times wider) where a nonlinearity can separate features more easily.
  • Going down. A 2×3 matrix squeezes 3D into 2D, necessarily losing some information. The feed-forward block’s second matrix compresses back to the original width, keeping what training found useful.
  • Lookups. Even the very first step of an LLM, turning a token into a vector, can be written as a matrix multiplication: multiply a one-hot vector (all zeros except a 1 at the token’s index) by the embedding matrix, and you pick out one row. In practice it is implemented as a direct lookup because that is faster.

What it costs

Each output entry of WxW\mathbf{x} is a dot product of length nn: nn multiplications and about nn additions. An m×nm \times n matrix therefore costs about 2mn2mn floating-point operations (FLOPs) per input vector, which is two per parameter. That gives a handy rule of thumb you will meet again in scaling laws: running a model on one token costs roughly 2 FLOPs per parameter. For a 7-billion-parameter model, that is about 14 billion operations per token, and modern GPUs do hundreds of trillions of these per second.

Because every row’s dot product is independent of the others, all of them can be computed at the same time. That is why GPUs, with thousands of simple parallel cores, are such a good fit for neural networks, as the history lesson described.

MATH CORNER · optionalMatrix–vector products, composition and the determinant

Matrix–vector product. For an m×nm \times n matrix WW and an nn-vector x\mathbf{x}, the output has mm entries:

(Wx)i=∑j=1nWij xj.(W\mathbf{x})_i = \sum_{j=1}^{n} W_{ij}\, x_j .

Each output is the dot product of row ii with x\mathbf{x}; equivalently, the output is a weighted sum of the columns.

Worked example. Let W=(2101)W = \begin{pmatrix} 2 & 1 \\ 0 & 1 \end{pmatrix} (a stretch plus a shear) and x=(1,2)\mathbf{x} = (1, 2).

viewcomputationresult
rows · x(2⋅1+1⋅2,  0⋅1+1⋅2)(2\cdot1 + 1\cdot2,\; 0\cdot1 + 1\cdot2)(4,2)(4, 2)
columns1⋅(2,0)+2⋅(1,1)1\cdot(2, 0) + 2\cdot(1, 1)(4,2)(4, 2)
determinant2⋅1−1⋅02\cdot1 - 1\cdot022 (areas double)
with bias b=(−1,0.5)\mathbf{b} = (-1, 0.5)(4,2)+(−1,0.5)(4, 2) + (-1, 0.5)(3,2.5)(3, 2.5)

Set a=2,b=1,c=0,d=1a = 2, b = 1, c = 0, d = 1 in the demo and drag x\mathbf{x} to (1,2)(1, 2) to check.

Composition is multiplication. Doing AA then BB is the single matrix BABA (note the order: the matrix applied first is written on the right). For example, rotating by 90° twice, R=(0−110)R = \begin{pmatrix} 0 & -1 \\ 1 & 0\end{pmatrix}, gives R2=(−100−1)R^2 = \begin{pmatrix} -1 & 0 \\ 0 & -1 \end{pmatrix}, a rotation by 180°. Determinants multiply too: det⁡(BA)=det⁡B⋅det⁡A\det(BA) = \det B \cdot \det A, which makes sense, since area scale factors compound.

Inverses. If det⁡W≠0\det W \neq 0, there is a matrix W−1W^{-1} that undoes WW. For 2×2:

W−1=1ad−bc(d−b−ca).W^{-1} = \frac{1}{ad - bc}\begin{pmatrix} d & -b \\ -c & a \end{pmatrix} .

The 1/(ad−bc)1/(ad - bc) factor shows directly why a zero determinant means no inverse.

In code

A whole layer, forward pass included, in a few lines:

import numpy as np

W = np.array([[2.0, 1.0],
              [0.0, 1.0]])
x = np.array([1.0, 2.0])
b = np.array([-1.0, 0.5])

print(W @ x)                 # [4. 2.]
print(W @ x + b)             # [3.  2.5]   <- a linear layer
print(np.linalg.det(W))      # 2.0

# A real layer: 4096 inputs -> 1024 outputs, applied to a batch of 8 vectors
layer = np.random.randn(1024, 4096) * 0.02
batch = np.random.randn(8, 4096)
out = batch @ layer.T        # shape (8, 1024): 8 x 1024 dot products of length 4096
print(out.shape, layer.size) # (8, 1024) 4194304 parameters

# In PyTorch the same layer is: torch.nn.Linear(4096, 1024)
COMMON MISCONCEPTIONS
  • “A matrix is just a table for storing numbers.” It can be used that way, but in machine learning a weight matrix is best understood as a transformation that moves every input vector to an output vector.
  • “Stacking more linear layers makes a model more powerful.” Without nonlinear activations, any stack of linear layers collapses into a single matrix. Depth only helps because of the nonlinearities in between.
  • “Matrix multiplication is commutative, like regular multiplication.” In general AB≠BAAB \neq BA: rotating then shearing is not the same as shearing then rotating. Order matters.
  • “A zero determinant means the matrix is all zeros.” It means the matrix flattens space into fewer dimensions, as the projection preset does. The matrix (1000)\begin{pmatrix}1 & 0\\0 & 0\end{pmatrix} has non-zero entries and determinant 0.

Check your understanding

0/4 answered
  1. Q1.A 2×2 matrix has first column (0, 1) and second column (−1, 0). Where does the vector (1, 0) go?

  2. Q2.A matrix has determinant −2. What does it do to the unit square?

  3. Q3.Why do neural networks put nonlinear activation functions between their matrix layers?

  4. Q4.A layer maps vectors with 512 entries to vectors with 2,048 entries using y = Wx + b. How many parameters does it have?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.