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

NumPy Lab

Easy๐Ÿ Python & DataW1 D2

Before You Start

Required knowledge
Python lists, loops, functions, and basic arithmetic.
Libraries used
NumPy
Dataset and source
Small arrays and random matrices created in the notebook; no external dataset.
Expected output
Vectorized array operations, shape checks, timing comparisons, and a PCA calculation.

NumPy Deep Dive โ€” Theory & Concepts

Read this before attempting the exercises. This guide covers the core NumPy concepts you'll need, with visual explanations and code examples.


1. Why NumPy?

Python lists are flexible but slow for numerical computation. NumPy arrays are:

  • โ—Contiguous in memory โ€” no pointer chasing
  • โ—Typed โ€” every element is the same dtype (float64, int32, etc.)
  • โ—Vectorized โ€” operations apply element-wise in C, not Python loops
# Python list: ~100x slower for large arrays
python_list = [i**2 for i in range(1_000_000)]

# NumPy: vectorized, runs in C
import numpy as np
arr = np.arange(1_000_000) ** 2  # ~100x faster

Memory Layout: Row-Major (C) vs Column-Major (Fortran)

Row-major (C order):          Column-major (F order):
+---+---+---+                 +---+---+---+
| 1 | 2 | 3 |  > memory       | 1 | 3 | 5 |  > memory
+---+---+---+                 +---+---+---+
| 4 | 5 | 6 |                 | 2 | 4 | 6 |
+---+---+---+                 +---+---+---+
Memory: [1,2,3,4,5,6]         Memory: [1,2,3,4,5,6]

FAANG Interview Tip: When asked "why is NumPy faster than Python lists?", mention: contiguous memory, no type checking per element, SIMD vectorization, and cache locality.


2. Array Creation & Shapes

import numpy as np

# From lists
a = np.array([1, 2, 3])              # shape: (3,)
b = np.array([[1, 2], [3, 4]])       # shape: (2, 2)

# Common constructors
np.zeros((3, 4))       # 3ร—4 matrix of zeros
np.ones((2, 3))        # 2ร—3 matrix of ones
np.eye(3)              # 3ร—3 identity matrix
np.arange(0, 10, 2)    # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5)   # [0.0, 0.25, 0.5, 0.75, 1.0]
np.random.randn(3, 4)  # 3ร—4 matrix of standard normal values

Shape vs Reshape

Original: shape (6,)
[1, 2, 3, 4, 5, 6]

Reshaped to (2, 3):        Reshaped to (3, 2):
+---+---+---+               +---+---+
| 1 | 2 | 3 |               | 1 | 2 |
+---+---+---+               +---+---+
| 4 | 5 | 6 |               | 3 | 4 |
+---+---+---+               +---+---+
                            | 5 | 6 |
                            +---+---+

Key rule: reshape doesn't copy data โ€” it creates a view. The total number of elements must stay the same.


3. Indexing & Slicing

NumPy supports powerful indexing beyond Python lists:

arr = np.array([[10, 20, 30],
                [40, 50, 60],
                [70, 80, 90]])

arr[0, 1]        # 20 โ€” single element
arr[0]           # [10, 20, 30] โ€” first row
arr[:, 1]        # [20, 50, 80] โ€” second column
arr[1:, :2]      # [[40, 50], [70, 80]] โ€” submatrix

Boolean Indexing (Masking)

arr = np.array([1, -2, 3, -4, 5])
mask = arr > 0          # [True, False, True, False, True]
arr[mask]               # [1, 3, 5] โ€” only positive values
arr[arr > 0] = 0        # set all positives to 0

Fancy Indexing

arr = np.array([10, 20, 30, 40, 50])
indices = [0, 3, 4]
arr[indices]            # [10, 40, 50]

FAANG Gotcha: Boolean indexing returns a copy, but basic slicing returns a view. Modifying a view modifies the original!

