Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 8 — Lab: Supervised Learning

Open in Colab

Lab Overview

You will implement the core of supervised learning yourself, then use scikit-learn the way professionals do.

ExerciseTopicPoints
1Linear regression with the normal equation15
2Gradient descent15
3Entropy and information gain20
4k-nearest neighbours15
5Precision, recall and F115
6A leak-free pipeline with cross-validation20
ChallengeThe best threshold for a numeric feature+10

How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Do not change the check cells.


Exercise 1: Linear Regression with the Normal Equation (15 points)

  1. mse(y_true, y_pred) returns the mean squared error.

  2. fit_normal_equation(X, y) adds a column of ones to X and returns the weight vector w=(X⊤X)−1X⊤y\mathbf{w} = (X^\top X)^{-1}X^\top\mathbf{y}, intercept first. Use np.linalg.solve rather than inverting the matrix.


Exercise 2: Gradient Descent (15 points)

Complete fit_gradient_descent(X, y, eta, steps): start from w=0\mathbf{w} = \mathbf{0} and repeat w←w−η 2nXb⊤(Xbw−y)\mathbf{w} \leftarrow \mathbf{w} - \eta\,\frac{2}{n}X_b^\top(X_b\mathbf{w} - \mathbf{y}), where XbX_b is X with a column of ones. Return the weights and the list of MSE values, one per step (computed before the update).

Question. Why does a learning rate of 1.5 make the loss grow? Answer in one or two sentences.

Your answer:


Exercise 3: Entropy and Information Gain (20 points)

Rows are tuples whose last element is the class. Complete:

  1. entropy(labels): −∑jpjlog⁡2pj-\sum_j p_j\log_2 p_j over the classes present in labels.

  2. information_gain(rows, a): the entropy of all labels, minus the weighted entropy of the subsets with each value of attribute a.

  3. best_attribute(rows, attributes): the attribute index with the highest gain.


Exercise 4: k-Nearest Neighbours (15 points)

Complete knn_predict(X_train, y_train, x, k) for one query point x: compute the Euclidean distance to every training point, take the k nearest, and return the most common label among them.


Exercise 5: Precision, Recall and F1 (15 points)

Complete precision_recall_f1(y_true, y_pred) for binary labels (1 = positive). Return a tuple of three floats. If there are no predicted positives, the precision is 0; if precision and recall are both 0, F1 is 0.


Exercise 6: A Leak-Free Pipeline (20 points)

Using the wine dataset (3 classes, 13 features):

  1. Split it 75/25 with stratify=y and random_state=0.

  2. Build a Pipeline with a StandardScaler followed by a KNeighborsClassifier.

  3. Use GridSearchCV with 5 folds to choose n_neighbors among 1, 3, 5, …, 21, on the training set only.

  4. Return the fitted search object and the test accuracy of its best model.

Question. Why must the StandardScaler be inside the pipeline rather than fitted on all of X before splitting?

Your answer:


Challenge: The Best Threshold for a Numeric Feature (+10 points)

Decision trees split numeric features with a threshold x≤tx \le t. Complete best_threshold(values, labels): try the midpoint between every pair of consecutive distinct sorted values, and return the (threshold, gain) pair with the highest information gain (use your entropy).


Lab Report

Submit this notebook with:

  • every check cell showing ✅,

  • your answers to the two questions,

  • one paragraph: which exercise taught you the most, and why?