Linear Algebra for Artificial Intelligence
Neural networks, images, and language models all run on the same engine: vectors and matrices. This lesson explains every building block — from a single number to eigenvalues — in plain language, with equations you can read and diagrams you can see.
Why Linear Algebra Is the Language of AI
When you hear that a neural network has "millions of parameters," those parameters are stored as matrices. When an image is fed into a model, it becomes a vector (or a stack of vectors). When one layer talks to the next, the operation is almost always matrix multiplication. Linear algebra is not an optional side topic — it is the grammar every AI system speaks.
If you completed Lesson 1, you already know numbers, functions, and equations. This lesson adds the geometric and structural tools that make large-scale AI computation possible on a GPU.
Scalars
A scalar is simply a single number — one value with no direction attached. Temperature (23°C), a learning rate (0.001), or a pixel brightness (0.87) are all scalars.
Scalars are usually written in lowercase italic: \(a\), \(b\), \(\lambda\), \(\eta\)
Operations: add, subtract, multiply, divide — ordinary arithmetic.
\(c = a + b\), \(d = 3 \times a\), \(e = \dfrac{a}{b}\)
Scalars vs. vectors vs. matrices
| Object | Size | Example | AI role |
|---|---|---|---|
| Scalar | 0 dimensions | \(5\), \(-0.3\) | Learning rate, loss value, single weight |
| Vector | 1 dimension (list) | \([1, 2, 3]\) | One data sample, one layer's activations |
| Matrix | 2 dimensions (table) | \(3\times3\) grid | All weights in a layer |
The loss at the end of training is a scalar — one number telling you how wrong the model is. The learning rate \(\eta\) is a scalar controlling step size. Even when everything else is huge matrices, you often care about a few key scalars: accuracy, loss, learning rate.
Vectors
A vector is an ordered list of numbers. Think of it as an arrow in space (with direction and length) or simply as a row/column of data.
Column vector (most common in AI): \(\mathbf{v} = \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{bmatrix}\)
Row vector: \(\mathbf{v} = [v_1,\ v_2,\ \ldots,\ v_n]\)
Dimension (length): \(n\) — the number of entries
Magnitude (length)
\(\|\mathbf{v}\| = \sqrt{v_1^2 + v_2^2 + \cdots + v_n^2}\)
Example: \(\mathbf{v} = [3, 4]\) → \(\|\mathbf{v}\| = \sqrt{9+16} = 5\)
Unit vector
A vector with length 1. Normalize any vector by dividing by its magnitude: \(\hat{\mathbf{v}} = \dfrac{\mathbf{v}}{\|\mathbf{v}\|}\)
A house has features: area = 120 m², bedrooms = 3, age = 10 years. As a vector: \(\mathbf{x} = [120,\ 3,\ 10]\). A model reads this vector and outputs a predicted price.
Each training example is a feature vector. A 28×28 grayscale image flattened becomes a vector of 784 numbers. Word embeddings (Word2Vec, BERT) map each word to a dense vector where similar words sit close together.
Matrices
A matrix is a rectangular grid of numbers arranged in rows and columns. If a matrix has \(m\) rows and \(n\) columns, we call it an \(m \times n\) matrix.
\[A = \begin{bmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \end{bmatrix} \quad \text{(a } 2 \times 3 \text{ matrix)}\]
Entry \(a_{ij}\) = row \(i\), column \(j\)
Special shapes
- Square matrix — same number of rows and columns (\(n \times n\))
- Column vector — \(n \times 1\) matrix
- Row vector — \(1 \times n\) matrix
- Transpose \(A^T\) — flip rows and columns
If \(A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}\), then \(A^T = \begin{bmatrix} 1 & 3 \\ 2 & 4 \end{bmatrix}\)
A fully connected layer with 784 inputs and 128 neurons stores its weights in a \(128 \times 784\) matrix. A batch of 32 images is stored as a \(32 \times 784\) matrix — 32 rows, one per image. GPUs are fast precisely because they multiply huge matrices in parallel.
Matrix Operations
Before multiplying matrices, you need the basic arithmetic: adding, subtracting, and scaling — element by element, when shapes match.
Addition and subtraction
Same dimensions required: \((m \times n) + (m \times n) = (m \times n)\)
\[\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} + \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 6 & 8 \\ 10 & 12 \end{bmatrix}\]
Scalar multiplication
Multiply every entry by the scalar: \(3 \cdot \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} = \begin{bmatrix} 3 & 6 \\ 9 & 12 \end{bmatrix}\)
Element-wise (Hadamard) product
\(A \odot B\) — multiply matching entries: \([1,2] \odot [3,4] = [3,8]\)
Used in gates of LSTM/GRU networks and attention masking
Two sensors read temperatures [20, 22] and [18, 21]. Sum vector = [38, 43]. If you scale the second by 0.5 (unit conversion): \(0.5 \times [18,21] = [9, 10.5]\).
Residual connections in ResNet add the input of a layer back to its output: \(\mathbf{y} = F(\mathbf{x}) + \mathbf{x}\). Dropout scales surviving activations by \(\frac{1}{1-p}\) after randomly zeroing some entries. Batch normalization subtracts a mean vector and divides by a standard-deviation vector — all element-wise vector operations on batches stored as matrices.
Matrix Multiplication
Matrix multiplication is the most important operation in deep learning. It is not element-wise — each entry of the result combines an entire row of the first matrix with an entire column of the second.
\(A_{m \times n} \cdot B_{n \times p} = C_{m \times p}\)
Inner dimensions must match: columns of \(A\) = rows of \(B\)
\[c_{ij} = \sum_{k=1}^{n} a_{ik} \cdot b_{kj}\]
Important properties
- Not commutative: \(AB \neq BA\) in general
- Associative: \((AB)C = A(BC)\)
- Distributive: \(A(B+C) = AB + AC\)
Input \(\mathbf{x}\) is \(784 \times 1\). Weights \(W\) are \(128 \times 784\). Bias \(\mathbf{b}\) is \(128 \times 1\).
\[\mathbf{z} = W\mathbf{x} + \mathbf{b} \quad \text{(result: } 128 \times 1 \text{)}\]
Each of the 128 neurons computes one weighted sum of all 784 inputs — matrix multiplication does all 128 at once.
Almost every layer in a transformer, CNN (after im2col), or MLP is implemented as GEMM — General Matrix Multiply. Libraries like cuBLAS and PyTorch's torch.matmul exist solely to make this operation fast. Understanding shapes prevents the #1 beginner bug: dimension mismatch errors.
Identity Matrix
The identity matrix \(I_n\) is the "number 1" of matrix world. It has 1s on the diagonal and 0s everywhere else. Multiplying any matrix by \(I\) leaves it unchanged.
\[I_3 = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix}\]
\[AI = IA = A\]
In attention mechanisms, an identity-style mask (diagonal allowed, rest blocked) prevents a token from "seeing" future tokens. Weight initialization sometimes starts near identity (e.g., orthogonal init) to preserve signal magnitude at the start of training. Skip connections effectively add an identity path: output = layer(x) + x.
Inverse Matrix
The inverse \(A^{-1}\) of a square matrix \(A\) undoes multiplication — like how \(\frac{1}{5}\) undoes multiplying by 5.
\[A \cdot A^{-1} = A^{-1} \cdot A = I\]
Only invertible (non-singular) matrices have an inverse — when \(\det(A) \neq 0\)
2×2 formula: if \(A = \begin{bmatrix} a & b \\ c & d \end{bmatrix}\), then \(A^{-1} = \dfrac{1}{ad-bc}\begin{bmatrix} d & -b \\ -c & a \end{bmatrix}\)
\(A = \begin{bmatrix} 2 & 1 \\ 5 & 3 \end{bmatrix}\), \(\det = 2\cdot3 - 1\cdot5 = 1\)
\(A^{-1} = \begin{bmatrix} 3 & -1 \\ -5 & 2 \end{bmatrix}\). Check: \(AA^{-1} = I\) ✓
Computing \(A^{-1}\) explicitly is rare in deep learning (too expensive for huge matrices). But the idea of inversion appears in solving linear systems, normal equations in linear regression \(\mathbf{w} = (X^TX)^{-1}X^T\mathbf{y}\), and whitening transforms in preprocessing. Optimization prefers iterative methods over direct inversion.
Determinant
The determinant \(\det(A)\) is a single scalar that captures how a square matrix scales area (2D) or volume (3D) when it transforms space. If \(\det(A) = 0\), the matrix squashes space flat — it has no inverse.
2×2: \(\det\begin{bmatrix} a & b \\ c & d \end{bmatrix} = ad - bc\)
3×3: expand by cofactors (sum of signed minor products)
\(\det(AB) = \det(A)\cdot\det(B)\)
A zero determinant means redundant features — the matrix is singular. In PCA, eigenvalues relate to determinants of submatrices. Jacobian determinants appear in normalizing flows (generative models) to track how density changes under a transformation.
Rank
The rank of a matrix is the maximum number of linearly independent rows (or columns). It tells you how much real information the matrix carries — how many dimensions survive the transformation.
\(\text{rank}(A) \leq \min(m, n)\) for an \(m \times n\) matrix
Full rank: \(\text{rank} = \min(m,n)\) — no redundancy
Low rank: rows/columns can be built from fewer independent vectors
\(\begin{bmatrix} 1 & 2 & 3 \\ 2 & 4 & 6 \end{bmatrix}\) has rank 1 — row 2 is just 2× row 1. Only one independent direction.
\(\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}\) has rank 2 — both directions are independent.
Low-rank approximation compresses huge weight matrices (LoRA fine-tuning adds low-rank updates \(W + BA\)). Rank collapse in transformers can make attention maps degenerate. Understanding rank helps you see when embeddings or activations are truly high-dimensional vs. lying on a smaller subspace.
Eigenvalues
An eigenvalue \(\lambda\) tells you how much a matrix stretches its eigenvectors — special directions that only get scaled, not rotated, when the matrix is applied.
\[A\mathbf{v} = \lambda \mathbf{v}\]
\(\lambda\) is an eigenvalue, \(\mathbf{v}\) is the corresponding eigenvector (\(\mathbf{v} \neq \mathbf{0}\))
Find eigenvalues by solving: \(\det(A - \lambda I) = 0\) (the characteristic polynomial)
\(A = \begin{bmatrix} 4 & 1 \\ 2 & 3 \end{bmatrix}\). Characteristic equation:
\((4-\lambda)(3-\lambda) - 2 = \lambda^2 - 7\lambda + 10 = 0\)
Eigenvalues: \(\lambda_1 = 5\), \(\lambda_2 = 2\)
PCA finds eigenvalues of the covariance matrix — largest eigenvalues = directions of maximum variance in data. Spectral analysis of graph Laplacians powers graph neural networks. Stability of recurrent networks can be studied via eigenvalues of the weight matrix (values > 1 can cause exploding gradients).
Eigenvectors
For each eigenvalue \(\lambda\), an eigenvector \(\mathbf{v}\) is the direction that matrix \(A\) stretches by factor \(\lambda\) without turning.
Solve \((A - \lambda I)\mathbf{v} = \mathbf{0}\) for each \(\lambda\)
Example: for \(\lambda = 5\), \(A = \begin{bmatrix} 4 & 1 \\ 2 & 3 \end{bmatrix}\):
\(\begin{bmatrix} -1 & 1 \\ 2 & -2 \end{bmatrix}\mathbf{v} = \mathbf{0}\) → \(\mathbf{v} = \begin{bmatrix} 1 \\ 1 \end{bmatrix}\) (or any scalar multiple)
Diagonalization
If \(A\) has enough independent eigenvectors, \(A = PDP^{-1}\) where \(D\) is diagonal (eigenvalues on the diagonal) and columns of \(P\) are eigenvectors. This decomposes complex matrix action into simple scaling along each axis.
PCA principal components are eigenvectors of the covariance matrix. In PageRank and GNNs, the dominant eigenvector of a matrix reveals the most important node scores. Eigendecomposition turns covariance structure into interpretable axes for visualization (t-SNE builds on similar ideas).
Dot Product
The dot product (inner product) multiplies matching entries and sums them. It measures how much two vectors point in the same direction.
\[\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i = a_1b_1 + a_2b_2 + \cdots + a_nb_n\]
\[\mathbf{a} \cdot \mathbf{b} = \|\mathbf{a}\| \|\mathbf{b}\| \cos\theta\]
Result is a scalar
\(\mathbf{a}=[1,2,3]\), \(\mathbf{b}=[4,5,6]\): dot \(= 1\cdot4 + 2\cdot5 + 3\cdot6 = 32\)
Orthogonal check: \([1,0] \cdot [0,1] = 0\) — perpendicular vectors
Every neuron computes a dot product between its weight vector and the input vector (plus bias). Attention scores in transformers are scaled dot products \(\frac{QK^T}{\sqrt{d_k}}\). Cosine similarity between embeddings is the dot product of normalized vectors — used in search, RAG, and recommendation systems.
Cross Product
The cross product applies only to vectors in 3D (or the 2D scalar version). It produces a vector perpendicular to both inputs, with magnitude equal to the area of the parallelogram they span.
\[\mathbf{a} \times \mathbf{b} = \begin{bmatrix} a_2b_3 - a_3b_2 \\ a_3b_1 - a_1b_3 \\ a_1b_2 - a_2b_1 \end{bmatrix}\]
\(\|\mathbf{a} \times \mathbf{b}\| = \|\mathbf{a}\| \|\mathbf{b}\| \sin\theta\)
\(\mathbf{a} \times \mathbf{b} = -\mathbf{b} \times \mathbf{a}\) (anti-commutative)
Cross products are less central than dot products in standard deep learning, but they appear in 3D vision (surface normals, camera geometry), robotics, and physics-informed neural networks. The 2D scalar cross product (determinant of two 2D vectors) is used in computational geometry for orientation tests.
Matrix Transformations
Every matrix multiplication can be read as a transformation of space: rotating, scaling, shearing, or projecting vectors. A matrix is a machine that moves every point in space according to fixed rules.
Common transformations
| Transform | 2×2 matrix | Effect |
|---|---|---|
| Scale x by 2, y by 3 | \(\begin{bmatrix} 2 & 0 \\ 0 & 3 \end{bmatrix}\) | Stretch axes |
| Rotate by θ | \(\begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}\) | Turn space |
| Shear | \(\begin{bmatrix} 1 & k \\ 0 & 1 \end{bmatrix}\) | Slant sideways |
| Projection | rank-1 matrix | Collapse onto a line |
Compose transforms by multiplying matrices: \(T_{\text{total}} = T_2 T_1\) (apply \(T_1\) first, then \(T_2\))
Affine transform (used in data augmentation): \(\mathbf{y} = A\mathbf{x} + \mathbf{b}\)
CNN filters apply small linear transformations locally across an image. Data augmentation uses rotation/scaling matrices on images. In transformers, positional encodings add structured vectors so the model knows token order. Understanding transforms helps you debug why augmented data looks "wrong" or why features collapse.
Applications in Neural Networks
Every concept in this lesson converges inside a working neural network. Here is the full map.
1 · Forward pass of one layer
\[\mathbf{z}^{(l)} = W^{(l)} \mathbf{a}^{(l-1)} + \mathbf{b}^{(l)}\]
\[\mathbf{a}^{(l)} = f(\mathbf{z}^{(l)})\]
Matrix multiply + bias (vector add) + activation function applied element-wise
2 · Batch processing
\[Z = XW^T + B\]
\(X\): batch of \(N\) samples (\(N \times d_{in}\)), \(W\): weights (\(d_{out} \times d_{in}\))
One matrix multiply processes the entire mini-batch — why GPUs win
3 · Attention (transformer core)
\[\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}}\right) V\]
\(QK^T\): matrix of dot products between queries and keys
\(V\): values blended by attention weights
4 · Dimensionality reduction (PCA)
1. Build covariance matrix \(C\) from data
2. Find eigenvectors of \(C\) (principal components)
3. Project data: \(\mathbf{z} = W_{PCA}^T \mathbf{x}\) (keep top eigenvalues)
You do not need to derive every theorem by hand. You do need to recognize when a paper says \(W \in \mathbb{R}^{d \times k}\) what shape of object that is, why \(AB \neq BA\) matters for composition order, and why attention is a softmax over dot products. That fluency — reading linear algebra as the operating manual of AI — is what this lesson builds.