a = np.array([1, 2, 3, 4])
b = a[:2]       # view โ€” shares memory
b[0] = 99       # a is now [99, 2, 3, 4] โš ๏ธ

c = a[a > 2]    # copy โ€” independent
c[0] = 0        # a is unchanged

4. Broadcasting

Broadcasting lets NumPy operate on arrays of different shapes without copying data.

Rules:

  1. โ—Align shapes from the right
  2. โ—Dimensions match if they're equal OR one of them is 1
  3. โ—Missing dimensions are treated as 1
Shape (3, 4) + Shape (4,)  > works! (4,) becomes (1, 4) > broadcast to (3, 4)
Shape (3, 4) + Shape (3,)  > ERROR! trailing dimensions 4 ! 3
Shape (3, 1) + Shape (1, 4) > works! result is (3, 4)

Visual Example:

A: shape (3, 1)     B: shape (1, 4)     A + B: shape (3, 4)
+---+               +---+---+---+---+   +---+---+---+---+
| 1 |       +       | 10| 20| 30| 40| = | 11| 21| 31| 41|
+---+               +---+---+---+---+   +---+---+---+---+
| 2 |                                   | 12| 22| 32| 42|
+---+                                   +---+---+---+---+
| 3 |                                   | 13| 23| 33| 43|
+---+                                   +---+---+---+---+

Interview Tip: Broadcasting is how ML frameworks compute things like "subtract the mean from every row" efficiently:

X = np.random.randn(1000, 5)     # 1000 samples, 5 features
mean = X.mean(axis=0)             # shape (5,)
X_centered = X - mean             # broadcasting! (1000, 5) - (5,) โ†’ (1000, 5)

5. Vectorized Operations & Aggregations

Never use Python loops on NumPy arrays. Use vectorized operations instead:

a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

# Element-wise operations
a + b       # [11, 22, 33, 44]
a * b       # [10, 40, 90, 160]
a ** 2      # [1, 4, 9, 16]
np.sqrt(a)  # [1.0, 1.414, 1.732, 2.0]
np.exp(a)   # [2.718, 7.389, 20.086, 54.598]

Aggregations with axis

X = np.array([[1, 2, 3],
              [4, 5, 6]])

X.sum()          # 21 โ€” total
X.sum(axis=0)    # [5, 7, 9] โ€” sum down columns
X.sum(axis=1)    # [6, 15] โ€” sum across rows
X.mean(axis=0)   # [2.5, 3.5, 4.5] โ€” column means
X.max(axis=1)    # [3, 6] โ€” row maxima
axis=0: v down rows (collapse rows)
axis=1: > across columns (collapse columns)

     col0 col1 col2
      v    v    v
row0 [ 1,   2,   3 ] > axis=1 sum = 6
row1 [ 4,   5,   6 ] > axis=1 sum = 15
      v    v    v
      5    7    9     < axis=0 sum

FAANG Gotcha: axis=0 means "operate along axis 0 (rows)" which collapses that axis. Many candidates confuse this.


6. Linear Algebra Essentials

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Matrix multiplication (NOT element-wise)
A @ B                    # or np.dot(A, B)
# [[19, 22],
#  [43, 50]]

# Transpose
A.T                      # [[1, 3], [2, 4]]

# Inverse
np.linalg.inv(A)         # [[-2, 1], [1.5, -0.5]]

# Determinant
np.linalg.det(A)         # -2.0

# Eigenvalues
vals, vecs = np.linalg.eig(A)

Key for ML: Matrix multiplication is the backbone of neural networks. Every layer computes output = X @ W + b.


7. Common Patterns in ML

Normalize features (zero mean, unit variance)

X = np.random.randn(100, 5)
X_norm = (X - X.mean(axis=0)) / X.std(axis=0)

Softmax function

def softmax(z):
    exp_z = np.exp(z - z.max())  # subtract max for numerical stability
    return exp_z / exp_z.sum()

Euclidean distance matrix

