Chapter 1 of 10 · ~20 min read & lab+50 XP
Chapter 1 · Linear Algebra

Scalars, Vectors, Matrices & Tensors — The Building Blocks

Start from zero: numbers, arrows, coordinates, grids, vector arithmetic, linear combinations, and how every ML dataset lives in Linear Algebra

Why ML Engineers & Data Scientists Actually Need This

Every single input to a Machine Learning model — text, photos, audio, tables — MUST become a Tensor first!

ML / AI Engineer

90% of beginner PyTorch bugs are tensor shape mismatches (e.g., (B, T, D) vs (T, B, D)). Knowing tensor ranks lets you read GPU memory and model architectures fluently.

Data Scientist

Every Pandas DataFrame of N customers × D features IS a 2D matrix X ∈ ℝ^(N×D) — vectorizing operations in NumPy runs 100× faster than Python for-loops.

Interview & Debug Edge

Interviewers routinely test whether you can reason about tensor shapes (e.g., batching images (B, C, H, W) or LLM embeddings (B, seq_len, d_model)) without running code.

Step 0 · Test Your Gut Before Any Math!

You feed a batch of 32 color photos (each 224×224 pixels with Red, Green, Blue channels) into a PyTorch vision model. What is the shape of that single tensor?

What You Will Master in This Chapter
  • Understand the exact difference between a 0D Scalar, 1D Vector, 2D Matrix, and N-D Tensor — and read their shapes effortlessly.
  • Read and write standard mathematical notation (x ∈ ℝ^n, v_i, A_{ij}, Aᵀ) with zero intimidation.
  • Perform vector addition, subtraction, scalar multiplication, and linear combinations both by hand and geometrically (tip-to-tail).
  • Map real-world Data Science tables, RGB images, and LLM token sequences directly into NumPy arrays and PyTorch tensors.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“R-n (n-dimensional real space)”
Plain-English Meaning
Just the set of all lists containing n decimal numbers!
Everyday Example
A house profile [sqft=2000, beds=3, age=12] lives in ℝ³.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

If you have ever looked at a spreadsheet, a GPS coordinate, or a photo on your phone, you have already used Linear Algebra! Linear algebra is simply the language of organized arrays of numbers and the geometric rules for moving, stretching, and combining them. Whether you are a college student seeing vectors for the first time or an engineer preparing for ML interviews, mastering these 4 building blocks makes everything that follows click effortlessly.

1. The Four Fundamental Objects: Scalar, Vector, Matrix, Tensor

Everyday Story First (Zero Math Yet!)

Look at your phone screen right now. To your eyes, a photo of a dog is fur, ears, and sky. To an AI model, there is NO dog — there is only a giant grid of numbers! Each tiny dot (pixel) is a 3-number list [Red, Green, Blue]. A whole photo is a 3D block of pixels. And a 10-second video is a 4D block! That's literally all Scalars, Vectors, Matrices, and Tensors are: nested lists of numbers.

0D · SCALAR42shape: ()Loss, LR η, Temp1D · VECTORv₁3.0v₂2.0v₃-1.0shape: (3,)1 Row / Embedding2D · MATRIX Acols (j = 1..3)1420573-12A[2,3] = 7 · shape: (3, 3)Dataset / Weights W3D+ · TENSORR / G / Bshape: (H, W, 3)Images, Video, LLM Batch
Figure 1.1 — The Linear Algebra Hierarchy: every ML object is a 0D scalar, 1D vector, 2D matrix, or N-D tensor.

