Lecture 01: Exercises
On this page
Lab
Code: code/lab.py. Tests: pytest test_lab.py (or -k core, -k stretch, -k challenge). Move to the next tier only when its tests pass.
AI rule: no AI-generated code for core functions. AI may explain an error message or a concept. For stretch and challenge you may use AI, but you must be able to explain every line to the instructor.
Core (everyone, 35 min)
word_counts, standardize, add_intercept, fit_least_squares, predict, then analyse_diabetes: a mini analysis that uses your own functions to fit BMI alone and all 10 features of the diabetes data. Expected: $R^2 \approx 0.34$ and $0.52$.
Stretch
fill_missing, group_summary (pandas, with the self-study section), top_words, pairwise_distances (derive the identity yourself first), r2_score.
Challenge (open-ended)
nearest_centroid, then a full k-means loop: assign, recompute centroids, repeat until assignments stop changing. Test data:
rng = np.random.default_rng(1)
X = np.vstack([c + rng.normal(0, 0.8, size=(15, 2)) for c in ([0, 0], [5, 5], [0, 6])])- Standardise the 10 diabetes features, refit, and rank features by $|w_j|$. Why is the ranking meaningless without standardising?
Exit ticket (last 3 minutes)
E.1 What is the shape of X.mean(axis=0) for X of shape (100, 5)? E.2 In one sentence: why lstsq instead of an explicit inverse?
In-class practice
P.1 Parsons problem (novices start here)
Put these lines in order to standardise the columns of X. One line is a distractor and is not used.
Z = (X - mean) / std
std = X.std(axis=0)
mean = X.mean(axis=1)
mean = X.mean(axis=0)
std[std == 0] = 1.0P.2 Half-complete example
Fill the two blanks so that D[i, j] is the distance between A[i] and B[j].
sq_a = (A**2).sum(axis=1)[:, None] # shape (n, 1)
sq_b = ____________________________ # shape (1, m)
D = np.sqrt(np.maximum(sq_a + sq_b - ____________, 0.0))P.3 Blank problem
Write column_ranges(X) returning, for each column, max - min, with no loops. Predict its output for X = np.array([[1, 5], [4, 2], [3, 9]]) before running it.
Questions
Recall
R.1 to R.4: the four recall questions at the start of notes.md.
1. Python core
1.1 Predict the output: a = (1, [2]); a[1].append(3); print(a). Is a tuple always unchangeable?
1.2 Explain why sorted(..., key=lambda kv: (-kv[1], kv[0])) breaks ties alphabetically.
1.3 Write a dict comprehension mapping each word to its length, keeping only words longer than 3 letters.
2. NumPy
2.1 Predict the shape of np.ones((4, 1, 3)) + np.ones((5, 1)), or say why it fails.
2.2 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?
2.3 Derive the cost of the pairwise distance formula in multiplications, in terms of $n$, $m$, $d$. Which term dominates?
3. pandas
3.1 Explain the difference between df.loc[0:2] and df.iloc[0:2] on a default integer index. How many rows does each return?
3.2 A column has values [1, 2, 3, 1000, NaN]. Compute the mean and median imputations. Which one would you use, and why?
3.3 Predict: df.groupby("sex")["target"].agg(["count", "mean"]) on the diabetes data. What shape is the result?
4. Least squares
4.1 Derive the gradient of $\mathcal{L}(\theta)$ from the sum form and confirm it equals the matrix form.
4.2 Predict what happens to $\theta^\star$ if the BMI column is duplicated. Why does lstsq still answer while inv(Xb.T @ Xb) fails?
4.3 Can $R^2$ be negative on training data for least squares with an intercept? On test data?
Solutions
Solutions are released after the session.