DS1 · Gap lecture G1
The tools every course in the path assumes: Python, NumPy, pandas and a first model in plain linear algebra.
Today · 9:00 to 12:00
| Block | Minutes |
|---|---|
| Setup and recall quiz | 15 |
| Python core | 25 |
| NumPy: vectorise and broadcast | 50 |
| Break | 10 |
| Least squares | 35 |
| Lab, exit ticket | 45 |
pandas is self-study before Day 2 (notes, section 3).
Recall · 10 minutes, on paper
R.1 · Matrices
\(A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}\), \(v = \begin{pmatrix} 1 \\ 1 \end{pmatrix}\): find \(Av\)
R.2 · Python
x = [4, 1, 3]
print(x[1:], sum(x) / len(x))
R.3 · Calculus
Minimise \(f(\theta) = (y - \theta)^2\)
R.4 · Statistics
Mean and variance of \(x = (1, 2, 3)\)
Why it matters
Rows are samples: \(n = 3\) patients.
Columns are features: \(d = 4\) measurements.
NumPy stores \(X\) as one array of shape (3, 4) and runs maths on it in compiled code.
1 · Python core
a = [1, 2]
b = a # b names the same list
b.append(99)
print(a) # [1, 2, 99]
c = a.copy() # a new list
Mutable
list, dict, set change in place
Trap
Never use a list as a default argument
1 · Worked example
text = "The model fits the data. The data fit the model."
words = re.findall(r"[a-z']+", text.lower()) # split into words
counts = Counter(words) # one pass, O(n)
sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
# [('the', 4), ('data', 2), ('model', 2)]
The key (−count, word) sorts by count, then breaks ties A to Z.
Concept question 1
a = [1, 2]; b = a; b.append(3); print(a)
A
[1, 2]
B
[1, 2, 3]
C
an error
D
[3]
Vote alone, discuss with a neighbour, vote again.
2 · NumPy

~1000×
Both lines grow linearly; NumPy just runs the loop in compiled code.
2 · Broadcasting
a: (3, 1)
+
b: (1, 4)
=
a + b: (3, 4)
2 · Worked example
\(Z_{ij} = \dfrac{X_{ij} - \bar{x}_j}{s_j}\)
X = np.array([[1., 200.], [2., 400.], [3., 600.]])
mean = X.mean(axis=0) # [2., 400.]
std = X.std(axis=0) # [0.8165, 163.30]
Z = (X - mean) / std # (3, 2) - (2,)
Result
Both columns become \((-1.22,\ 0,\ 1.22)\): units removed
2 · Derivation
\(\lVert a - b \rVert^2 = (a - b)^\top (a - b)\)
\(\phantom{\lVert a - b \rVert^2} = \lVert a \rVert^2 + \lVert b \rVert^2 - 2\,a^\top b\)
sq = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T
Check: \(a = (1, 2)\), \(b = (4, 6)\): \(5 + 52 - 32 = 25\), distance 5.

Concept question 2
np.ones((4, 1, 3)) + np.ones((5, 1))
A
(4, 5, 3)
B
an error
C
(4, 1, 3)
D
(5, 4, 3)
Vote alone, discuss with a neighbour, vote again.
3 · Least squares
We derive it, solve it in NumPy, and match scikit-learn.
3 · Derivation
\(\mathcal{L}(\theta) = \lVert y - X_b\theta \rVert^2\)
\(\phantom{\mathcal{L}(\theta)} = y^\top y - 2\,\theta^\top X_b^\top y + \theta^\top X_b^\top X_b\,\theta\)
\(\nabla_\theta \mathcal{L} = -2X_b^\top y + 2X_b^\top X_b\,\theta = 0\)
\(\theta^\star = (X_b^\top X_b)^{-1} X_b^\top y\)
Solve with np.linalg.lstsq, not an explicit inverse: stable when features are nearly collinear.
3 · Worked example
Data \((x, y)\): \((1, 1),\ (2, 3),\ (3, 5)\)
Step 1
\(X_b^\top X_b = \begin{pmatrix} 3 & 6 \\ 6 & 14 \end{pmatrix}\)
\(X_b^\top y = \begin{pmatrix} 9 \\ 22 \end{pmatrix}\)
Step 2
\(\det = 6\)
\((X_b^\top X_b)^{-1} = \tfrac{1}{6}\begin{pmatrix} 14 & -6 \\ -6 & 3 \end{pmatrix}\)
Step 3
\(\theta^\star = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\)
np.linalg.lstsq(Xb, [1., 3., 5.], rcond=None)[0] # array([-1., 2.])
3 · Real data

\(R^2 = 0.34\)
Each extra unit of BMI adds about 10 units of progression on average.
Concept question 3
A
Yes, if the fit is bad
B
No, never
C
Only with outliers
D
Only when d > n
Vote alone, discuss with a neighbour, vote again.
Practice · from worked example to blank page
P.1 · Parsons
Order the lines. One is a distractor.
P.2 · Half-complete
Fill two blanks in the distance code.
P.3 · Blank
column_ranges(X), no loops.
Z = (X - mean) / std
std = X.std(axis=0)
mean = X.mean(axis=1)
mean = X.mean(axis=0)
std[std == 0] = 1.0
Confident? Start at P.3.
5 · Lab
cd lectures/01-python-for-ds/code
pytest test_lab.py
| Tier | Functions in lab.py | Run |
|---|---|---|
| Core | word_counts, standardize, add_intercept, fit_least_squares, predict | pytest -k core |
| Stretch | fill_missing, group_summary, top_words, pairwise_distances, r2_score | -k stretch |
| Challenge | nearest_centroid, a k-means loop, all 10 features | -k challenge |
AI rule: write core code yourself.
Exit ticket · 3 minutes
E.1
Shape of X.mean(axis=0) for X of shape (100, 5)?
E.2
One sentence: why lstsq instead of an explicit inverse?
Write on the card or the form; no names needed.
Self-study before Day 2 · 30 minutes

Notes, section 3: worked example on the diabetes data.
Lab stretch: fill_missing and group_summary.
Day 2 opens with two pandas recall questions.
Recap
Python
Names share objects. Never use a mutable default.
NumPy
Think in shapes. Broadcast from the right.
Least squares
Solve \(X_b^\top X_b\,\theta = X_b^\top y\) with lstsq, never inv.
Next
1:00 Git and your portfolio repo. Before Day 2: pandas self-study, finish lab core.