In machine learning and mathematics, we classify arrays of numbers by how many indices (axes) you need to pinpoint a single number inside them:

  1. Scalar (0D — 0 axes): Just a single plain number, written in lowercase italic like x=42x = 42 or η=0.001\eta = 0.001.
    • Examples: A house's price ($350,000), a model's loss value (0.420.42), a learning rate (η=0.01\eta = 0.01), or an LLM's temperature (T=0.7T = 0.7).
  2. Vector (1D — 1 axis): An ordered list of numbers, written in bold lowercase like v∈R3\mathbf{v} \in \mathbb{R}^3. You need 1 index (viv_i) to grab an element.
    • By convention in Linear Algebra, a vector is written as a column vector: v=[32−1]∈R3\mathbf{v} = \begin{bmatrix} 3 \\ 2 \\ -1 \end{bmatrix} \in \mathbb{R}^3
    • Here R3\mathbb{R}^3 simply means "a list of 3 real numbers". In general, x∈Rd\mathbf{x} \in \mathbb{R}^d means "a vector with dd real entries".
    • Writing vT=[3,2,−1]\mathbf{v}^T = [3, 2, -1] (with a transpose TT) turns a column into a row so it fits neatly inside text!
  3. Matrix (2D — 2 axes): A rectangular grid of numbers with mm rows and nn columns, written in bold uppercase like A∈Rm×nA \in \mathbb{R}^{m \times n}. You need 2 indices (AijA_{ij}) to locate an entry: row ii first, column jj second ("Row before Column — remember RC Cola!"). A=[1420573−12]∈R3×3A = \begin{bmatrix} 1 & 4 & 2 \\ 0 & 5 & 7 \\ 3 & -1 & 2 \end{bmatrix} \in \mathbb{R}^{3 \times 3}
    • Looking at row 2, column 3 (1-based math indexing): A2,3=7A_{2,3} = 7.
    • (Watch out: Python/NumPy uses 0-based indexing, so A[1, 2] == 7!)
  4. Tensor (3D or higher — 3+ axes): A multi-dimensional stack of matrices!
    • 3D Tensor: A single color photo of height HH, width WW, and 3 color channels (Red, Green, Blue) has shape (H,W,3)(H, W, 3).
    • 4D Tensor: A mini-batch of B=32B = 32 color images fed into a CNN has shape (32,3,224,224)(32, 3, 224, 224).

Worked Example 1 — Reading Shapes & Entries by Hand

Consider the matrix: M=[102030405152535]M = \begin{bmatrix} 10 & 20 & 30 & 40 \\ 5 & 15 & 25 & 35 \end{bmatrix}

  • How many rows and columns? 2 rows and 4 columns   ⟹  M∈R2×4\implies M \in \mathbb{R}^{2 \times 4}, shape (2, 4).
  • What is M1,3M_{1,3} (math 1-based)? Row 1, Column 3 = 3030. (In Python: M[0, 2] == 30.)
  • What is M2,4M_{2,4}? Row 2, Column 4 = 3535. (In Python: M[1, 3] == 35.)
  • What is the transpose MTM^T? Flip rows into columns! MTM^T has shape (4×2)(4 \times 2): MT=[105201530254035]M^T = \begin{bmatrix} 10 & 5 \\ 20 & 15 \\ 30 & 25 \\ 40 & 35 \end{bmatrix}
Hands-On Mini-Lab · Every Pixel in an AI Image Is Literally a 3D Vector!

Slide Red, Green, and Blue below. Computers don't see “sky blue” — they store a 1D vector of 3 numbers, and a 224×224 photo is simply a 3D tensor of shape (224, 224, 3)!

v = [56, 189, 248]
Normalized: [0.22, 0.74, 0.97]
1 pixel → shape (3,) · 32 photos → shape (32, 224, 224, 3)
Try It Yourself

Given B = [[2, -3, 8], [4, 0, -1]], what is the shape of B, what is B_{2,1} (math 1-based), and what is the shape of Bᵀ?

2. Two Ways to Think About a Vector (Numbers vs. Geometry)

Everyday Story First (Zero Math Yet!)

Imagine walking 3 blocks East and 1 block North (v = [3, 1]), and then walking 1 block East and 2 blocks North (w = [1, 2]). Where do you end up? Simply add East-with-East and North-with-North: [4, 3]! That tip-to-tail arrow walk is vector addition — and multiplying by 2 simply walks twice as far in the exact same direction!

