Chapter 8 — Implementation: Supervised Learning in Practice
Each method of the chapter is written from scratch in NumPy first, so you can see every step, and then compared with scikit-learn, the library you will use in practice.
Contents
Linear regression: normal equation and gradient descent
Logistic regression with gradient descent
A decision tree (ID3) on the tennis data
k-nearest neighbours, and the choice of k
Naive Bayes for spam
Comparing models with cross-validation, a confusion matrix and an ROC curve
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
from math import log2
from sklearn.datasets import load_iris, load_breast_cancer, make_regression
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, roc_auc_score, ConfusionMatrixDisplay
np.random.seed(0)
plt.rcParams['figure.figsize'] = (7, 4)1. Linear Regression¶
We generate 200 noisy points from and recover the weights two ways.
rng = np.random.default_rng(42)
X = rng.uniform(-2, 2, size=(200, 2))
y = 4 + 3 * X[:, 0] - 2 * X[:, 1] + rng.normal(0, 0.5, 200)
def add_bias(X):
"""Prepend a column of ones, so that w[0] is the intercept."""
return np.c_[np.ones(len(X)), X]
# 1) the normal equation (solve is more stable than inverting the matrix)
Xb = add_bias(X)
w_normal = np.linalg.solve(Xb.T @ Xb, Xb.T @ y)
print('normal equation :', np.round(w_normal, 3))
# 2) batch gradient descent
def fit_gd(X, y, eta=0.1, steps=500):
Xb = add_bias(X)
w = np.zeros(Xb.shape[1])
history = []
for _ in range(steps):
error = Xb @ w - y
history.append(np.mean(error ** 2))
w -= eta * 2 / len(y) * Xb.T @ error
return w, history
w_gd, history = fit_gd(X, y)
print('gradient descent :', np.round(w_gd, 3))
print('scikit-learn :', np.round([LinearRegression().fit(X, y).intercept_, *LinearRegression().fit(X, y).coef_], 3))
plt.plot(history); plt.yscale('log'); plt.xlabel('step'); plt.ylabel('MSE (log scale)'); plt.title('Gradient descent converges'); plt.show()normal equation : [ 3.98 3.047 -2.064]
gradient descent : [ 3.98 3.047 -2.064]
scikit-learn : [ 3.98 3.047 -2.064]

All three methods agree on weights close to the true ; the leftover difference is the noise.
2. Logistic Regression¶
The breast-cancer dataset has 569 tumours, 30 numeric features each, labelled malignant (0) or benign (1). We standardise with statistics of the training set only.
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
scaler = StandardScaler().fit(X_train) # fitted on the training set only
X_train_s, X_test_s = scaler.transform(X_train), scaler.transform(X_test)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def fit_logistic(X, y, eta=0.1, steps=2000):
Xb = add_bias(X)
w = np.zeros(Xb.shape[1])
losses = []
for _ in range(steps):
p = sigmoid(Xb @ w)
losses.append(-np.mean(y * np.log(p + 1e-12) + (1 - y) * np.log(1 - p + 1e-12)))
w -= eta * Xb.T @ (p - y) / len(y) # the cross-entropy gradient
return w, losses
w, losses = fit_logistic(X_train_s, y_train)
pred = (sigmoid(add_bias(X_test_s) @ w) > 0.5).astype(int)
print(f'from scratch : test accuracy {np.mean(pred == y_test):.3f}')
sk = LogisticRegression(max_iter=1000).fit(X_train_s, y_train)
print(f'scikit-learn : test accuracy {sk.score(X_test_s, y_test):.3f}')
plt.plot(losses); plt.xlabel('step'); plt.ylabel('cross-entropy'); plt.title('Training loss'); plt.show()from scratch : test accuracy 0.965
scikit-learn : test accuracy 0.958

