Lecture 01: Python for Data Science
On this page
Gap lecture G1. Taken before C1-1 Machine Learning with Python. Notation: syllabus/notation.md.
Setup (offline, once per laptop):
python -m venv .venv && source .venv/bin/activatepip install -r requirements.txtThe dataset is sklearn.datasets.load_diabetes, which ships with scikit-learn, so no download is needed.
Recall
Prerequisites check, 10 minutes, answered on paper before section 1. Solutions in exercises.md (R.1 to R.4).
- For $A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}$ and $v = \begin{pmatrix} 1 \\ 1 \end{pmatrix}$, compute $Av$ and $v^\top A v$. What is the shape of $AB$ when $A \in \mathbb{R}^{2 \times 3}$ and $B \in \mathbb{R}^{3 \times 4}$?
- Predict the output:
x = [4, 1, 3]; print(x[1:], sorted(x), sum(x) / len(x)). - For $f(\theta) = (y - \theta)^2$, find $f'(\theta)$ and the $\theta$ that minimises $f$.
- Compute the mean $\bar{x}$ and the variance $\frac{1}{n}\sum_i (x_i - \bar{x})^2$ of $x = (1, 2, 3)$.
1. Python core for data work
Theory
Every course in the path is taught in Python. Before arrays and models, learners need the core types well enough to clean text, build lookup tables and write small reusable functions. Most data bugs come from two things covered here: misunderstanding mutability, and writing loops where a built-in already exists.
Definitions
Definition (mutable object). An object whose value can change after creation without changing its identity
id(obj).list,dict,setare mutable;int,float,str,tupleare immutable.
Plain English: assigning b = a does not copy; both names point to one object. If that object is mutable, changing it through b also changes what a shows.
Definition (comprehension).
[f(v) for v in S if p(v)]builds the list $\{f(v) : v \in S,\ p(v)\}$ in iteration order.
Symbols: $S$ is any iterable, $f$ maps each element to the output value, $p$ is a filter predicate returning True/False.
Core containers:
| Type | Literal | Use |
|---|---|---|
list |
[1, 2, 3] |
Ordered sequence, index by position |
tuple |
(1, 2) |
Fixed record, can be a dict key |
dict |
{"a": 1} |
Key to value lookup, average $O(1)$ |
set |
{1, 2} |
Unique items, membership test average $O(1)$ |
Worked example: word frequencies
Task: the 3 most frequent words in a sentence.
import re
from collections import Counter
text = "The model fits the data. The data fit the model."
words = re.findall(r"[a-z']+", text.lower())
# ['the', 'model', 'fits', 'the', 'data', 'the', 'data', 'fit', 'the', 'model']
counts = Counter(words)
# {'the': 4, 'model': 2, 'data': 2, 'fits': 1, 'fit': 1}
top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
# [('the', 4), ('data', 2), ('model', 2)]Step by step:
text.lower()so"The"and"the"count as one word.re.findall(r"[a-z']+", ...)returns every maximal run of letters or apostrophes, which drops punctuation.Counteris adictsubclass that counts occurrences in one pass, $O(n)$.- Sort key
(-count, word): Python compares tuples element by element, so higher counts come first and ties are broken alphabetically. This is whydatacomes beforemodel.
Mutability trap:
def add_item(item, basket=[]): # default list created once, at definition
basket.append(item)
return basket
add_item("a") # ['a']
add_item("b") # ['a', 'b'] same list reusedFix: basket=None, then basket = [] if basket is None else basket.
Visual
Names point to objects:
a = [1, 2] a ──┐
b = a ├──► [1, 2, 99] (one list)
b.append(99) b ──┘
c = a.copy() c ────► [1, 2, 99] (separate list)Check questions
- Predict the output:
a = (1, [2]); a[1].append(3); print(a). Is a tuple always unchangeable? - Explain why
sorted(..., key=lambda kv: (-kv[1], kv[0]))breaks ties alphabetically. - Write a dict comprehension mapping each word to its length, keeping only words longer than 3 letters.
2. NumPy: arrays, vectorisation, broadcasting
Theory
A dataset of $n$ samples and $d$ features is a matrix $X \in \mathbb{R}^{n \times d}$. ML maths is written in matrix form (C1-2, C1-3), and NumPy runs that form directly in compiled code. In the timing figure below, a Python loop is about 1000 times slower than the NumPy equivalent at $n = 10^6$. C1-3 calls this vectorisation and depends on it.
Definitions
Definition (ndarray). A fixed-type, n-dimensional grid of numbers with a
shapetuple $(s_1, \dots, s_k)$ and adtype.
Plain English: one block of memory holding numbers of the same type, plus the shape that says how to read it. X.shape == (n, d) means $n$ rows (samples) and $d$ columns (features).
Definition (axis reduction). For $X \in \mathbb{R}^{n \times d}$,
X.mean(axis=0)is the vector $\bar{x} \in \mathbb{R}^d$ with $\bar{x}_j = \frac{1}{n}\sum_{i=1}^{n} X_{ij}$.
Plain English: axis=0 collapses the rows and gives one value per column (per feature). axis=1 collapses the columns and gives one value per row (per sample).
Definition (broadcasting). Two shapes are compatible if, aligning them from the right, each pair of dimensions is equal or one of them is 1. Missing leading dimensions count as 1. The result takes the larger size in each position, and a size-1 dimension is repeated along it without copying.
Examples:
A.shape |
B.shape |
Result | Meaning |
|---|---|---|---|
(n, d) |
(d,) |
(n, d) |
Subtract a per-feature vector from every row |
(n, 1) |
(1, m) |
(n, m) |
Outer combination: every row with every column |
(n, d) |
(n,) |
error | Aligned from the right, $d \ne n$; use (n, 1) |
Worked example 1: standardisation
Goal: $Z_{ij} = \dfrac{X_{ij} - \bar{x}_j}{s_j}$, where $s_j = \sqrt{\frac{1}{n}\sum_i (X_{ij} - \bar{x}_j)^2}$ is the std of feature $j$.
X = np.array([[1., 200.], [2., 400.], [3., 600.]]) # shape (3, 2)
mean = X.mean(axis=0) # [2., 400.] shape (2,)
std = X.std(axis=0) # [0.8165, 163.30] shape (2,)
Z = (X - mean) / std # (3, 2) - (2,) broadcasts to (3, 2)
# [[-1.2247, -1.2247],
# [ 0. , 0. ],
# [ 1.2247, 1.2247]]Check by hand for column 0: $\bar{x}_0 = 2$, $s_0 = \sqrt{(1 + 0 + 1)/3} = \sqrt{2/3} = 0.8165$, so $Z_{00} = (1 - 2)/0.8165 = -1.2247$. Both columns end up equal because column 1 is $200 \times$ column 0, and standardisation removes scale. This is why gradient descent (C1-2) is run on standardised features: no feature dominates because of its units.
Worked example 2: all pairwise distances without loops
k-means (C1-1) and k-NN need $D_{ij} = \lVert a^{(i)} - b^{(j)} \rVert$ for $A \in \mathbb{R}^{n \times d}$, $B \in \mathbb{R}^{m \times d}$.
Derivation. Expand the squared norm using $\lVert v \rVert^2 = v^\top v$:
$$ \lVert a - b \rVert^2 = (a - b)^\top (a - b) = a^\top a - a^\top b - b^\top a + b^\top b = \lVert a \rVert^2 + \lVert b \rVert^2 - 2\, a^\top b, $$
using $b^\top a = a^\top b$ (both are the same scalar). For all pairs at once:
- $\lVert a^{(i)} \rVert^2$ for every $i$:
(A**2).sum(axis=1), shape(n,), reshaped to(n, 1) - $\lVert b^{(j)} \rVert^2$ for every $j$:
(B**2).sum(axis=1), reshaped to(1, m) - $a^{(i)\top} b^{(j)}$ for every pair: entry $(i, j)$ of $AB^\top$, shape
(n, m)
sq = (A**2).sum(axis=1)[:, None] + (B**2).sum(axis=1)[None, :] - 2 * A @ B.T
D = np.sqrt(np.maximum(sq, 0.0))Broadcasting (n, 1) + (1, m) gives (n, m). np.maximum(sq, 0) handles rounding: when $a \approx b$ the subtraction of two large, nearly equal numbers can give a tiny negative value, and sqrt of that is nan.
Numeric check with $a = (1, 2)$, $b = (4, 6)$: $\lVert a \rVert^2 = 5$, $\lVert b \rVert^2 = 52$, $a^\top b = 16$, so $5 + 52 - 32 = 25$ and $D = 5$. Directly: $\sqrt{3^2 + 4^2} = 5$.
Visual