Vector Addition: u(2, 1) + v(1, 3) = w(3, 4)u = (2, 1)+ v (1, 3)u+v = (3, 4)Scalar Scaling: Stretch (2u), Shrink (0.5u), Flip (-u)2u = (4, 2)u = (2, 1)-u = (-2, -1)Every scalar multiple α·u stays along the exact same line (span)!
Figure 1.2 — Geometric Vector Operations: tip-to-tail addition (parallelogram law) and scalar stretching/flipping.

Every great mathematician and ML engineer switches smoothly between two mental pictures of a vector u=[21]\mathbf{u} = \begin{bmatrix} 2 \\ 1 \end{bmatrix}:

  • The Computer Science / Data Picture: An ordered list of numbers [2, 1] — e.g., [hours_studied=2, cups_of_coffee=1].
  • The Physics / Geometry Picture: An arrow starting at the origin (0,0)(0, 0) and pointing 2 units right and 1 unit up.

Operation A: Vector Addition & Subtraction (Component-by-Component!)

You can only add or subtract two vectors if they have the exact same length (dimension). Simply add matching coordinates:

u+v=[u1u2]+[v1v2]=[u1+v1u2+v2]\mathbf{u} + \mathbf{v} = \begin{bmatrix} u_1 \\ u_2 \end{bmatrix} + \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} = \begin{bmatrix} u_1 + v_1 \\ u_2 + v_2 \end{bmatrix}

Geometrically (Tip-to-Tail Rule): Walk along arrow u\mathbf{u}, then start arrow v\mathbf{v} at the tip of u\mathbf{u}. The shortcut arrow from the origin straight to the final tip is u+v\mathbf{u} + \mathbf{v}!

Operation B: Scalar Multiplication (Stretch, Shrink, or Flip!)

Multiplying a vector u\mathbf{u} by a plain number α\alpha multiplies every single entry by α\alpha:

αu=[αu1αu2]\alpha \mathbf{u} = \begin{bmatrix} \alpha u_1 \\ \alpha u_2 \end{bmatrix}

  • If α>1\alpha > 1: stretches the arrow longer in the same direction (e.g., 2u2\mathbf{u} is twice as long).
  • If 0<α<10 < \alpha < 1: shrinks the arrow shorter (e.g., 0.5u0.5\mathbf{u} is half as long).
  • If α<0\alpha < 0: reverses the arrow 180∘180^\circ into the opposite direction (e.g., −u-\mathbf{u}).
  • If α=0\alpha = 0: collapses any vector to the zero vector 0=[0,0]T\mathbf{0} = [0, 0]^T.

Worked Example 2 — Basic Vector Arithmetic by Hand

Let u=[23−1]\mathbf{u} = \begin{bmatrix} 2 \\ 3 \\ -1 \end{bmatrix} and v=[1−45]\mathbf{v} = \begin{bmatrix} 1 \\ -4 \\ 5 \end{bmatrix}. Compute:

  1. Addition u+v\mathbf{u} + \mathbf{v}: u+v=[2+13+(−4)−1+5]=[3−14]\mathbf{u} + \mathbf{v} = \begin{bmatrix} 2 + 1 \\ 3 + (-4) \\ -1 + 5 \end{bmatrix} = \begin{bmatrix} 3 \\ -1 \\ 4 \end{bmatrix}
  2. Subtraction u−v\mathbf{u} - \mathbf{v}: (Geometrically, the arrow pointing from v\mathbf{v} to u\mathbf{u}!) u−v=[2−13−(−4)−1−5]=[17−6]\mathbf{u} - \mathbf{v} = \begin{bmatrix} 2 - 1 \\ 3 - (-4) \\ -1 - 5 \end{bmatrix} = \begin{bmatrix} 1 \\ 7 \\ -6 \end{bmatrix}
  3. Scalar multiplication 3u3\mathbf{u} and −2v-2\mathbf{v}: 3u=[69−3],−2v=[−28−10]3\mathbf{u} = \begin{bmatrix} 6 \\ 9 \\ -3 \end{bmatrix}, \qquad -2\mathbf{v} = \begin{bmatrix} -2 \\ 8 \\ -10 \end{bmatrix}
Formula Anatomy · Click Any Colored Piece to Decode It
Linear Combination: y = c₁·v₁ + c₂·v₂

