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 — Implementation: Supervised Learning in Practice

Open in Colab

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

  1. Linear regression: normal equation and gradient descent

  2. Logistic regression with gradient descent

  3. A decision tree (ID3) on the tennis data

  4. k-nearest neighbours, and the choice of k

  5. Naive Bayes for spam

  6. Comparing models with cross-validation, a confusion matrix and an ROC curve

1. Linear Regression

We generate 200 noisy points from y=4+3x1−2x2+noisey = 4 + 3x_1 - 2x_2 + \text{noise} and recover the weights two ways.

normal equation  : [ 3.98   3.047 -2.064]
gradient descent : [ 3.98   3.047 -2.064]
scikit-learn     : [ 3.98   3.047 -2.064]
<Figure size 700x400 with 1 Axes>

All three methods agree on weights close to the true (4,3,−2)(4, 3, -2); 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.

from scratch : test accuracy 0.965
scikit-learn : test accuracy 0.958
<Figure size 700x400 with 1 Axes>

3. A Decision Tree from Scratch (ID3)

We rebuild the tree of the chapter’s worked example and check the information gains.

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'}}}}
No
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:

test accuracy: 0.978
<Figure size 1100x500 with 1 Axes>

Depth and overfitting

Training accuracy keeps rising with depth; validation accuracy stops improving, and then falls a little. That gap is overfitting.

<Figure size 700x400 with 1 Axes>
best depth by cross-validation: 5

4. k-Nearest Neighbours

from scratch (k=5): 0.951
scikit-learn (k=5): 0.951
without scaling   : 0.916
<Figure size 700x400 with 1 Axes>
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.

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 P(spam)=0.32P(\text{spam}) = 0.32, 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.

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
<Figure size 700x400 with 1 Axes>

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

<Figure size 1100x400 with 2 Axes>

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, kk 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.