Vectors and Matrices

In the Math topic group, we’ll look at the most important concepts that underpin ML and AI systems.

Understanding the fundamental concepts here is necessary in order to grasp more complicated concepts in AI, such as ML algorithms and deep learning.

Besides, math is awesome. And I’ve written all these pretty math equations for us to explore!

Linear algebra is the backbone of machine learning and AI.

Or maybe the backbone is calculus…

Anyway, we’ll be talking about calculus later. For now, it’s all about vectors and matrices.

This Lesson Will Cover
  • 📏 Vectors and their operations
  • ✖️ Dot product and magnitude
  • 📐 Unit vectors and cosine similarity
  • 🧮 Basic matrix operations
  • ➗ Matrix multiplication and its applications
  • 🖼️ Example: CNN sliding window convolution
Foundational Topics in Linear Algebra for ML
Foundational topics in linear algebra for ML.

Vector Operations

Vectors are ordered lists of numbers. They might represent data points, features, or even directions in space.

For example:

Description Indices Example
A data point vector representing information about a person height, weight, age [170, 65, 25]
A word embedding vector representing semantic meaning embedding for “cat” [0.8, 0.6, 0.2, 0.0, 0.5, 0.4]
A direction vector in 3D space x, y, z [1, 0, -1]

Dot Product

The dot product is a way to combine two vectors to produce a single scalar (number).

It’s calculated as:

a⋅b=∑i=1naibi \mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i

For example, if a=[1,2,3]\mathbf{a} = [1, 2, 3] and b=[4,5,6]\mathbf{b} = [4, 5, 6]:

a⋅b=1⋅4+2⋅5+3⋅6=32 \mathbf{a} \cdot \mathbf{b} = 1 \cdot 4 + 2 \cdot 5 + 3 \cdot 6 = 32

In machine learning, the dot product can be used to measure similarity between vectors, such as when comparing embeddings.

Magnitude

The magnitude (or length) of a vector measures its size.

It’s calculated as:

∥a∥=∑i=1nai2 \|\mathbf{a}\| = \sqrt{\sum_{i=1}^{n} a_i^2}

For a=[3,4]\mathbf{a} = [3, 4]:

∥a∥=32+42=5 \|\mathbf{a}\| = \sqrt{3^2 + 4^2} = 5

Magnitudes tell us how large something is.

For the vectors we encounter in ML, large differences in magnitudes between features can bias the learning process, which is why techniques like feature scaling and normalization are commonly applied.

Unit Vectors

A unit vector has a magnitude of 1 and points in a specific direction.

To convert a vector to a unit vector:

a^=a∥a∥ \mathbf{\hat{a}} = \frac{\mathbf{a}}{\|\mathbf{a}\|}

For a=[3,4]\mathbf{a} = [3, 4], its unit vector is:

a^=[3,4]5=[0.6,0.8] \mathbf{\hat{a}} = \frac{[3, 4]}{5} = [0.6, 0.8]

Scaling vectors into unit vectors can be used to normalize features like word embeddings.

Example: Cosine Similarity

Cosine similarity measures the cosine of the angle between two vectors, ranging from -1 (pointing in opposite directions) to 1 (pointing in the same direction). It’s commonly used to determine similarity between two embeddings.

It’s the dot product of a\mathbf{a} and b\mathbf{b}, normalized by the product of their magnitudes:

cosine similarity=a⋅b∥a∥∥b∥ \text{cosine similarity} = \frac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\| \|\mathbf{b}\|}

Let’s calculate the cosine similarity between two hypothetical word embeddings:

  • “apple” embedding aa = [0.2, 0.5, 0.3]
  • “banana” embedding bb = [0.1, 0.4, 0.2]

Step 1: Calculate dot product

a⋅b=(0.2×0.1)+(0.5×0.4)+(0.3×0.2)=0.02+0.20+0.06=0.28 \mathbf{a} \cdot \mathbf{b} = (0.2 \times 0.1) + (0.5 \times 0.4) + (0.3 \times 0.2) = 0.02 + 0.20 + 0.06 = 0.28

Step 2: Calculate magnitudes

∥a∥=0.22+0.52+0.32=0.38=0.616 \|\mathbf{a}\| = \sqrt{0.2^2 + 0.5^2 + 0.3^2} = \sqrt{0.38} = 0.616
∥b∥=0.12+0.42+0.22=0.21=0.458 \|\mathbf{b}\| = \sqrt{0.1^2 + 0.4^2 + 0.2^2} = \sqrt{0.21} = 0.458

Step 3: Calculate final similarity

cosine similarity=0.280.616×0.458=0.991 \text{cosine similarity} = \frac{0.28}{0.616 \times 0.458} = 0.991

The high cosine similarity value (close to 1) indicates these embeddings point in very similar directions, suggesting semantic similarity between the words they represent.