The #1 building block of EVERY linear regression and neural network layer!

Scalar Weights (Knobs the AI Learns!)

How much to stretch, shrink, or flip each vector — literally the 'weights' trained by gradient descent!

In our example: 2× vector v₁ plus (−1)× vector v₂
Put it together with real numbers: Every word embedding blend (like King − Man + Woman ≈ Queen!) is literally a linear combination of vectors!
Try It Yourself

Let a = [4, -2]ᵀ and b = [-1, 5]ᵀ. Compute 2a + 3b and a - b by hand.

3. Linear Combinations — The Single Most Important Idea in Linear Algebra

Everyday Story First (Zero Math Yet!)

Open any CSV file at work: each row is one customer (a vector!), each column is one feature (Age, Spend, Clicks), and the whole table is a Matrix X of shape (N, D). Whenever you hear 'tensor' in PyTorch or TensorFlow, don't flinch — it's just a multi-dimensional NumPy array!

Put scalar multiplication and vector addition together and you get a linear combination:

w=α1v1+α2v2+⋯+αkvk\mathbf{w} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2 + \dots + \alpha_k \mathbf{v}_k

Why is this simple formula the heartbeat of all Linear Algebra and Machine Learning?

  • Every vector in 2D is a linear combination of the two standard unit axes i^=[10]\hat{i} = \begin{bmatrix}1\\0\end{bmatrix} and j^=[01]\hat{j} = \begin{bmatrix}0\\1\end{bmatrix}: [5−3]=5i^+(−3)j^\begin{bmatrix} 5 \\ -3 \end{bmatrix} = 5\hat{i} + (-3)\hat{j}
  • Every Linear Regression model is literally a linear combination of your feature columns weighted by learned parameters w1,w2,…,wdw_1, w_2, \dots, w_d: y^=w1x1+w2x2+⋯+wdxd+b1\hat{\mathbf{y}} = w_1 \mathbf{x}_1 + w_2 \mathbf{x}_2 + \dots + w_d \mathbf{x}_d + b\mathbf{1}
  • Every Transformer Attention output is a weighted linear combination of Value vectors: ∑jαjvj\sum_j \alpha_j \mathbf{v}_j!

Worked Example 3 — Reaching a Target Point with a Linear Combination

Suppose your two building-block vectors are u=[21]\mathbf{u} = \begin{bmatrix} 2 \\ 1 \end{bmatrix} and v=[−12]\mathbf{v} = \begin{bmatrix} -1 \\ 2 \end{bmatrix}. Can we combine them to reach the target w=[34]\mathbf{w} = \begin{bmatrix} 3 \\ 4 \end{bmatrix}? We want scalars α,β\alpha, \beta such that: α[21]+β[−12]=[34]\alpha \begin{bmatrix} 2 \\ 1 \end{bmatrix} + \beta \begin{bmatrix} -1 \\ 2 \end{bmatrix} = \begin{bmatrix} 3 \\ 4 \end{bmatrix} Reading the top and bottom rows gives two tiny equations:

  • Row 1: 2α−β=3  ⟹  β=2α−32\alpha - \beta = 3 \implies \beta = 2\alpha - 3
  • Row 2: α+2β=4\alpha + 2\beta = 4 Substitute β=2α−3\beta = 2\alpha - 3 into Row 2: α+2(2α−3)=4  ⟹  5α−6=4  ⟹  5α=10  ⟹  α=2,  β=1\alpha + 2(2\alpha - 3) = 4 \implies 5\alpha - 6 = 4 \implies 5\alpha = 10 \implies \mathbf{\alpha = 2},\; \mathbf{\beta = 1} Check: 2[21]+1[−12]=[4−12+2]=[34]2\begin{bmatrix}2\\1\end{bmatrix} + 1\begin{bmatrix}-1\\2\end{bmatrix} = \begin{bmatrix}4-1\\2+2\end{bmatrix} = \begin{bmatrix}3\\4\end{bmatrix}! (You will test this exact puzzle visually in the Interactive Lab right below!)

Special Matrices You Must Recognize on Sight

