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
Every single input to a Machine Learning model — text, photos, audio, tables — MUST become a Tensor first!
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.
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.
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.
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?
- 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.
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
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.
In machine learning and mathematics, we classify arrays of numbers by how many indices (axes) you need to pinpoint a single number inside them:
- Scalar (0D — 0 axes): Just a single plain number, written in lowercase italic like or .
- Examples: A house's price ($350,000), a model's loss value (), a learning rate (), or an LLM's temperature ().
- Vector (1D — 1 axis): An ordered list of numbers, written in bold lowercase like . You need 1 index () to grab an element.
- By convention in Linear Algebra, a vector is written as a column vector:
- Here simply means "a list of 3 real numbers". In general, means "a vector with real entries".
- Writing (with a transpose ) turns a column into a row so it fits neatly inside text!
- Matrix (2D — 2 axes): A rectangular grid of numbers with rows and columns, written in bold uppercase like . You need 2 indices () to locate an entry: row first, column second ("Row before Column — remember RC Cola!").
- Looking at row 2, column 3 (1-based math indexing): .
- (Watch out: Python/NumPy uses 0-based indexing, so
A[1, 2] == 7!)
- Tensor (3D or higher — 3+ axes): A multi-dimensional stack of matrices!
- 3D Tensor: A single color photo of height , width , and 3 color channels (Red, Green, Blue) has shape .
- 4D Tensor: A mini-batch of color images fed into a CNN has shape .
Worked Example 1 — Reading Shapes & Entries by Hand
Consider the matrix:
- How many rows and columns? 2 rows and 4 columns , shape
(2, 4). - What is (math 1-based)? Row 1, Column 3 = . (In Python:
M[0, 2] == 30.) - What is ? Row 2, Column 4 = . (In Python:
M[1, 3] == 35.) - What is the transpose ? Flip rows into columns! has shape :
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)!
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)
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!
Every great mathematician and ML engineer switches smoothly between two mental pictures of a vector :
- 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 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:
Geometrically (Tip-to-Tail Rule): Walk along arrow , then start arrow at the tip of . The shortcut arrow from the origin straight to the final tip is !
Operation B: Scalar Multiplication (Stretch, Shrink, or Flip!)
Multiplying a vector by a plain number multiplies every single entry by :
- If : stretches the arrow longer in the same direction (e.g., is twice as long).
- If : shrinks the arrow shorter (e.g., is half as long).
- If : reverses the arrow into the opposite direction (e.g., ).
- If : collapses any vector to the zero vector .
Worked Example 2 — Basic Vector Arithmetic by Hand
Let and . Compute:
- Addition :
- Subtraction : (Geometrically, the arrow pointing from to !)
- Scalar multiplication and :
The #1 building block of EVERY linear regression and neural network layer!
How much to stretch, shrink, or flip each vector — literally the 'weights' trained by gradient descent!
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
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:
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 and :
- Every Linear Regression model is literally a linear combination of your feature columns weighted by learned parameters :
- Every Transformer Attention output is a weighted linear combination of Value vectors: !
Worked Example 3 — Reaching a Target Point with a Linear Combination
Suppose your two building-block vectors are and . Can we combine them to reach the target ? We want scalars such that: Reading the top and bottom rows gives two tiny equations:
- Row 1:
- Row 2: Substitute into Row 2: Check: ! (You will test this exact puzzle visually in the Interactive Lab right below!)
Special Matrices You Must Recognize on Sight
| Matrix Name | Example () | Why It Matters |
|---|---|---|
| Zero Matrix | All entries | Additive identity () |
| Identity Matrix | s on main diagonal, s elsewhere | Multiplicative identity (); used in Ridge () & skip connections |
| Diagonal Matrix | Non-zero only on diagonal | Scales each axis independently; just takes ! |
| Symmetric Matrix () | Covariance matrices, Hessians, kernel matrices — always have real eigenvalues! |
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?
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
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
- Tabular ML (CSV / Pandas DataFrame): You have 50,000 customers and 12 features (age, spend, clicks...).
- Object: 2D Design Matrix , shape
(50000, 12). - Row
X[i]is customer 's feature vector . - Column
X[:, j]is feature across all 50,000 customers.
- Object: 2D Design Matrix , shape
- Computer Vision (CNN / ViT): A mini-batch of 64 RGB images of size .
- Object: 4D Tensor of shape
(64, 3, 224, 224)in PyTorch (Channel-First:(B, C, H, W)). - Total scalars inside this single batch: floats (~38.5 MB in
float32!).
- Object: 4D Tensor of shape
- Large Language Models (GPT / Llama / Gemini): A batch of prompts, each tokens long, where each token is an embedding vector of size .
- Object: 3D Tensor of shape
(8, 512, 4096).
- Object: 3D Tensor of shape
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!
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.
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)