Both lines grow linearly in $n$ (slope 1 on log-log axes), but NumPy's constant is about 1000 times smaller. Same algorithm, different execution engine.

Points are ordered by cluster, so the three dark blocks on the diagonal are within-cluster distances. Clustering algorithms look for exactly this block structure.
Code: code/figures.py.
Check questions
- Predict the shape of
np.ones((4, 1, 3)) + np.ones((5, 1)), or say why it fails. - A learner writes
X - X.mean(axis=1)for $X$ of shape(100, 5). What happens? What did they mean, and how do they fix it? - Derive the cost of the pairwise distance formula in floating point multiplications, in terms of $n$, $m$, $d$. Which term dominates?
3. pandas: tables, groups, missing values
Self-study before Day 2 (30 minutes). Not taught live. Work through this section and the stretch functions
fill_missingandgroup_summary; Day 2 opens with two recall questions on it.
Theory
Real data arrives as tables with named, mixed-type columns and gaps. pandas is the standard tool for loading, cleaning and summarising it before it becomes a NumPy array for a model. C1-1 labs use it throughout.
Definitions
Definition (DataFrame). A 2-D table with a row index, named columns, and one dtype per column. Each column is a
Series: a 1-D array with the same index.
Plain English: a spreadsheet in memory whose columns are NumPy arrays and whose rows have labels.
Definition (split-apply-combine).
df.groupby(g)[c].agg(f)splits rows into groups by the value of column $g$, applies $f$ to column $c$ within each group, and combines the results into one row per group.Definition (median imputation). Replace each missing value in column $c$ by the median of the observed values of $c$.
Plain English: fill gaps with a typical value. The median is used instead of the mean because a few extreme values do not move it.
Selection rules:
| Expression | Returns |
|---|---|
df["bmi"] |
One column, Series |
df[["bmi", "age"]] |
Several columns, DataFrame |
df.loc[rows, cols] |
By label |
df.iloc[i, j] |
By integer position |
df[df["bmi"] > 30] |
Rows where the boolean mask is True |
Worked example: does BMI relate to diabetes progression?
from sklearn.datasets import load_diabetes
df = load_diabetes(as_frame=True, scaled=False).frame # 442 rows, 11 columns
df.shape # (442, 11)
df["bmi"].describe() # mean 26.4, min 18.0, max 42.2
df.isna().sum().sum() # 0 missing values
df["bmi_band"] = pd.qcut(df["bmi"], 4, labels=["Q1 low", "Q2", "Q3", "Q4 high"])
df.groupby("bmi_band", observed=True)["target"].mean().round(1)
# Q1 low 103.4
# Q2 123.9
# Q3 172.3
# Q4 high 210.1Steps:
scaled=Falseloads the original units (BMI in kg/m$^2$) instead of the pre-standardised version.pd.qcut(..., 4)cuts at the 25th, 50th, 75th percentiles, giving 4 groups of about 110 patients each.groupby(...).mean()splits by band, takes the mean target in each, and combines into one value per band.- Reading: mean progression roughly doubles from the lowest to the highest BMI quartile. This is an association only; section 4 puts a number on the slope.
Missing values on a small table:
students = pd.DataFrame({"track": ["ml", "nlp", "ml"], "hours": [10.0, np.nan, 14.0]})
students.fillna(students.select_dtypes("number").median())
# hours: [10.0, 12.0, 14.0] median of observed {10, 14} is 12Visual

