AI State of the Art
Math/Linear Algebra/12 min
Section 314

Vectors and Matrices: The Building Blocks

Listen as a podcast โ†’

Introduction: why linear algebra?

Machine learning (ML) is about manipulating numbers. Lots of numbers. A language model like GPT processes billions of parameters, an image contains millions of pixels, a dataset can have thousands of columns.

To organize and manipulate all these numbers efficiently, you need structures. That's exactly what vectors, matrices, and tensors provide. Without them, no ML.

Linear algebra isn't a boring prerequisite. It's the native language of deep learning.

Vectors: ordered lists of numbers

Geometric view

A vector is an arrow in space. In 2D, the vector v=(32)\mathbf{v} = \begin{pmatrix} 3 \\ 2 \end{pmatrix} represents a displacement of 3 units to the right and 2 upward.

In 3D, you add a component: v=(321)\mathbf{v} = \begin{pmatrix} 3 \\ 2 \\ 1 \end{pmatrix}.

So far, nothing complicated. But the powerful idea is that you can generalize to any dimension. A vector in dimension 768 is just a list of 768 numbers. You can no longer draw it, but you can still manipulate it mathematically.

Numerical view

More concretely, a vector of dimension nn is an element of Rn\mathbb{R}^n:

v=(v1v2โ‹ฎvn)\mathbf{v} = \begin{pmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{pmatrix}

It's an ordered list of nn real numbers.

Vectors in machine learning

In ML, vectors are everywhere:

  • Feature vector: each example in the dataset is described by a vector. An apartment described by (area, number of rooms, floor, distance to subway) = a 4-dimensional vector.

  • Embeddings: a word, a sentence, or an image is represented by a dense vector. The word "cat" in Word2Vec is a 300-dimensional vector. In GPT, a token is a 12,288-dimensional vector.

  • Neuron weights: each neuron has a weight vector w\mathbf{w} that determines the importance of each input.

  • Gradients: during training, the gradient of the loss with respect to parameters is a vector pointing in the direction of steepest ascent.

The useful analogy: a vector is a point in a space. Two words close in meaning have close vectors in the embedding space. It's this idea that allows a model to understand that "king" and "queen" are related.

Two identical planes each carrying four blue vectors from the origin: Queen (0.3, 0.9), King (0.5, 0.7), Woman (0.3, 0.4) and Man (0.5, 0.2). Red arrows link Queen to Woman and King to Man on the left plane, Queen to King and Woman to Man on the right plane.
Four words reduced to 2-dimensional vectors so they can be drawn. What matters is the red arrows: the gap between Queen and Woman is the same as the gap between King and Man (left), and the gap between Queen and King the same as between Woman and Man (right). Meaning becomes a position in space, and relations between words become displacements.Source : Pantelis Monogioudis, Data Mining course (CS634), Word2Vec

Matrices: tables of numbers

Definition

A matrix is a rectangular table of numbers, with mm rows and nn columns. We denote it AโˆˆRmร—n\mathbf{A} \in \mathbb{R}^{m \times n}:

A=(a11a12โ‹ฏa1na21a22โ‹ฏa2nโ‹ฎโ‹ฎโ‹ฑโ‹ฎam1am2โ‹ฏamn)\mathbf{A} = \begin{pmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \end{pmatrix}

The element at row ii and column jj is denoted aija_{ij}.

A column vector is a matrix of size nร—1n \times 1. A row vector is a matrix of size 1ร—n1 \times n. A scalar is a 1ร—11 \times 1 matrix. Matrices encompass everything.

Matrices in machine learning

Matrices are the natural format for data and models:

  • Dataset: a tabular dataset with mm examples and nn features is a matrix XโˆˆRmร—n\mathbf{X} \in \mathbb{R}^{m \times n}. Each row is an example, each column is a feature. 1,000 patients with 50 measurements each? A 1000ร—501000 \times 50 matrix.

  • Weight matrix: in a neural network, a linear layer transforms an input vector of dimension nn into an output vector of dimension pp. This transformation is entirely defined by a matrix WโˆˆRpร—n\mathbf{W} \in \mathbb{R}^{p \times n}.

  • Attention matrix: in a Transformer, attention scores form a matrix indicating how much each token "attends to" each other token.

  • Confusion matrix: in evaluation, it summarizes the correct and incorrect predictions of a classifier.

Square matrices and special types

Some types of matrices you'll encounter often:

  • Square matrix (m=nm = n): same number of rows and columns
  • Identity matrix I\mathbf{I}: 1s on the diagonal, 0s everywhere else. It's the "neutral element" of matrix multiplication: AI=A\mathbf{AI} = \mathbf{A}
  • Diagonal matrix: nonzero only on the diagonal
  • Symmetric matrix: aij=ajia_{ij} = a_{ji} for all i,ji, j. Covariance matrices are symmetric.

Tensors: the generalization

A scalar is a dimension-0 tensor. A vector, dimension 1. A matrix, dimension 2.

A tensor is the generalization to any number of dimensions (called axes or ranks).

Four objects lined up on a grid: a single number labelled Scalar, a column of two numbers labelled Vector, a 2 by 2 table labelled Matrix, and a stack of two 2 by 2 tables inside brackets labelled Tensor.
The same family of objects, with one more axis at each step. Start from a single number, stack numbers into a column to get a vector, stack columns to get a matrix, then stack matrices: that is a tensor. Nothing new appears at any step, only one more index needed to point at an element.Source : Think Data Science (thinkdsm.org), NumPy chapter

Why tensors are essential

In deep learning, you rarely work with simple matrices:

  • Color image: height ร—\times width ร—\times 3 channels (RGB). That's a 3D tensor. A 224ร—224ร—3224 \times 224 \times 3 image contains about 150,000 numbers.
Three square 3 by 3 grids of decimal numbers drawn in perspective and offset behind one another: the first red, the second green, the third blue. Axes are labelled row, column and channel.
A tiny color image, 3 pixels by 3, seen as an order-3 tensor. Each grid is one channel (red, green, blue) holding the intensity of that color at every pixel. Pointing at one specific number takes three indices: row, column, channel. That is exactly what a shape of 224 x 224 x 3 means.Source : Brandon Rohrer, e2eML
  • Batch of images: when you train a network, you process a batch of BB images at once. That gives a 4D tensor: Bร—Hร—Wร—CB \times H \times W \times C.

  • Token sequence: in a Transformer, a batch of BB sequences of length LL with embeddings of dimension dd forms a 3D tensor: Bร—Lร—dB \times L \times d.

  • Video: a 5D tensor if you add time: Bร—Tร—Hร—Wร—CB \times T \times H \times W \times C.

Notation and conventions

In practice, with PyTorch or NumPy:

  • Dimensions are described by their shape. A tensor of shape (32, 128, 768) represents a batch of 32 sequences of 128 tokens, each encoded by a 768-dimensional vector.

  • The order of dimensions follows conventions. In PyTorch, images are often in (B, C, H, W) format, batch, channels, height, width. In TensorFlow, it's often (B, H, W, C).

  • The memory size is the product of dimensions. A (32, 128, 768) tensor of type float32 (4 bytes) occupies 32ร—128ร—768ร—4โ‰ˆ1232 \times 128 \times 768 \times 4 \approx 12 MB.

Notation and general conventions

Some standard conventions in ML:

NotationMeaning
xx or ฮฑ\alphaScalar (lowercase, italic)
v\mathbf{v} or x\mathbf{x}Vector (lowercase, bold)
A\mathbf{A} or W\mathbf{W}Matrix (uppercase, bold)
X\mathcal{X}Higher-order tensor (calligraphic)
xi\mathbf{x}_iThe ii-th example in the dataset
xjx_jThe jj-th feature
W(l)\mathbf{W}^{(l)}Weight matrix of layer ll

These conventions vary by author, but this base covers the majority of papers and courses.

Why this matters for AI

All information in a deep learning model is stored in tensors. Input data, model weights, intermediate activations, gradients, everything is a tensor.

When you read that GPT-4 has hundreds of billions of parameters, those are numbers organized in gigantic weight matrices. When we talk about semantic embeddings, those are vectors in a high-dimensional space.

Mastering vectors, matrices, and tensors means understanding the data format that AI manipulates. It's the essential first step.

Where this is used. The perceptron, the smallest network building block, is already a vector-matrix product.