Table of Contents
- What is Vectorization?
- When to Use Vectorization
- Mathematical Foundations
- General Rules and Key Formulas
- Step-by-Step Algorithm
- Numerical Example 1 — Basic Dot Product (Single Neuron)
- Numerical Example 2 — Two-Layer Neural Network
- Comparing the Two Examples
- Geometric Intuition
- Advantages of Vectorization
- Limitations of Vectorization
- Complete Formula Reference
- Summary
What is Vectorization?
Vectorization is a technique where operations are performed on entire arrays (vectors or matrices) at once, replacing explicit loops with compact linear-algebra expressions that hardware can execute in parallel.
Vectorization finds the most efficient representation of a computation by expressing it as matrix and vector operations, retaining the same numerical result while dramatically reducing wall-clock time.
Core Idea
Given a dataset with observations and features, and a weight vector , the output can be computed as:
- Loop-based: iterate over each element one at a time
- Vectorized: compute as a single dot product
When to Use Vectorization
| Situation | Use Vectorization? |
|---|---|
| Large datasets () | ✅ Yes — essential |
| Deep / wide neural networks | ✅ Yes — required |
| GPU / TPU acceleration | ✅ Yes — only way to exploit hardware |
| Training loops with many iterations | ✅ Yes — orders-of-magnitude speedup |
| Single scalar calculation | ❌ No — overhead not worth it |
| Inherently sequential computation | ❌ No — e.g., RNN hidden state roll-out |
| Debugging step-by-step | ❌ No — loops are clearer to inspect |
Mathematical Foundations
Vector Representation
A single input sample with features is a column vector:
Dot Product (Single Neuron, No Bias)
Affine Transformation (Single Neuron with Bias)
Matrix Form — One Layer, Neurons, Samples
Where:
- — weight matrix ( neurons, inputs each)
- — input matrix ( features, samples)
- — bias vector
- — pre-activation output
Activation Function (Element-wise)
Common choices: (sigmoid), ,
General Rules and Key Formulas
Rule 1: Loop-Based vs. Vectorized
Loop (scalar):
Vectorized:
General Rule: Any summation over features or samples can be replaced by a single matrix/vector product.
Rule 2: Layer-Wise Forward Pass Formula
Key dimension rules (always verify these):
| Quantity | Shape |
|---|---|
where = number of neurons in layer , = number of training samples.
Rule 3: Speed Rule
| Method | Time Complexity | Hardware Utilisation | Speed |
|---|---|---|---|
| Loop | sequential | CPU only (1 core) | Slow 🐢 |
| Vectorization | parallel | CPU/GPU/TPU SIMD | Fast 🚀 |
Rule of thumb: On modern hardware, a vectorized matrix multiply on GPU can be – faster than the equivalent Python loop, depending on matrix size.
Rule 4: Gradient (Backprop) Vectorization
All three backprop formulas are matrix products — no loops required.
Rule 5: Memory and Numerical Considerations
| Consideration | Vectorized Approach | Loop Approach |
|---|---|---|
| Memory layout | Contiguous (cache-friendly) | Scattered (cache misses) |
| Numerical stability | Same as loop | Same as vectorized |
| Overflow risk | Use float32/float64 carefully |
Same |
| Batch processing | Handles samples at once | Requires outer loop |
Step-by-Step Algorithm
Algorithm: Vectorized Forward Pass — L-Layer Neural Network
Input: Input matrix X ∈ ℝ^(p×m), weights {W^[l], b^[l]} for l = 1…L
Output: Final activation A^[L] ∈ ℝ^(n^[L]×m)
Step 1: INITIALISE
A^[0] = X (shape: p × m)
Step 2: FOR EACH LAYER l = 1 to L:
Step 2a: LINEAR STEP
Z^[l] = W^[l] · A^[l-1] + b^[l]
(broadcasting adds b^[l] to every column)
Step 2b: ACTIVATION STEP
A^[l] = g^[l]( Z^[l] ) (element-wise)
Step 3: OUTPUT
Ŷ = A^[L]
Step 4: COMPUTE LOSS (e.g., cross-entropy for classification)
L = -(1/m) Σ_j [ y_j log(ŷ_j) + (1-y_j) log(1-ŷ_j) ]
Step 5: BACKPROP (vectorized)
For l = L down to 1:
dZ^[l] = dA^[l] ⊙ g'^[l](Z^[l])
dW^[l] = (1/m) dZ^[l] · (A^[l-1])^T
db^[l] = (1/m) sum(dZ^[l], axis=1, keepdims=True)
dA^[l-1] = (W^[l])^T · dZ^[l]
Step 6: UPDATE WEIGHTS
W^[l] ← W^[l] - α · dW^[l]
b^[l] ← b^[l] - α · db^[l]
Numerical Example 1 — Basic Dot Product (Single Neuron)
Scope: input features, neuron, sample — reduce a weighted sum to a single scalar output.
Step 1 — Define Inputs
Step 2 — Loop-Based Computation
Step 3 — Vectorized Computation
👉 Same result — one line 🔥
Step 4 — Apply Activation Function
Using sigmoid :
Final Result — Example 1
| Quantity | Value |
|---|---|
A single dot product replaced three multiplications and two additions executed in a loop — and the pattern scales to millions of features with zero code change.
Numerical Example 2 — Two-Layer Neural Network
Scope: input features, Layer 1 has neurons (ReLU), Layer 2 has neuron (Sigmoid). training samples.
Step 1 — Define Inputs and Parameters
Input matrix ():
Layer 1 ():
Layer 2 ():
Step 2 — Layer 1: Linear Step
Step 3 — Layer 1: Activation (ReLU)
All values are positive, so ReLU makes no change here.
Step 4 — Layer 2: Linear Step
Step 5 — Layer 2: Activation (Sigmoid)
Final Result — Example 2
| Sample | ||||
|---|---|---|---|---|
| Sample 1 | 1 | 4 | 3.5 | 0.9706 |
| Sample 2 | 2 | 5 | 4.5 | 0.9890 |
| Sample 3 | 3 | 6 | 5.5 | 0.9959 |
All three samples processed simultaneously in one matrix multiply per layer — no outer loop over samples required.
Comparing the Two Examples
| Property | Example 1 (Single Neuron) | Example 2 (Two-Layer Network) |
|---|---|---|
| Input shape | , | , |
| Network depth | 1 layer | 2 layers |
| Weight shapes | , | |
| Activation | Sigmoid | ReLU → Sigmoid |
| Loops replaced | 1 loop (3 iterations) | 2 layer loops + 1 sample loop |
| Output | Scalar | Row vector |
| Key vectorization benefit | Clarity / conciseness | Batch parallelism over samples |
Geometric Intuition
PCA rotates a coordinate system; vectorization transforms a dataset in the same spirit:
- Weight matrix — applies a linear transformation (rotation + scaling) to the input space
- Bias — shifts (translates) the transformed space
- Activation — bends the space non-linearly
Instead of transforming one point at a time, the matrix multiply transforms all points simultaneously — this is the geometric essence of vectorization.
Advantages of Vectorization
| Advantage | Description |
|---|---|
| Speed | Exploits SIMD / GPU parallelism — – faster 🚀 |
| Simplicity | 3 lines of math replace 30 lines of loops |
| Scalability | Same code runs on 10 samples or 10 million samples |
| Numerical | BLAS-optimised routines reduce floating-point error |
| Batch norm | Batch statistics computed trivially across the sample axis |
Limitations of Vectorization
| Limitation | Description | Alternative |
|---|---|---|
| Memory | Large matrices may exceed GPU VRAM | Mini-batch gradient descent |
| Debugging | Hard to inspect intermediate per-sample values | Use loop version for debugging |
| Sequential ops | RNNs with data-dependent control flow resist full vectorization | Truncated BPTT, scan ops |
| Sparse data | Dense matrix ops waste compute on zero entries | Sparse matrix formats |
| Numerical overflow | Large in softmax causes inf |
Stable log-sum-exp trick |
Complete Formula Reference
| Formula | Expression |
|---|---|
| Dot product | |
| Layer linear step | |
| Layer activation | |
| Sigmoid | |
| ReLU | |
| Backprop — | |
| Backprop — | |
| Backprop — | |
| Backprop — | |
| Weight update | |
| Cross-entropy loss |
Summary
INPUT (p × m)
│
▼
LAYER 1 — LINEAR: Z¹ = W¹ · X + b¹
│
▼
LAYER 1 — ACTIVATE: A¹ = g¹(Z¹)
│
▼
LAYER 2 — LINEAR: Z² = W² · A¹ + b²
│
▼
LAYER 2 — ACTIVATE: A² = g²(Z²)
│
▼
OUTPUT Ŷ = A^[L] (all m samples processed at once)
│
▼
LOSS → BACKPROP (all gradients are matrix products)
│
▼
UPDATE WEIGHTS (W ← W − α · dW)
Key Takeaways
- Vectorization = no loops — replace with
- Batch processing — stack samples as columns; one matrix multiply handles all
- Shape discipline — always verify
- Both forward and backward passes are fully vectorizable
- Hardware wins — vectorized code automatically benefits from BLAS, CUDA, and TPU kernels
- Same math, any scale — code for runs unchanged on
- Linear algebra is the language of deep learning — mastering it unlocks everything