DS1 · Gap lecture G1

Python for Data Science

The tools every course in the path assumes: Python, NumPy, pandas and a first model in plain linear algebra.

Day 1 · Fri 4 Dec 2026

9:00–12:00 · Lab 16

Group AI-2

Today · 9:00 to 12:00

Three tools, one model

BlockMinutes
Setup and recall quiz15
Python core25
NumPy: vectorise and broadcast50
Break10
Least squares35
Lab, exit ticket45

pandas is self-study before Day 2 (notes, section 3).

Recall · 10 minutes, on paper

Four warm-up questions

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

Every dataset in this path is a matrix \(X \in \mathbb{R}^{n \times d}\)

x₁₁
x₁₂
x₁₃
x₁₄
x₂₁
x₂₂
x₂₃
x₂₄
x₃₁
x₃₂
x₃₃
x₃₄

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

Assignment shares an object; it never copies

Python

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

Count words in four lines

Python

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

What does this print?

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

Same work, about 1000 times faster

Log-log chart of runtime against array length: a Python loop is about 1000 times slower than NumPy x @ x at one million elements

~1000×

Both lines grow linearly; NumPy just runs the loop in compiled code.

2 · Broadcasting

Align shapes from the right; a size-1 axis stretches

0
0
0
0
10
10
10
10
20
20
20
20

a: (3, 1)

+

1
2
3
4
1
2
3
4
1
2
3
4

b: (1, 4)

=

1
2
3
4
11
12
13
14
21
22
23
24

a + b: (3, 4)

2 · Worked example

Standardise every column in one line

\(Z_{ij} = \dfrac{X_{ij} - \bar{x}_j}{s_j}\)

Python

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

All pairwise distances without a loop

\(\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.

Heatmap of pairwise distances for 45 points in 3 clusters A, B, C: three dark blocks on the diagonal

Concept question 2

What is the shape of the result?

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

LinearRegression().fit is linear algebra and nothing more

We derive it, solve it in NumPy, and match scikit-learn.

3 · Derivation

Setting the gradient to zero gives the normal equations

\(\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

Three points give \(\hat{y} = -1 + 2x\)

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

BMI alone explains a third of the variance

Scatter of disease progression against BMI for 442 patients, fitted line y = -118 + 10.2 BMI, grey residual segments, R squared 0.34

\(R^2 = 0.34\)

Each extra unit of BMI adds about 10 units of progression on average.

Concept question 3

Least squares with an intercept, on training data: can \(R^2\) be negative?

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

Three steps, less help each time

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.

Python

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

Core first, then stretch, then challenge

Terminal

cd lectures/01-python-for-ds/code

pytest test_lab.py

TierFunctions in lab.pyRun
Coreword_counts, standardize, add_intercept, fit_least_squares, predictpytest -k core
Stretchfill_missing, group_summary, top_words, pairwise_distances, r2_score-k stretch
Challengenearest_centroid, a k-means loop, all 10 features-k challenge

AI rule: write core code yourself.

Exit ticket · 3 minutes

Two questions before you leave

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

pandas: load, select, group, fill gaps

Bar chart of mean disease progression by BMI quartile: Q1 103, Q2 124, Q3 172, Q4 210

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

What to take into C1-1

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.

Home