Part 01 / Stage 1
Python for AI
Goal: Set up a clean Python environment and learn NumPy — the array library every later stage builds on. Time: ~2 hours · Needs: Python 3.13+, the course venv
What you will learn
- Setting up: a virtual environment with pinned package versions
- NumPy arrays: creating, shape, dtype, indexing and slicing
- Vectorization: replacing Python loops with array operations
- Broadcasting: how arrays of different shapes combine
- Randomness and seeds: reproducible experiments
- Writing clean experiment code
- Version control habits for ML projects
Topics in this part
Practice
Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.
Exercise 1: Array warm-up
Create a 4×3 array of the numbers 1–12 with np.arange and reshape. Print its shape, the second row, the last column, and every value greater than 7.
Show the solution to Exercise 1
# Exercise 1: Array warm-up
import numpy as np
a = np.arange(1, 13).reshape(4, 3)
print(a.shape)
print(a[1])
print(a[:, -1])
print(a[a > 7])
Exercise 2: Vectorize a loop
This loop computes the squared distance between two points. Rewrite it as one NumPy expression and check both give the same answer.
a = [1.0, 4.0, 2.0, 8.0]
b = [2.0, 1.0, 2.0, 4.0]
total = 0.0
for x, y in zip(a, b):
total += (x - y) ** 2
Show the solution to Exercise 2
# Exercise 2: Vectorize a loop
import numpy as np
a = [1.0, 4.0, 2.0, 8.0]
b = [2.0, 1.0, 2.0, 4.0]
total = 0.0
for x, y in zip(a, b):
total += (x - y) ** 2
av, bv = np.array(a), np.array(b)
vec = ((av - bv) ** 2).sum()
print("loop:", total)
print("vectorized:", vec)
print("same:", np.isclose(total, vec))
Exercise 3: Standardize with broadcasting
Generate a 5×3 array from default_rng(7).normal(50, 10, (5, 3)). Standardize each column (mean 0, std 1) with one broadcast expression and print the new column means and stds, rounded to 6 decimals.
Show the solution to Exercise 3
# Exercise 3: Standardize with broadcasting
import numpy as np
X = np.random.default_rng(7).normal(50, 10, (5, 3))
X_std = (X - X.mean(axis=0)) / X.std(axis=0)
print("column means:", X_std.mean(axis=0).round(6))
print("column stds: ", X_std.std(axis=0).round(6))
Exercise 4: Seeds
Write a function roll(seed) that returns 3 dice rolls (integers 1–6) from a seeded generator. Show that the same seed repeats the rolls and a different seed changes them.
Show the solution to Exercise 4
# Exercise 4: Seeds
import numpy as np
def roll(seed):
rng = np.random.default_rng(seed)
return rng.integers(1, 7, 3)
print("seed 1:", roll(1))
print("seed 1:", roll(1))
print("seed 2:", roll(2))
Mini-project: Array drills
Rewrite five loop-based functions as vectorized NumPy, and time both versions on arrays of 100,000 elements:
- sum of squares
- moving average (window 3)
- pairwise distances between two sets of points
- min-max normalisation
- one-hot encoding of integer labels
A solution for the full drill set is in solutions/mini_array_drills.py.
Stretch: turn the five functions into a small module with pytest tests and a benchmark table.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Installing packages globally | Projects break each other on upgrade | One venv per project, pinned requirements.txt |
| Looping over array elements | 100x slower, more code | Whole-array operations (+, @, .mean(axis=...)) |
| Ignoring dtype | int / int becomes float64 silently; torch wants float32 |
Check a.dtype; cast with .astype(...) |
| No seed | Results change every run; bugs hide in the noise | np.random.default_rng(42) everywhere |
| Committing data and models to Git | Repo bloats; reviews drown | .gitignore them; commit code and metrics |
Quick recap
- Create one venv per project and pin the versions in
requirements.txt. - A NumPy array holds one dtype in contiguous memory, and you can index and slice it in any dimension.
- Vectorize by writing whole-array operations instead of Python loops.
- Broadcasting applies per-column (or per-row) operations in one line.
- Seed every random generator; reproducibility is a feature.
- Commit code, ignore data and model files.
Checklist
- I created the venv and installed the pinned requirements.
- I can create arrays and explain
shape,dtype,ndim. - I can slice rows, columns and boolean masks.
- I rewrote a loop as a vectorized expression.
- I standardized columns with one broadcast expression.
- I can explain why every example here sets a seed.
Read more: NumPy broadcasting guide · Random generators