def pairwise_distances(X):
    # X: shape (N, D)
    sq = np.sum(X**2, axis=1, keepdims=True)  # (N, 1)
    return np.sqrt(sq + sq.T - 2 * X @ X.T)   # (N, N)

Summary

ConceptKey Takeaway
Why NumPyContiguous memory, vectorized C ops, cache-friendly
Views vs CopiesSlicing = view (shared memory), boolean indexing = copy
BroadcastingAlign from right, dimensions must be equal or 1
axis parameteraxis=0 collapses rows, axis=1 collapses columns
VectorizationNever loop โ€” use +, *, @, np.sum(), etc.

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

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/15 solvedSubstack Notes
1
Dataset & Setup

Setup

Section 1 โ€” ndarray Fundamentals

Task 1.1: Array Creation & Shapes

Loading editor...
1

ndarray Fundamentals

2
Array Creation & Shapes
4

Section 1 โ€” ndarray Fundamentals

Task 1.1: Array Creation & Shapes

Loading editor...
2

dtype & Memory

3
Compare memory usage
4

Explain:

  • โ—What does .shape represent?
  • โ—Why does contiguous memory matter?

Section 1.2 โ€” dtype & Memory

Task 1.2: Compare memory usage

Loading editor...
3

Indexing, Views & Copies

4
Views vs Copies
5

Interview Question:
Why does dtype selection matter in large ML pipelines?

Section 2 โ€” Indexing, Views & Copies

Task 2.1: Views vs Copies

Loading editor...
4

Boolean Masking

5
Boolean masking
4

Explain:

  • โ—Why did the original array change (or not)?

Section 2.2 โ€” Boolean Masking

Task 2.2: Boolean masking

Loading editor...
5

Broadcasting

6
Broadcasting Rules
6

Section 3 โ€” Broadcasting

Task 3.1: Broadcasting Rules

Loading editor...
6

Broadcasting Trap

7
Fix a broadcasting trap
2

Explain broadcasting step-by-step.

Section 3.2 โ€” Broadcasting Trap

Task 3.2: Fix a broadcasting trap

Loading editor...
7

Vectorization vs Loops

8
Loop vs Vectorized
3

What was wrong with the original shapes?

Section 4 โ€” Vectorization vs Loops

Task 4.1: Loop vs Vectorized

Loading editor...
9
Pairwise Distance (FAANG Classic)
4

Why is vectorization faster?

Task 4.2: Pairwise Distance (FAANG Classic)

Loading editor...
8

Numerical Stability

10
Softmax
4

Section 5 โ€” Numerical Stability

Task 5.1: Softmax

Softmax converts logits into probabilities:

softmax(z)i=eziโˆ‘j=1Kezj\mathrm{softmax}(z)_i = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}}

Stable form (subtract max logit in each row):

softmax(z)i=eziโˆ’maxโก(z)โˆ‘j=1Kezjโˆ’maxโก(z)\mathrm{softmax}(z)_i = \frac{e^{z_i - \max(z)}}{\sum_{j=1}^{K} e^{z_j - \max(z)}}
Loading editor...
9

Linear Algebra

11
Matrix Multiplication
2

Why does subtracting max work?

Section 6 โ€” Linear Algebra

Task 6.1: Matrix Multiplication

Loading editor...
12
Solving Linear Systems
2

Explain difference between dot, @, and matmul.

Task 6.2: Solving Linear Systems

Loading editor...
10

Performance & Memory

13
In-Place Operations
3

Section 7 โ€” Performance & Memory

Task 7.1: In-Place Operations

Loading editor...
14
Strides
3

Task 7.2: Strides

Loading editor...
11

Mini Case Study

15
Mini case study (NumPy PCA)
4

Section 8 โ€” Mini Case Study

Task 8.1: Mini case study (NumPy PCA)

Eigen Decomposition Overview

Singular Value Decomposition (SVD)

Loading editor...

Need help? Share feedback