S30 Logo
S30 AI Labwww.thes30.com
Back
#4

Linear Algebra for ML

Easy📐 Math for MLW2 D1

Before You Start

Required knowledge
NumPy arrays, indexing, and basic algebra.
Libraries used
NumPy
Dataset and source
Vectors and matrices defined or generated in the notebook; no external dataset.
Expected output
Dot products, projections, least-squares solutions, and PCA using SVD.

Linear Algebra for ML — Theory & Concepts

Read this before attempting the exercises. Linear algebra is the language of ML. Every model, from linear regression to transformers, is built on matrix operations.


1. Vectors & Matrices

A vector is an ordered list of numbers. A matrix is a 2D grid.

import numpy as np

v = np.array([1, 2, 3])           # vector, shape (3,)
M = np.array([[1, 2], [3, 4]])    # matrix, shape (2, 2)

Key operations:

# Dot product: measures similarity
np.dot(a, b)        # scalar: sum of element-wise products

# Matrix multiply: transforms vectors
M @ v               # shape (2,2) @ (2,) → (2,)

# Transpose: swap rows and columns
M.T                  # shape (2,2) → (2,2)

ML Connection: In a neural network layer, output = X @ W + b is a matrix multiply followed by a bias addition.


2. Norms — Measuring Size

v = np.array([3, 4])

# L2 norm (Euclidean distance)
np.linalg.norm(v)        # √(9+16) = 5.0

# L1 norm (Manhattan distance)
np.linalg.norm(v, ord=1) # |3|+|4| = 7

# Frobenius norm (for matrices)
np.linalg.norm(M, 'fro')
NormFormulaML Use
L2√(Σxᵢ²)Ridge regularization, Euclidean distance
L1Σxᵢ
L∞max(xᵢ

3. Matrix Decompositions

Eigendecomposition

Every square matrix A can be decomposed as A = QΛQ⁻¹ where:

  • ●Q = matrix of eigenvectors (directions)
  • ●Λ = diagonal matrix of eigenvalues (magnitudes)
eigenvalues, eigenvectors = np.linalg.eig(A)

ML Use: PCA uses eigendecomposition of the covariance matrix to find principal components.

SVD (Singular Value Decomposition)

Works for any matrix (not just square): A = UΣVᵀ

U, S, Vt = np.linalg.svd(A)

ML Use: Dimensionality reduction, matrix completion (recommender systems), low-rank approximation.


4. Positive Semi-Definite (PSD) Matrices

A matrix A is PSD if vᵀAv ≥ 0 for all vectors v.

Why it matters:

  • ●Covariance matrices are always PSD
  • ●Kernel matrices must be PSD
  • ●Gram matrix AᵀA is always PSD (because vᵀAᵀAv = ‖Av‖² ≥ 0)
# Check PSD: all eigenvalues ≥ 0
eigenvalues = np.linalg.eigvalsh(A)  # eigvalsh for symmetric matrices
is_psd = np.all(eigenvalues >= -1e-10)

5. Key Identities for Interviews

IdentityWhy It Matters
(AB)ᵀ = BᵀAᵀTranspose reverses order
(AB)⁻¹ = B⁻¹A⁻¹Inverse reverses order
det(AB) = det(A)·det(B)Determinant is multiplicative
rank(A) ≤ min(m, n)Rank can't exceed smaller dimension
AᵀA is PSDGram matrices are always PSD

6. Linear Algebra in ML Models

Linear Regression:  w* = (XᵀX)⁻¹Xᵀy     < normal equation
PCA:                Cov = XᵀX/(n-1)       < eigendecompose this
Neural Network:     h = ReLU(X @ W + b)    < matrix multiply
Attention:          softmax(QKᵀ/√d) @ V    < three matrix multiplies

Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!

LU Decomposition (Visual)

LU Decomposition Overview

Use LU to solve Ax=b via forward/back substitution instead of explicit matrix inverse.

SVD Visual

Singular Value Decomposition (SVD)

Use SVD to understand low-rank structure and dimensionality reduction (M = U\Sigma V^T).

Ready to practice?

Python 3 — Notebook
0/6 solvedSubstack Notes
1
Dataset & Setup

Linear Algebra for ML — FAANG-Level Lab

Goal: Build shape intuition + compute core linear algebra objects used in ML.

Outcome: You can implement least squares, projections, eigen decomposition intuition, and SVD-based PCA.

Loading editor...
1

Vectors, Dot Product, Norms

2
Implement dot + L2 norm (no np.linalg.norm)
2

Section 1 — Vectors, Dot Product, Norms

Task 1.1: Implement dot + L2 norm (no np.linalg.norm)

  • ●dot(x,y) = sum(x_i * y_i)
  • ●||x||_2 = sqrt(dot(x,x))

Explain: What does dot product measure geometrically?

Explain: What does dot product measure geometrically?
Loading editor...
2

Matrix Multiplication + Shapes

3
Validate shapes and compute A@B
1

Section 2 — Matrix Multiplication + Shapes

Task 2.1: Validate shapes and compute A@B

Given A (n,d) and B (d,k) compute C (n,k).

FAANG gotcha: Many bugs are shape bugs. Always assert shapes.

Loading editor...
3

Projections (Least Squares Intuition)

4
Project vector v onto vector u
1

Section 3 — Projections (Least Squares Intuition)

Task 3.1: Project vector v onto vector u

proj_u(v) = (u^T v / u^T u) * u

  • ●Use your dot()

Explain: Why does projection show up in linear regression?

Explain: Why does projection show up in linear regression?
Loading editor...
4

Least Squares (Closed Form)

5
Solve min_w ||Xw - y||^2
1

Section 4 — Least Squares (Closed Form)

Task 4.1: Solve min_w ||Xw - y||^2

Use normal equation: w = (X^T X)^{-1} X^T y

  • ●Use np.linalg.solve (more stable than explicit inverse)

FAANG gotcha: Don’t compute matrix inverse unless you must.

LU Decomposition Overview

Loading editor...
5

Eigenvalues & SVD Intuition

6
PCA via SVD
1

Section 5 — Eigenvalues & SVD Intuition

Task 5.1: PCA via SVD

Steps:

  1. ●Center X
  2. ●Compute SVD: X = U S V^T
  3. ●Take top-k components from V
  • ●U, S, Vt = np.linalg.svd(X_centered, full_matrices=False)

Explain: Why does SVD show up in embeddings and dimensionality reduction?

Eigen Decomposition Overview

Singular Value Decomposition (SVD)

Explain: Why does SVD show up in embeddings and dimensionality reduction?
Loading editor...

Need help? Share feedback