Linear Algebra ML Applications
Some linear algebra applications in machine learning.

Basic Matrix Operations

Matrices generalize vectors to two dimensions.

In ML, they are used to represent data like:

  • Image data for a single color shade (e.g., a grayscale image as a matrix where each element represents pixel intensity)
  • Features (e.g., a dataset of houses where each row represents a house, and columns are price, square footage, and the number of bedrooms)
  • Weights in a single neural network layer (e.g., a 9×16 matrix - 9 rows and 16 columns—representing weights between a layer with 16 neurons and the next layer with 9 neurons)

Matrices in mathematics and Python are indexed by row first and then column[1]. e.g. A∈R5×8\mathbf{A} \in \mathbb{R}^{5 \times 8} denotes a 5 row by 8 column matrix, and A3,4\mathbf{A}_{3,4} refers to the element in the 3rd row and 4th column of that matrix . In NumPy, if we call this matrix a, then a.shape would return (5,8).

Matrix Transpose

The transpose of a matrix swaps its rows and columns.

For example, given A\mathbf{A}:

A=[1234],AT=[1324] \mathbf{A} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}, \mathbf{A}^T = \begin{bmatrix} 1 & 3 \\ 2 & 4 \end{bmatrix}

This operation is used in deep learning when computing gradients for backpropagation.

Matrix Inverse

The inverse of a matrix A\mathbf{A} is denoted as A−1\mathbf{A}^{-1} and has the property that when multiplied with the original matrix, it yields the identity matrix:

AA−1=A−1A=I \mathbf{A}\mathbf{A}^{-1} = \mathbf{A}^{-1}\mathbf{A} = \mathbf{I}

Given a 2x2 matrix:

A=[abcd],A−1=1ad−bc[d−b−ca] \mathbf{A} = \begin{bmatrix} a & b \\ c & d \end{bmatrix}, \mathbf{A}^{-1} = \frac{1}{ad-bc} \begin{bmatrix} d & -b \\ -c & a \end{bmatrix}

For example, if:

A=[2113] \mathbf{A} = \begin{bmatrix} 2 & 1 \\ 1 & 3 \end{bmatrix}

Then:

A−1=1(2×3)−(1×1)[3−1−12]=[0.6−0.2−0.20.4] \mathbf{A}^{-1} = \frac{1}{(2 \times 3) - (1 \times 1)} \begin{bmatrix} 3 & -1 \\ -1 & 2 \end{bmatrix} = \begin{bmatrix} 0.6 & -0.2 \\ -0.2 & 0.4 \end{bmatrix}

This satisfies the definition of an inverse matrix:

AA−1=[2113][0.6−0.2−0.20.4]=[1001]=I \mathbf{A}\mathbf{A}^{-1} = \begin{bmatrix} 2 & 1 \\ 1 & 3 \end{bmatrix} \begin{bmatrix} 0.6 & -0.2 \\ -0.2 & 0.4 \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} = \mathbf{I}

I’m sure you can see how this evaluation works, even though we haven’t explicitly talked about how matrix multiplication works. That’s because it’s actually a type of linear transformation which we’re holding out on until the next lesson.

Note that not all matrices have inverses. A matrix must be square and have a non-zero determinant to be invertible. Have a look at the 2x2 example above, and pick out the term that isn’t allowed to be zero. It’s the denominator: ad−bcad-bc. That is the determinant of a 2x2 matrix.

We’ll see the matrix inverse appear again in the next lesson when we use linear algebra to solve for OLS regression coefficients.

Matrix Multiplication

Matrix multiplication typically means taking a series of dot products.

For two matrices A\mathbf{A} and B\mathbf{B}, the matrix multiplication is calculated by summing the row-by-column products.

The resulting matrix has dimensions (m × p) when multiplying an m × n matrix by an n × p matrix.

For two matrices A\mathbf{A} (m × n) and B\mathbf{B} (n × p), we define the matrix multiplication C\mathbf{C} as:

C=AB \mathbf{C} = \mathbf{A} \mathbf{B}

The values of C\mathbf{C} are given by:

(C)ij=∑k=1nAikBkj (\mathbf{C})_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}

where:

  • ii is the row index (1 to m)
  • jj is the column index (1 to p)
  • nn is the number of columns in A (which equals the number of rows in B)

The number of columns in A\mathbf{A} must match the number of rows in B\mathbf{B} for matrix multiplication to be valid.

Example

Let:

A=[123456] \mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix}

and

B=[789101112131415161718] \mathbf{B} = \begin{bmatrix} 7 & 8 & 9 & 10 \\ 11 & 12 & 13 & 14 \\ 15 & 16 & 17 & 18 \end{bmatrix}

We want to calculate the matrix multiplication:

C=AB \mathbf{C} = \mathbf{A} \mathbf{B}