Check questions
- Explain the difference between
df.loc[0:2]anddf.iloc[0:2]on a default integer index. How many rows does each return? - A column has values
[1, 2, 3, 1000, NaN]. Compute the mean and median imputations. Which one would you use, and why? - Predict:
df.groupby("sex")["target"].agg(["count", "mean"])on the diabetes data. What shape is the result?
4. From data to model: least squares in NumPy
Theory
This section connects the tools to the first model of C1-1 and C1-2. Linear regression predicts a target as a weighted sum of features. Solving it in NumPy first, then checking against scikit-learn, shows that LinearRegression().fit is linear algebra and nothing more.
Definitions
Definition (linear model). $\hat{y} = X_b \theta$, where $X_b = [\mathbf{1}_n \ X] \in \mathbb{R}^{n \times (d+1)}$ and $\theta = (b, w_1, \dots, w_d)^\top$.
Symbols: $\mathbf{1}_n$ is a column of ones, so the first entry of $\theta$ acts as the intercept $b$; $w_j$ is the weight of feature $j$; $\hat{y} \in \mathbb{R}^n$ holds one prediction per sample.
Definition (least squares loss). $\mathcal{L}(\theta) = \lVert y - X_b \theta \rVert^2 = \sum_{i=1}^{n} \big(y_i - \hat{y}_i\big)^2$.
Plain English: add up the squared vertical gaps (residuals) between each point and the line. Squaring makes every gap positive and penalises big misses more.
Definition (coefficient of determination). $R^2 = 1 - \dfrac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2}$.
Plain English: the fraction of the target's variance the model explains. $R^2 = 0$ means no better than always predicting the mean $\bar{y}$; $R^2 = 1$ is a perfect fit.
Derivation: the normal equations
Expand the loss:
$$ \mathcal{L}(\theta) = (y - X_b\theta)^\top (y - X_b\theta) = y^\top y - 2\,\theta^\top X_b^\top y + \theta^\top X_b^\top X_b\, \theta . $$
The middle step uses $y^\top X_b \theta = (y^\top X_b \theta)^\top = \theta^\top X_b^\top y$, since a scalar equals its transpose.
Take the gradient with the identities $\nabla_\theta (\theta^\top c) = c$ and $\nabla_\theta (\theta^\top A \theta) = (A + A^\top)\theta = 2A\theta$ for symmetric $A$ (here $A = X_b^\top X_b$, which is symmetric):
$$ \nabla_\theta \mathcal{L} = -2 X_b^\top y + 2 X_b^\top X_b\, \theta . $$
Set it to zero:
$$ X_b^\top X_b\, \theta = X_b^\top y . $$
This is a minimum, not just a stationary point: the Hessian is $2X_b^\top X_b$, and for any $v$, $v^\top X_b^\top X_b v = \lVert X_b v \rVert^2 \ge 0$, so $\mathcal{L}$ is convex. If the columns of $X_b$ are linearly independent, $X_b^\top X_b$ is invertible and
$$ \theta^\star = (X_b^\top X_b)^{-1} X_b^\top y . $$
In code, use np.linalg.lstsq, not an explicit inverse. It solves the same problem with an orthogonal factorisation, which is more accurate when features are nearly collinear and still works when $X_b^\top X_b$ is singular.
Worked example 1: by hand, 3 points
Data $(x, y)$: $(1, 1), (2, 3), (3, 5)$.
$$ X_b = \begin{pmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \end{pmatrix},\quad X_b^\top X_b = \begin{pmatrix} 3 & 6 \\ 6 & 14 \end{pmatrix},\quad X_b^\top y = \begin{pmatrix} 9 \\ 22 \end{pmatrix}. $$
$\det(X_b^\top X_b) = 3 \cdot 14 - 6 \cdot 6 = 6$, so
$$ \theta^\star = \frac{1}{6}\begin{pmatrix} 14 & -6 \\ -6 & 3 \end{pmatrix}\begin{pmatrix} 9 \\ 22 \end{pmatrix} = \frac{1}{6}\begin{pmatrix} 126 - 132 \\ -54 + 66 \end{pmatrix} = \begin{pmatrix} -1 \\ 2 \end{pmatrix}. $$
The line is $\hat{y} = -1 + 2x$. It passes through all three points, so the residuals are 0 and $R^2 = 1$. NumPy agrees:
X = np.array([[1.], [2.], [3.]]); y = np.array([1., 3., 5.])
Xb = np.column_stack([np.ones(len(X)), X])
np.linalg.lstsq(Xb, y, rcond=None)[0] # array([-1., 2.])Worked example 2: BMI on the diabetes data
X, y = df[["bmi"]].to_numpy(), df["target"].to_numpy()
Xb = np.column_stack([np.ones(len(X)), X])
theta = np.linalg.lstsq(Xb, y, rcond=None)[0] # [-117.77, 10.23]
y_hat = Xb @ theta
r2 = 1 - ((y - y_hat)**2).sum() / ((y - y.mean())**2).sum() # 0.344
from sklearn.linear_model import LinearRegression
m = LinearRegression().fit(X, y)
m.intercept_, m.coef_ # -117.77, [10.23]Reading: each extra unit of BMI goes with about 10.2 more units of progression on average, and BMI alone explains 34% of the variance. The intercept $-117.8$ is the prediction at BMI 0, which lies outside the data and has no physical meaning; it only positions the line.
Visual

Grey segments are residuals $y_i - \hat{y}_i$ for a sample of points. The fitted line minimises the sum of their squares.
Check questions
- Derive the gradient of $\mathcal{L}(\theta)$ yourself, starting from the sum form $\sum_i (y_i - x_b^{(i)\top}\theta)^2$, and confirm it equals the matrix form.
- Predict what happens to $\theta^\star$ if you duplicate the BMI column, so $X$ has two identical columns. Why does
lstsqstill return an answer whilenp.linalg.inv(Xb.T @ Xb)fails or is unstable? - Can $R^2$ be negative on training data for least squares with an intercept? On test data? Explain.
Lab
code/lab.py: 11 functions to implement, covering all four sections. Tests in code/test_lab.py.
cd lectures/01-python-for-ds/code && pytest test_lab.pyReference answers: code/solutions.py (verify with LAB_MODULE=solutions pytest test_lab.py).