Chapter 8 — Lab: Supervised Learning
Lab Overview¶
You will implement the core of supervised learning yourself, then use scikit-learn the way professionals do.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Linear regression with the normal equation | 15 |
| 2 | Gradient descent | 15 |
| 3 | Entropy and information gain | 20 |
| 4 | k-nearest neighbours | 15 |
| 5 | Precision, recall and F1 | 15 |
| 6 | A leak-free pipeline with cross-validation | 20 |
| Challenge | The 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.
import numpy as np
from collections import Counter
from math import log2
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
print('Setup complete.')Exercise 1: Linear Regression with the Normal Equation (15 points)¶
mse(y_true, y_pred)returns the mean squared error.fit_normal_equation(X, y)adds a column of ones toXand returns the weight vector , intercept first. Usenp.linalg.solverather than inverting the matrix.
def mse(y_true, y_pred):
# TODO: the mean of the squared differences
raise NotImplementedError
def fit_normal_equation(X, y):
# TODO: add a bias column, then solve (X^T X) w = X^T y
raise NotImplementedErrorcheck('mse', lambda: abs(mse([1, 2, 3], [1, 2, 5]) - 4 / 3) < 1e-9)
check('normal equation on (1,3) (2,5) (3,7) (4,9)', lambda: np.allclose(fit_normal_equation(np.array([[1.], [2.], [3.], [4.]]), np.array([3., 5., 7., 9.])), [1, 2]))
rng = np.random.default_rng(0); X1 = rng.normal(size=(100, 3)); y1 = X1 @ [2, -1, 0.5] + 7
check('normal equation with 3 features', lambda: np.allclose(fit_normal_equation(X1, y1), [7, 2, -1, 0.5]))Exercise 2: Gradient Descent (15 points)¶
Complete fit_gradient_descent(X, y, eta, steps): start from and repeat , where is X with a column of ones. Return the weights and the list of MSE values, one per step (computed before the update).
def fit_gradient_descent(X, y, eta=0.1, steps=1000):
# TODO: the loop of gradient descent; return (w, history)
raise NotImplementedErrorcheck('recovers the weights of exercise 1', lambda: np.allclose(fit_gradient_descent(X1, y1, 0.1, 2000)[0], [7, 2, -1, 0.5], atol=1e-3))
check('the loss never increases with eta = 0.1', lambda: np.all(np.diff(fit_gradient_descent(X1, y1, 0.1, 50)[1]) <= 1e-12))
check('a learning rate of 1.5 diverges', lambda: fit_gradient_descent(X1, y1, 1.5, 30)[1][-1] > fit_gradient_descent(X1, y1, 1.5, 30)[1][0])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:
entropy(labels): over the classes present inlabels.information_gain(rows, a): the entropy of all labels, minus the weighted entropy of the subsets with each value of attributea.best_attribute(rows, attributes): the attribute index with the highest gain.
TENNIS = [('Sunny','Hot','High','Weak','No'), ('Sunny','Hot','High','Strong','No'), ('Overcast','Hot','High','Weak','Yes'),
('Rain','Mild','High','Weak','Yes'), ('Rain','Cool','Normal','Weak','Yes'), ('Rain','Cool','Normal','Strong','No'),
('Overcast','Cool','Normal','Strong','Yes'), ('Sunny','Mild','High','Weak','No'), ('Sunny','Cool','Normal','Weak','Yes'),
('Rain','Mild','Normal','Weak','Yes'), ('Sunny','Mild','Normal','Strong','Yes'), ('Overcast','Mild','High','Strong','Yes'),
('Overcast','Hot','Normal','Weak','Yes'), ('Rain','Mild','High','Strong','No')]
def entropy(labels):
# TODO: count each class, then -sum p log2 p
raise NotImplementedError
def information_gain(rows, a):
# TODO: entropy of the labels minus the weighted entropy of each value's subset
raise NotImplementedError
def best_attribute(rows, attributes):
# TODO
raise NotImplementedErrorcheck('entropy of a 50/50 set is 1', lambda: abs(entropy(['a', 'b', 'a', 'b']) - 1) < 1e-9)
check('entropy of a pure set is 0', lambda: abs(entropy(['a'] * 5)) < 1e-9)
check('H(tennis) = 0.940', lambda: abs(entropy([r[-1] for r in TENNIS]) - 0.940) < 1e-3)
check('Gain(Outlook) = 0.247 and Gain(Wind) = 0.048', lambda: abs(information_gain(TENNIS, 0) - 0.247) < 1e-3 and abs(information_gain(TENNIS, 3) - 0.048) < 1e-3)
check('the root is Outlook', lambda: best_attribute(TENNIS, [0, 1, 2, 3]) == 0)
check('on the sunny days, Humidity is best', lambda: best_attribute([r for r in TENNIS if r[0] == 'Sunny'], [1, 2, 3]) == 2)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.
def knn_predict(X_train, y_train, x, k=3):
# TODO: distances, the k smallest (np.argsort), then a majority vote (Counter)
raise NotImplementedErrorXk = np.array([[0, 0], [0, 1], [1, 0], [5, 5], [5, 6], [6, 5.]]); yk = np.array([0, 0, 0, 1, 1, 1])
check('a point near the first group', lambda: knn_predict(Xk, yk, np.array([0.5, 0.5]), 3) == 0)
check('a point near the second group', lambda: knn_predict(Xk, yk, np.array([5.2, 5.1]), 3) == 1)
from sklearn.datasets import load_breast_cancer
Xc, yc = load_breast_cancer(return_X_y=True) # two classes and an odd k: no tied votes
Xa, Xb_, ya, yb = train_test_split(Xc, yc, test_size=0.3, random_state=0)
check('agrees with scikit-learn on the breast-cancer data', lambda: np.array_equal([knn_predict(Xa, ya, x, 5) for x in Xb_], KNeighborsClassifier(5).fit(Xa, ya).predict(Xb_)))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.
def precision_recall_f1(y_true, y_pred):
# TODO: count TP, FP, FN, then apply the formulas
raise NotImplementedErrory_true = [1] * 10 + [0] * 990
y_pred = [1] * 8 + [0] * 2 + [1] * 40 + [0] * 950 # the disease example of the chapter
check('the disease example: precision 0.167, recall 0.8, F1 0.276', lambda: np.allclose(precision_recall_f1(y_true, y_pred), (8 / 48, 0.8, 2 * (8 / 48) * 0.8 / (8 / 48 + 0.8))))
check('a classifier that never says positive', lambda: precision_recall_f1([1, 0, 1], [0, 0, 0]) == (0.0, 0.0, 0.0))Exercise 6: A Leak-Free Pipeline (20 points)¶
Using the wine dataset (3 classes, 13 features):
Split it 75/25 with
stratify=yandrandom_state=0.Build a
Pipelinewith aStandardScalerfollowed by aKNeighborsClassifier.Use
GridSearchCVwith 5 folds to choosen_neighborsamong 1, 3, 5, …, 21, on the training set only.Return the fitted search object and the test accuracy of its best model.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
def wine_pipeline():
X, y = load_wine(return_X_y=True)
# TODO: split, pipeline, grid search on the training set, then the test accuracy
raise NotImplementedErrordef _pipeline_ok():
search, acc = wine_pipeline()
steps = [type(s).__name__ for _, s in search.best_estimator_.steps]
return steps == ['StandardScaler', 'KNeighborsClassifier'] and acc >= 0.93 and search.best_params_['knn__n_neighbors'] in range(1, 22, 2)
check('scaler + k-NN, tuned by cross-validation, test accuracy ≥ 0.93', _pipeline_ok)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 . 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).
def best_threshold(values, labels):
# TODO
raise NotImplementedErrortemps = [64, 65, 68, 69, 70, 71, 72, 75, 80, 81, 83, 85]
play = ['Y', 'N', 'Y', 'Y', 'Y', 'N', 'N', 'Y', 'N', 'Y', 'Y', 'N']
check('a perfect split is found', lambda: best_threshold([1, 2, 3, 10, 11, 12], 'aaabbb') == (6.5, 1.0))
check('the threshold is a midpoint of two distinct values', lambda: best_threshold(temps, play)[0] in {(a + b) / 2 for a, b in zip(sorted(set(temps))[:-1], sorted(set(temps))[1:])})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?