3. A Decision Tree from Scratch (ID3)¶
We rebuild the tree of the chapter’s worked example and check the information gains.
COLUMNS = ['Outlook', 'Temp', 'Humidity', 'Wind']
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(rows):
counts = Counter(r[-1] for r in rows)
return -sum(c / len(rows) * log2(c / len(rows)) for c in counts.values())
def gain(rows, a):
remainder = 0
for v in set(r[a] for r in rows):
subset = [r for r in rows if r[a] == v]
remainder += len(subset) / len(rows) * entropy(subset)
return entropy(rows) - remainder
def id3(rows, attributes):
labels = [r[-1] for r in rows]
if len(set(labels)) == 1:
return labels[0] # a pure leaf
if not attributes:
return Counter(labels).most_common(1)[0][0] # out of questions: the majority
best = max(attributes, key=lambda a: gain(rows, a))
rest = [a for a in attributes if a != best]
return {COLUMNS[best]: {v: id3([r for r in rows if r[best] == v], rest) for v in sorted(set(r[best] for r in rows))}}
for a, name in enumerate(COLUMNS):
print(f'Gain({name}) = {gain(TENNIS, a):.3f}')
tree = id3(TENNIS, [0, 1, 2, 3])
print(tree)Gain(Outlook) = 0.247
Gain(Temp) = 0.029
Gain(Humidity) = 0.152
Gain(Wind) = 0.048
{'Outlook': {'Overcast': 'Yes', 'Rain': {'Wind': {'Strong': 'No', 'Weak': 'Yes'}}, 'Sunny': {'Humidity': {'High': 'No', 'Normal': 'Yes'}}}}
def classify(tree, example):
while isinstance(tree, dict):
attribute = next(iter(tree))
tree = tree[attribute][example[COLUMNS.index(attribute)]]
return tree
print(classify(tree, ('Sunny', 'Cool', 'High', 'Strong'))) # -> No: sunny and humid
print(classify(tree, ('Rain', 'Hot', 'High', 'Weak'))) # -> Yes: rain, but no strong windNo
Yes
scikit-learn’s CART trees work on numbers. On the iris flowers, a depth-3 tree already reaches high accuracy, and we can draw it:
iris = load_iris()
Xi_train, Xi_test, yi_train, yi_test = train_test_split(iris.data, iris.target, test_size=0.3, stratify=iris.target, random_state=1)
dt = DecisionTreeClassifier(max_depth=3, random_state=0).fit(Xi_train, yi_train)
print(f'test accuracy: {dt.score(Xi_test, yi_test):.3f}')
plt.figure(figsize=(11, 5))
plot_tree(dt, feature_names=iris.feature_names, class_names=iris.target_names, filled=True, fontsize=8)
plt.show()test accuracy: 0.978