where:

  • AA is a 2 x 3 matrix (2 rows, 3 columns)
  • BB is a 3 x 4 matrix (3 rows, 4 columns)

The resulting matrix C\mathbf{C} will have dimensions 2 x 4 (matching the number of rows in A\mathbf{A} and the number of columns in B\mathbf{B}).

First row of C\mathbf{C}

  • C11=(1×7)+(2×11)+(3×15)=7+22+45=74C_{11} = (1 \times 7) + (2 \times 11) + (3 \times 15) = 7 + 22 + 45 = 74
  • C12=(1×8)+(2×12)+(3×16)=8+24+48=80C_{12} = (1 \times 8) + (2 \times 12) + (3 \times 16) = 8 + 24 + 48 = 80
  • C13=(1×9)+(2×13)+(3×17)=9+26+51=86C_{13} = (1 \times 9) + (2 \times 13) + (3 \times 17) = 9 + 26 + 51 = 86
  • C14=(1×10)+(2×14)+(3×18)=10+28+54=92C_{14} = (1 \times 10) + (2 \times 14) + (3 \times 18) = 10 + 28 + 54 = 92

Second row of C\mathbf{C}

  • C21=(4×7)+(5×11)+(6×15)=28+55+90=173C_{21} = (4 \times 7) + (5 \times 11) + (6 \times 15) = 28 + 55 + 90 = 173
  • C22=(4×8)+(5×12)+(6×16)=32+60+96=188C_{22} = (4 \times 8) + (5 \times 12) + (6 \times 16) = 32 + 60 + 96 = 188
  • C23=(4×9)+(5×13)+(6×17)=36+65+102=203C_{23} = (4 \times 9) + (5 \times 13) + (6 \times 17) = 36 + 65 + 102 = 203
  • C24=(4×10)+(5×14)+(6×18)=40+70+108=218C_{24} = (4 \times 10) + (5 \times 14) + (6 \times 18) = 40 + 70 + 108 = 218

Thus we get the final result:

C=[74808692173188203218] \mathbf{C} = \begin{bmatrix} 74 & 80 & 86 & 92 \\ 173 & 188 & 203 & 218 \end{bmatrix}

In ML, matrix multiplications like this are used all over the place, such as:

  • Computing loss functions
  • Calculating correlation between feature matrices
  • Attention mechanisms in transformers

Example: CNN sliding window

Let’s look at a simple example of how matrix multiplication is used in a CNN (Convolutional Neural Network with a sliding window.

A CNN applies a small filter (kernel) to an input matrix (image) by sliding it over and performing element-wise multiplication followed by summation.

For example, consider a 4×4 input image and a 2×2 kernel/filter:

Input image:

I=[12345678910111213141516] \mathbf{I} = \begin{bmatrix} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 \end{bmatrix}

Kernel:

K=[1001] \mathbf{K} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}

The convolution operation slides this kernel across the image. For each position, we:

  1. Take the region under the kernel
  2. Multiply element-wise
  3. Sum the results

For the top-left position:

[1256]⊙[1001]=(1×1)+(2×0)+(5×0)+(6×1)=7 \begin{bmatrix} 1 & 2 \\ 5 & 6 \end{bmatrix} \odot \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} = (1 \times 1) + (2 \times 0) + (5 \times 0) + (6 \times 1) = 7

Sliding the kernel produces a 3x3 output:

Output=[789111213151617] \text{Output} = \begin{bmatrix} 7 & 8 & 9 \\ 11 & 12 & 13 \\ 15 & 16 & 17 \end{bmatrix}

This is how CNNs detect features like edges, textures, and patterns in images through learned kernel values.

Conclusion

See? I told you this would be fun. And we’re just getting warmed up…

Key Takeaways

🔢 Vectors are ordered lists of numbers that can represent data points, features, or directions.

🎯 The dot product combines two vectors into a scalar, useful for measuring similarity.

📏 Vector magnitude measures size/length, important for normalization.

➡️ Unit vectors have magnitude 1 and preserve direction.

📐 Cosine similarity measures the angle between vectors, ranging from -1 to 1.

🖼️ Matrices extend vectors to 2D and can represent images, features, or neural network weights.

🔄 Matrix operations like transpose, inverse, and multiplication are fundamental to ML.

🧠 CNNs use matrix operations with sliding windows to detect features in images.

Next: Linear Transformations

In the next lesson, we’ll explore linear transformations, learning how data points move and change in space.

Footnotes:


  1. I came up with a mnemonic to help me remember matrix indexation order: roman columns. See how row comes before column? Another way this can make sense is considering how you would represent tabular data in a basic python object, i.e. obj = [["1st value for col 1", "1st value for col 1", ...], ["2nd value for col 1", "2nd value for col 2", ...], ...]. Notice that you would access a value in this way: obj[row_index][column_index] ↩︎

Comments (0)

No comments yet.