Matrix NameExample (3×33 \times 3)Why It Matters
Zero Matrix 0\mathbf{0}All entries 00Additive identity (A+0=AA + \mathbf{0} = A)
Identity Matrix InI_n11s on main diagonal, 00s elsewhereMultiplicative identity (AI=IA=AAI = IA = A); used in Ridge (XTX+λIX^T X + \lambda I) & skip connections
Diagonal Matrix DDNon-zero only on diagonal (i=j)(i = j)Scales each axis independently; D−1D^{-1} just takes 1/di1/d_i!
Symmetric Matrix (A=ATA = A^T)Aij=AjiA_{ij} = A_{ji}Covariance matrices, Hessians, kernel matrices — always have real eigenvalues!
Pause & Check · Quick Intuition Pulse

Pause & Check: An LLM processes a batch of B = 16 sentences, each T = 128 tokens long, where every token is an embedding vector of size D = 768. What is the tensor shape?

Try It Yourself

Is the matrix S = [[2, 5], [5, -1]] symmetric? What is I₂ (the 2×2 identity matrix)?

4. How Real-World Data Science, Vision & LLMs Map to Matrices & Tensors

Tabular Dataset → Design Matrix X ∈ ℝ^(N × D)UserAgeIncome($k)ClicksRow 1 (x⁽¹⁾)288514Row 2 (x⁽²⁾)3512031Row 3 (x⁽³⁾)22549LLM Prompt → Sequence Matrix E ∈ ℝ^(T × d_model)"The"→[ 0.12, -0.44, 0.81, … ]"cat"→[ 0.77, 0.63, -0.19, … ]"sat"→[-0.25, 0.18, 0.54, … ]Stacking B prompts creates a 3D batch tensor: (B, T, d_model)
Figure 1.3 — Real-World Data as Linear Algebra: tabular datasets become (N × D) matrices; RGB images become (H × W × 3) tensors.

Whenever you open a Jupyter notebook or PyTorch script, look at the .shape of your data — it immediately tells you the exact mathematical object:

Worked Example 4 — Reading Real ML Tensor Shapes

  1. Tabular ML (CSV / Pandas DataFrame): You have 50,000 customers and 12 features (age, spend, clicks...).
    • Object: 2D Design Matrix X∈R50000×12X \in \mathbb{R}^{50000 \times 12}, shape (50000, 12).
    • Row X[i] is customer ii's feature vector x(i)∈R12\mathbf{x}^{(i)} \in \mathbb{R}^{12}.
    • Column X[:, j] is feature jj across all 50,000 customers.
  2. Computer Vision (CNN / ViT): A mini-batch of 64 RGB images of size 224×224224 \times 224.
    • Object: 4D Tensor of shape (64, 3, 224, 224) in PyTorch (Channel-First: (B, C, H, W)).
    • Total scalars inside this single batch: 64×3×224×224=9,633,79264 \times 3 \times 224 \times 224 = 9{,}633{,}792 floats (~38.5 MB in float32!).
  3. Large Language Models (GPT / Llama / Gemini): A batch of B=8B = 8 prompts, each T=512T = 512 tokens long, where each token is an embedding vector of size dmodel=4096d_{\text{model}} = 4096.
    • Object: 3D Tensor of shape (8, 512, 4096).
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Because they are two views of the exact same object! Data Scientists love the list-of-numbers view ([Age=28, Income=95k]), while geometric intuition uses the arrow view (so you can visually see similarity as angles and predictions as shadows!). Switching effortlessly between both views is the #1 superpower of Linear Algebra!

Interactive Visual Lab
Lab Challenge: Drag scalars α and β until your linear combination w = αu + βv hits the glowing gold Target Star at (3, 4)!
★ Target (3, 4)w (1.5, 2.0)
Building blocks: u = (2, 1), v = (-1, 2)
Scalar α (scales u)α = 1.0
Scalar β (scales v)β = 0.5
w = (1.0)(2, 1) + (0.5)(-1, 2)
w = (1.5, 2.0)
Distance to Target (3, 4): 2.50
Geometric Takeaway: Scalars (0D), Vectors (1D), Matrices (2D), and Tensors (3D+) organize all data in AI. Vector addition (tip-to-tail) + scalar multiplication build linear combinations αu + βv — the core engine of every ML model.
Where This Powers Real ML, Deep Learning & GenAI

