Mathematical Foundations

Linear Algebra

Linear Algebra for AI & Machine Learning | Lesson 2 — Free Guide (Vectors, Matrices, Eigenvalues)
Lesson 2 · AI Engineering Foundations

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.

16 topics
Beginner → Applied
Equations + SVG
Neural networks
00 Overview

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.

Data — features, pixels, word embeddings are vectors
Models — weights connecting layers are matrices
Computation — forward pass = matrix × vector
Learning — gradients flow through matrix calculus
Input vector x Weights matrix W Wx + b Output vector z × many layers
One neural layer: multiply input vector by a weight matrix, add a bias vector — repeat
Prerequisite

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.

01 Building blocks

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.

Notation

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

ObjectSizeExampleAI role
Scalar0 dimensions\(5\), \(-0.3\)Learning rate, loss value, single weight
Vector1 dimension (list)\([1, 2, 3]\)One data sample, one layer's activations
Matrix2 dimensions (table)\(3\times3\) gridAll weights in a layer
AI connection

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.

02 Building blocks

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.

Definitions

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

x y v = (3, 4) length = 5
A 2D vector is an arrow from the origin; its entries are the coordinates of the tip

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}\|}\)

Worked example

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.

AI connection

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.

03 Building blocks

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

Matrix A (2 × 3) 1 2 3 4 5 6 a₁₁ a₂₂ 3 columns 2 rows
Rows go horizontally; columns go vertically. Subscripts name each cell

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}\)

AI connection

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.

04 Operations

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

Worked example

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]\).

AI connection

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.

05 Operations

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.

Rule

\(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}\]

(2×3) · (3×2) = (2×2) A 1 2 3 4 5 6 × B 7 8 9 10 = C 23 34 58 78 c₁₁ = (1×7) + (2×9) + (3×?) — row 1 of A · column 1 of B highlighted cells multiply & sum
Each output cell = dot product of one row (A) with one column (B)

Important properties

  • Not commutative: \(AB \neq BA\) in general
  • Associative: \((AB)C = A(BC)\)
  • Distributive: \(A(B+C) = AB + AC\)
Neural layer example

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.

AI connection

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.

06 Special matrices

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\]

1 0 0 1 I₂ — diagonal of ones
The identity matrix leaves vectors and matrices unchanged when multiplied
AI connection

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.

07 Special matrices

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}\)

Worked example

\(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\) ✓

AI connection

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.

08 Properties

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

area = 1 → A → area = |det(A)| det<0: flip
Determinant = factor by which area/volume scales (sign indicates orientation flip)
AI connection

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.

09 Properties

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

Intuition

\(\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.

AI connection

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.

10 Eigenanalysis

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.

Definition

\[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)

Worked example

\(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\)

AI connection

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

11 Eigenanalysis

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)

v (eigenvector) Av = λv (same line)
Eigenvectors stay on the same line after transformation — only their length changes by λ

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.

AI connection

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

12 Vector products

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

θ a b
Dot product large when θ is small (vectors align); zero when θ = 90° (orthogonal)
Worked example

\(\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

AI connection

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.

13 Vector products

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)

a b a×b perpendicular to both
Cross product direction follows the right-hand rule (3D)
AI connection

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.

14 Geometry

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

Transform2×2 matrixEffect
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
Projectionrank-1 matrixCollapse onto a line
Before After rotation × R(θ)
Applying a rotation matrix R(θ) to every point rotates the entire grid

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}\)

AI connection

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.

15 Synthesis

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)

Linear algebra inside a deep learning stack Input vectorx ∈ ℝⁿ W · x + bmatmul Activationσ(z) AttentionQKᵀV Lossscalar Embeddingsvectors Weight matricesW, rank, LoRA PCA / SVDeigenvalues Every box is scalars, vectors, or matrices operating together
From input to loss: linear algebra is the substrate of every step
Scalars — loss, learning rate, regularization λ
Vectors — features, embeddings, gradients
Matrices — layer weights, attention maps, batches
Eigenanalysis — PCA, spectral methods, stability
The takeaway

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.

Frequently Asked Questions

Why is linear algebra important for AI and machine learning?
Neural networks store weights as matrices, data samples as vectors, and layer computations as matrix multiplication. Attention in transformers uses dot products. PCA and dimensionality reduction rely on eigenvalues and eigenvectors. Linear algebra is the computational language of modern AI.
What topics does Lesson 2 cover?
16 topics: why linear algebra matters in AI, scalars, vectors, matrices, matrix operations, matrix multiplication, identity matrix, inverse matrix, determinant, rank, eigenvalues, eigenvectors, dot product, cross product, matrix transformations, and applications in neural networks including attention and PCA.
Do I need prior math before this linear algebra lesson?
Lesson 1 (basic math for AI) is recommended but not required. This lesson explains every concept from scratch with plain language, equations, worked examples, and diagrams tied to neural networks and deep learning.
Is this linear algebra lesson free?
Yes. The full lesson is free and accessible in English and Arabic, with no signup required.