Depth and overfitting¶
Training accuracy keeps rising with depth; validation accuracy stops improving, and then falls a little. That gap is overfitting.
depths = range(1, 16)
train_acc, cv_acc = [], []
for d in depths:
m = DecisionTreeClassifier(max_depth=d, random_state=0)
train_acc.append(m.fit(X_train, y_train).score(X_train, y_train))
cv_acc.append(cross_val_score(m, X_train, y_train, cv=5).mean())
plt.plot(depths, train_acc, 'o-', label='training'); plt.plot(depths, cv_acc, 's-', label='5-fold cross-validation')
plt.xlabel('max depth'); plt.ylabel('accuracy'); plt.legend(); plt.title('Breast cancer: tree depth'); plt.show()
print('best depth by cross-validation:', depths[int(np.argmax(cv_acc))])
best depth by cross-validation: 5
4. k-Nearest Neighbours¶
def knn_predict(X_train, y_train, X_query, k=5):
predictions = []
for x in X_query:
distances = np.sqrt(((X_train - x) ** 2).sum(axis=1)) # Euclidean distance to every training point
nearest = np.argsort(distances)[:k]
predictions.append(Counter(y_train[nearest]).most_common(1)[0][0])
return np.array(predictions)
pred = knn_predict(X_train_s, y_train, X_test_s, k=5)
print(f'from scratch (k=5): {np.mean(pred == y_test):.3f}')
print(f'scikit-learn (k=5): {KNeighborsClassifier(5).fit(X_train_s, y_train).score(X_test_s, y_test):.3f}')
# scaling matters: the same model without standardisation
print(f'without scaling : {KNeighborsClassifier(5).fit(X_train, y_train).score(X_test, y_test):.3f}')from scratch (k=5): 0.951
scikit-learn (k=5): 0.951
without scaling : 0.916
ks = list(range(1, 40, 2))
scores = [cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(k)), X_train, y_train, cv=5).mean() for k in ks]
plt.plot(ks, scores, 'o-'); plt.xlabel('k'); plt.ylabel('cross-validated accuracy'); plt.title('Choosing k'); plt.show()
print('best k:', ks[int(np.argmax(scores))])
best k: 3
5. Naive Bayes for Spam¶
A multinomial Naive Bayes with Laplace smoothing, working with log probabilities to avoid underflow. These are the emails of the chapter’s worked example.
spam = ['free money now', 'free offer', 'win free money', 'cheap offer now']
ham = ['meeting today', 'project meeting notes', 'lunch today', 'meeting free time', 'notes for project', 'see you today']
class NaiveBayes:
def fit(self, documents, labels):
self.classes = sorted(set(labels))
self.vocabulary = {w for d in documents for w in d.split()}
self.log_prior, self.log_likelihood = {}, {}
for c in self.classes:
docs = [d for d, l in zip(documents, labels) if l == c]
counts = Counter(w for d in docs for w in d.split())
total = sum(counts.values())
self.log_prior[c] = np.log(len(docs) / len(documents))
self.log_likelihood[c] = {w: np.log((counts[w] + 1) / (total + len(self.vocabulary))) for w in self.vocabulary}
return self
def scores(self, document):
words = [w for w in document.split() if w in self.vocabulary] # unknown words are ignored
return {c: self.log_prior[c] + sum(self.log_likelihood[c][w] for w in words) for c in self.classes}
def predict_proba(self, document):
s = self.scores(document)
top = max(s.values())
exp = {c: np.exp(v - top) for c, v in s.items()}
return {c: e / sum(exp.values()) for c, e in exp.items()}
nb = NaiveBayes().fit(spam + ham, ['spam'] * 4 + ['ham'] * 6)
for message in ['free meeting', 'free money', 'project notes today', 'win cheap offer']:
p = nb.predict_proba(message)
print(f'{message:22} P(spam) = {p["spam"]:.2f} -> {max(p, key=p.get)}')free meeting P(spam) = 0.32 -> ham
free money P(spam) = 0.85 -> spam
project notes today P(spam) = 0.03 -> ham
win cheap offer P(spam) = 0.93 -> spam
“free meeting” gives , exactly the value computed by hand in the chapter.
6. Comparing Models¶
Five-fold stratified cross-validation of six classifiers on the breast-cancer training set. Each model that needs scaling gets it inside a pipeline, so the scaler never sees the validation fold.
models = {
'Logistic regression': make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
'k-NN (k=7)': make_pipeline(StandardScaler(), KNeighborsClassifier(7)),
'Gaussian Naive Bayes': GaussianNB(),
'Decision tree': DecisionTreeClassifier(max_depth=4, random_state=0),
'Random forest': RandomForestClassifier(200, random_state=0),
'Gradient boosting': GradientBoostingClassifier(random_state=0),
}
cv = StratifiedKFold(5, shuffle=True, random_state=0)
results = {name: cross_val_score(m, X_train, y_train, cv=cv, scoring='f1') for name, m in models.items()}
for name, s in sorted(results.items(), key=lambda kv: -kv[1].mean()):
print(f'{name:22} F1 = {s.mean():.3f} ± {s.std():.3f}')
names = list(results)
plt.barh(names, [results[n].mean() for n in names], xerr=[results[n].std() for n in names], color='C0')
plt.xlim(0.85, 1.0); plt.xlabel('cross-validated F1'); plt.title('Six classifiers, same data'); plt.show()Logistic regression F1 = 0.985 ± 0.009
k-NN (k=7) F1 = 0.978 ± 0.017
Random forest F1 = 0.970 ± 0.007
Gradient boosting F1 = 0.966 ± 0.009
Gaussian Naive Bayes F1 = 0.952 ± 0.021
Decision tree F1 = 0.942 ± 0.015

The final test¶
We keep the best model by cross-validation, fit it on the whole training set, and look at the test set once.
best_name = max(results, key=lambda n: results[n].mean())
best = models[best_name].fit(X_train, y_train)
print('best model:', best_name)
print(classification_report(y_test, best.predict(X_test), target_names=['malignant', 'benign']))
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
ConfusionMatrixDisplay.from_estimator(best, X_test, y_test, display_labels=['malignant', 'benign'], ax=axes[0], colorbar=False)
proba = best.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, proba)
axes[1].plot(fpr, tpr, label=f'AUC = {roc_auc_score(y_test, proba):.3f}'); axes[1].plot([0, 1], [0, 1], '--', color='gray')
axes[1].set_xlabel('false-positive rate'); axes[1].set_ylabel('true-positive rate (recall)'); axes[1].legend(); axes[1].set_title('ROC curve')
plt.tight_layout(); plt.show()best model: Logistic regression
precision recall f1-score support
malignant 0.94 0.94 0.94 53
benign 0.97 0.97 0.97 90
accuracy 0.96 143
macro avg 0.96 0.96 0.96 143
weighted avg 0.96 0.96 0.96 143

Key Takeaways¶
From-scratch versions and scikit-learn agree: the libraries do what the chapter’s formulas say.
Scale features for gradient descent, logistic regression and k-NN, inside a pipeline.
Choose depth, and other hyperparameters with cross-validation; touch the test set once.
On tabular data, ensembles (random forests, gradient boosting) are strong defaults, but a well-tuned linear model is often close behind and easier to explain.