Every Tabular ML Dataset is a Design Matrix X

Rows represent observations (samples) and columns represent features. Almost every scikit-learn model expects X with shape (N_samples, N_features) and y with shape (N_samples,).

Linear Models are Linear Combinations

Linear regression, Logistic regression, and linear SVMs all compute w₁x₁ + w₂x₂ + … + w_dx_d + b — choosing scalar weights to combine features.

Word & Document Embeddings in GenAI

Modern LLMs map every subword token to a dense vector in ℝ^{4096}. Semantic arithmetic like vector('king') − vector('man') + vector('woman') ≈ vector('queen') is pure vector addition and subtraction!

Batched GPU Tensor Processing

GPUs achieve 100× speedups by stacking individual vectors into 2D/3D/4D tensors and executing the same arithmetic across thousands of cores simultaneously.

Production NumPy & PyTorch Code Patterns
import numpy as np

# 1. The 4 building blocks in NumPy
scalar = np.array(42.0)                                   # shape: (), ndim: 0
vec_u  = np.array([2.0, 1.0])                             # shape: (2,), ndim: 1
vec_v  = np.array([-1.0, 2.0])                            # shape: (2,), ndim: 1
mat_A  = np.array([[1.0, 4.0, 2.0],
                   [0.0, 5.0, 7.0]])                      # shape: (2, 3), ndim: 2
img_3d = np.zeros((28, 28, 3), dtype=np.float32)          # shape: (28, 28, 3), ndim: 3

# 2. Vector arithmetic & linear combinations (vectorized — no Python loops!)
w = 2.0 * vec_u + 1.0 * vec_v                             # array([3., 4.])

# 3. Indexing (0-based in Python!) & Transpose
entry_r2_c3 = mat_A[1, 2]                                 # 7.0 (math A_{2,3})
mat_AT = mat_A.T                                          # shape: (3, 2)

# 4. Special matrices
I3 = np.eye(3)                                            # 3x3 Identity matrix
D  = np.diag([2.0, 5.0, 9.0])                             # 3x3 Diagonal matrix

# 5. Row vector vs Column vector (crucial for matrix math!)
col_u = vec_u.reshape(-1, 1)                              # shape: (2, 1)
row_u = vec_u.reshape(1, -1)                              # shape: (1, 2)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Confusing 1D shape (3,) with 2D column (3, 1) or row (1, 3) in NumPy
Best Practice: A 1D array of shape (3,) is neither a row nor a column — calling `.T` on a 1D array does NOTHING! Always check `.shape` and use `.reshape(-1, 1)` or `[:, None]` when you need an explicit column vector.
Trap #2: Off-by-one indexing between math textbooks (1-based) and Python (0-based)
Best Practice: Math entry A_{2,3} (row 2, col 3) is `A[1, 2]` in Python/NumPy/PyTorch.
Trap #3: Writing Python `for` loops to add or scale vectors
Best Practice: Always use vectorized NumPy/PyTorch operations (`2 * u + v`); Python loops are 50–200× slower because they bypass compiled C/SIMD/GPU kernels.
Chapter Mastery Check (+50 XP)
Score: 0 / 5
1If u = [2, -1]ᵀ and v = [0, 3]ᵀ, what is the linear combination 3u + 2v?
2A matrix A has shape (4, 7). What is the shape of its transpose Aᵀ, and which Python index accesses math entry A_{3, 5}?
3In PyTorch, a mini-batch of 16 RGB images of size 128 × 128 is stored in Channel-First format. What is its tensor rank (ndim) and shape?
4Geometrically, what happens when you multiply any non-zero 2D vector u by the scalar α = -0.5?
5In NumPy, if x = np.array([1.0, 2.0, 3.0]) has shape (3,), what is the shape of x.T?

Apply What You Learned — Solve Matching Coding Problems