Source

Module 4 · Your first learning algorithms: linear regression, softmax regression and decision trees

Time: about 7 hours with readings · Lab: python course/labs/lab04_softmax_regression.py

You need: Module 1 §3–§4 (the meals example; scores and probabilities) and Module 2 Part A (functions and parameters, e and ln, dot products and matrices, derivatives, the chain rule and gradient descent), plus §7–§8 (softmax and cross-entropy) and §9 (mean and standard deviation).

By the end you can:

  • fit a straight-line model to data by gradient descent and by formula, and say why inputs are standardised first;
  • turn a score into a yes/no probability (logistic regression) and read its weights;
  • write down a linear classifier for K classes and explain what its weights mean;
  • derive, step by step, the gradient that trains it ("prediction minus truth");
  • explain how a decision tree is learned, and how gradient boosting builds a strong model out of many small trees;
  • explain why TrayCheck's final layer is softmax regression on learned features.

Why this matters

In TrayCheck. The last layer of TrayCheck's model is

output = tf.keras.layers.Dense(class_count, activation="softmax", name="food_class")(x)

trained with the loss sparse_categorical_crossentropy. That is softmax regression (§3). Its input x is not pixels: it's 96 numbers that the rest of the network learned to compute from the photo. Understand this layer completely and the rest of deep learning is "how to compute better features to feed it".

In the internship. The other two models in this module, linear and logistic regression and gradient-boosted trees, are the workhorses of the "predictive analytics" in the position description: forecasting meals needed, predicting which trays come back mostly uneaten. They work well on tables of numbers, train in seconds and (in the regression case) are easy to explain. When a vendor proposes a complex model for a table-shaped problem, a good question is whether they compared it with these as baselines (Module 12 §6). For the interview, the ideas in §1, §2 and §6 matter more than the derivation in §4.


1. Linear regression: fitting a line, properly

The problem again

Module 1 §3 predicted meals from patients with the family meals = w × patients + b, and found w = 1, b = 4 by trying values. Now do it properly: choose a loss that suits gradient descent, compute its slopes, and let the algorithm find the best values.

Day Patients x Meals needed y
1 10 14
2 20 23
3 30 35
4 40 44

The loss: mean squared error

Module 1 used the average miss. The standard choice for regression squares each miss instead:

\[\text{MSE}(w, b) = \frac{1}{n}\sum_{i=1}^{n} \big(w x_i + b - y_i\big)^2\]

the mean squared error. Three reasons to square:

  1. Smooth slopes. The absolute miss has a sharp corner at zero, where its slope jumps from −1 to +1. A square curves smoothly through zero, so gradient descent always has a sensible slope.
  2. Big misses count more. A miss of 10 costs 100, ten times a miss of √10 ≈ 3. For forecasting, one disastrous day usually matters more than several slightly-off days.
  3. There's a clean formula for the best fit (below), which is why "least squares" has been the default since the early 1800s.

Rule B from Module 1 (w = 1, b = 4) misses by 0, 1, −1 and 0, so its MSE is (0 + 1 + 1 + 0)/4 = 0.5.

The slopes

Each term of the MSE is (miss)², where miss = w x + b − y. By the chain rule (Module 2 §4), the slope of (miss)² is 2 × miss × (slope of the miss), and the miss changes by x when w moves by 1, and by 1 when b moves by 1. Averaging over the days:

\[\frac{\partial\,\text{MSE}}{\partial w} = \frac{2}{n}\sum_i \text{miss}_i \cdot x_i \qquad \frac{\partial\,\text{MSE}}{\partial b} = \frac{2}{n}\sum_i \text{miss}_i\]

Read them in words: each example pushes w by (its miss) × (its input). A day the rule under-predicts (negative miss) pushes w up, and days with more patients push harder. Keep this "miss × input" shape in mind; it comes back in §4.

Gradient descent, and why inputs are standardised

Start at w = 0, b = 0. Every prediction is 0, the misses are −14, −23, −35, −44, and the slope for w is (2/4) × (−14×10 − 23×20 − 35×30 − 44×40) = −1,705. The slope for b is only −58.

That imbalance is a problem. The slope for w is huge because the inputs are large numbers (10 to 40). A learning rate small enough to keep w from overshooting is far too small to move b:

Inputs Learning rate After 10 steps After 100 steps After 10,000 steps
Raw patients 0.002 diverged (MSE above 10⁹)
Raw patients 0.001 MSE 2.4 MSE 2.3 MSE 0.45 (w 1.02, b 3.4)
Standardised 0.1 MSE 11.6 MSE 0.45 (done)

The fix is to standardise each input: subtract its mean and divide by its standard deviation (Module 2 §9), so it is centred on 0 with a spread of 1. Here patients have mean 25 and SD 11.2, so 10, 20, 30, 40 become −1.34, −0.45, 0.45, 1.34. Now both slopes are of similar size, one learning rate suits both, and training finishes in 100 steps instead of 10,000. Standardising inputs is the first thing to do before gradient descent on any table of numbers. (Pixels are rescaled for the same reason: TrayCheck maps 0–255 to −1…1.)

The exact answer: least squares

For this one model there is also a direct formula, no searching needed. With x̄ and ȳ the means of the inputs and outputs:

\[w = \frac{\sum_i (x_i - \bar x)(y_i - \bar y)}{\sum_i (x_i - \bar x)^2}, \qquad b = \bar y - w\,\bar x\]

Here x̄ = 25, ȳ = 29; the top sum is (−15)(−15) + (−5)(−6) + (5)(6) + (15)(15) = 510, the bottom is 225 + 25 + 25 + 225 = 500. So w = 1.02 and b = 29 − 1.02 × 25 = 3.5. Its MSE is 0.45, a little better than rule B's 0.5, and it's what gradient descent converged to above. On the held-back days it predicts 29.0 (actual 28) and 39.2 (actual 40). This is the least squares line, the same "trend line" a spreadsheet draws.

So why ever use gradient descent? Because the formula exists only for this simple family. For logistic regression, softmax regression and every neural network, there is no formula, and gradient descent is how they're fitted.

More inputs

Real forecasts use several inputs: patients, whether it's a weekend, the menu cycle, last week's count. With d inputs, the prediction is a dot product plus a bias (Module 2 §3):

\[\hat y = w_1 x_1 + w_2 x_2 + \dots + w_d x_d + b = w \cdot x + b\]

Each weight says how much its input moves the prediction, holding the others fixed: "each extra patient adds about 1.02 meals". That readability is a large part of why linear regression is still everywhere in predictive analytics.


2. Logistic regression: predicting yes or no

From a score to a probability

Now predict a yes/no outcome: will this tray come back more than half full? A weighted sum z = w · x + b can be any number, but a probability must lie between 0 and 1. The sigmoid function squashes any number into that range:

\[\sigma(z) = \frac{1}{1 + e^{-z}}\]
z −4 −2 −1 0 1 2 4
σ(z) 0.018 0.119 0.269 0.5 0.731 0.881 0.982

Large negative scores give probabilities near 0, large positive ones near 1, and a score of 0 means 50/50. (Check one: e⁻⁰ = 1, so σ(0) = 1/2.) The model is: probability of "yes" = σ(w · x + b). This is logistic regression, and it is trained exactly like TrayCheck: minimise −ln(probability given to the correct answer) by gradient descent (Module 2 §8).

Reading the weights: odds

The odds of an event are its probability divided by the probability it doesn't happen: a probability of 0.8 is odds of 0.8/0.2 = 4 (4 to 1). A little algebra on the sigmoid shows that ln(odds) = z, the weighted sum itself. So adding 1 to an input adds its weight w to ln(odds), which multiplies the odds by eʷ. A weight of 0.7 means "each extra unit of this input multiplies the odds of a mostly-uneaten tray by e⁰·⁷ ≈ 2". That is how logistic regression results are usually reported in health research, and why the model is popular there.


3. Softmax regression: many classes

With K classes instead of two, give each class its own weight vector and bias and compute a score per class. For an input x with D numbers, stack the K weight vectors as the columns of a matrix W of shape (D, K), and the biases into a vector b of length K:

\[z = xW + b\]

Then apply softmax to turn the K scores into probabilities (Module 2 §7), predict the class with the highest probability, and train with cross-entropy:

\[L = -\ln p_y \quad \text{(for one example whose correct class is } y\text{)}\]

This is softmax regression (also called multinomial logistic regression). With K = 2 it is exactly logistic regression: softmax of the two scores [z, 0] gives eᶻ / (eᶻ + 1) for the first class, which is σ(z).

The lab's problem. Lab 4 classifies 8 × 8 pixel images of handwritten digits (0–9), so D = 64 pixel values and K = 10. Each column of W acts as a template: a class's score is the dot product of the image with that class's template, which is large when the image's bright pixels line up with the template's large weights. The lab saves the learned templates as images (course/labs/output/lab04_weights.png): the template for "0" is a ring, the one for "1" a vertical stroke. Nobody drew them; gradient descent did.


4. The gradient, step by step

Training needs the slope of the loss with respect to every weight. This section derives it in three steps, each using one rule from Module 2.

Step 1: write the loss in terms of the scores. By softmax, the correct class's probability is its exponentiated score divided by the total S:

\[p_y = \frac{e^{z_y}}{S}, \qquad S = \sum_j e^{z_j}\]

A logarithm turns a division into a subtraction (since ln(a × b) = ln a + ln b, it follows that ln(a / b) = ln a − ln b), and the log of e raised to a power is just that power. So:

\[L = -\ln p_y = -z_y + \ln S\]

Step 2: the slope with respect to one score zₖ. Take the two parts separately.

  • The first part, minus the correct class's score: its slope with respect to zₖ is −1 if k is the correct class, and 0 otherwise (the other scores don't appear in it).
  • The second part, ln S: chain rule. The slope of ln is 1/(its input). Only one term of the sum S contains zₖ, and eˣ is its own slope, so S moves at the rate of that term. The slope is therefore that term divided by S, which is exactly the softmax probability pₖ.

Together:

\[\frac{\partial L}{\partial z_k} = p_k - [k = y]\]

where [k = y] is 1 for the correct class and 0 otherwise. In words: the slope on each score is "predicted probability minus truth".

Worked check. Three classes, scores z = [2, 1, 0], correct class the first. Softmax gives p = [0.665, 0.245, 0.090], so the slopes are [0.665 − 1, 0.245, 0.090] = [−0.335, 0.245, 0.090]. Nudging each score by 0.000001 and measuring the change in loss gives −0.3348, 0.2447 and 0.0900. Gradient descent subtracts the slope, so it raises the correct score and lowers the others, the most-probable wrong class most of all.

The vector of truths, with a 1 at the correct class and 0 elsewhere, is called one-hot: for the example, [1, 0, 0]. So the slopes on all the scores at once are p − one-hot.

Step 3: from scores to weights. Each score is a weighted sum of the inputs plus a bias:

\[z_k = \sum_d x_d W_{dk} + b_k\]

So nudging the weight that connects input d to class k moves score zₖ by the size of that input (and moves no other score), and nudging the bias moves it by 1. Chain rule again:

\[\frac{\partial L}{\partial W_{dk}} = x_d\,(p_k - [k = y]), \qquad \frac{\partial L}{\partial b_k} = p_k - [k = y]\]

Input times error, for every input–class pair: the same "miss × input" shape as linear regression in §1. Written for all d and k at once, that table of products is xᵀ(p − one-hot), where xᵀ is x written as a column (the transpose, Module 2 §3), so multiplying a column of D inputs by a row of K errors gives the full (D, K) table. For a batch of n examples (the rows of a matrix X), sum over the batch and divide by n. In code (lab04):

P = softmax(X @ W + b)          # (n, K) predicted probabilities
G = P.copy()
G[np.arange(n), y] -= 1         # P - onehot(y): subtract 1 at each row's correct class
G /= n                          # average over the batch
dW = X.T @ G + l2 * W           # plus the slope of an L2 penalty (Module 6)
db = G.sum(axis=0)
W -= lr * dW; b -= lr * db      # one step of gradient descent

The same "p minus one-hot" signal is where backpropagation starts in every classifier, including TrayCheck's (Module 5).


5. Doing it properly: three habits

1. Standardise using training statistics only. The lab subtracts each pixel's training-set mean and divides by its training-set standard deviation, then applies those same numbers to validation and test data. Computing them on all the data would let information about the test set into training (leakage, Module 9). TrayCheck's equivalent, preprocess_input, uses fixed constants and so can't leak.

2. Check your gradient. When you derive a gradient by hand, compare it with nudging, as in the worked check above. Relative differences around 10⁻⁷ or smaller mean the formula is right. The lab gets about 10⁻¹⁰:

W[ 4,2]: formula  0.10431722  nudging  0.10431722  relative error 1.3e-10

3. Touch the test set once. Training watches training loss and validation accuracy; the test set is used at the very end.

The lab, run

step   0  train loss 2.3026  train acc 0.099  val acc 0.100
step  25  train loss 0.2552  train acc 0.959  val acc 0.925
step 100  train loss 0.1357  train acc 0.981  val acc 0.964
step 200  train loss 0.1063  train acc 0.991  val acc 0.964

our softmax regression: test accuracy 0.969
scikit-learn LogisticRegression: test accuracy 0.964
  • The starting loss is 2.3026 = ln(10): with all-zero weights every class gets probability 1/10, and −ln(0.1) = 2.3026. Checking the first loss against ln(K) is a quick sanity check for any classifier.
  • 50 lines of NumPy match scikit-learn. There's no magic in the library, just this algorithm with a better optimiser.
  • Training accuracy (99.1%) ends above validation (96.4%): a small generalisation gap, the subject of Module 6.

6. A different kind of model: decision trees and gradient boosting

Everything so far has been a weighted sum. For tables of numbers, the other model family you will meet constantly is built from decision trees. Module 12's meal forecast, which beat its baseline, is one of these.

A decision tree is a learned flowchart

A tree asks a yes/no question about one input, then another question on each branch, and so on; each final branch (a leaf) predicts the average of the training examples that reached it. Eight days of data:

Day 1 2 3 4 5 6 7 8
Patients 20 22 30 32 20 22 30 32
Weekend? no no no no yes yes yes yes
Meals needed 24 26 35 36 19 21 28 30

How the first question is chosen. Predicting every day by the overall average (27.4) leaves a total squared error of 263.9. The algorithm tries every possible question, splits the days, predicts each side by its own average, and keeps the question that leaves the least squared error:

Candidate question Left side (yes) Right side (no) Total squared error
Weekend? 19, 21, 28, 30 (avg 24.5) 24, 26, 35, 36 (avg 30.25) 197.8
Patients ≤ 21? 24, 19 (avg 21.5) the other six (avg 29.3) 171.8
Patients ≤ 25? 24, 26, 19, 21 (avg 22.5) 35, 36, 28, 30 (avg 32.25) 73.8
Patients ≤ 31? six days (avg 25.5) 36, 30 (avg 33) 179.5

"Patients ≤ 25?" wins. The algorithm then repeats the search inside each side, and "Weekend?" wins on both. The finished tree of depth 2:

                 patients <= 25?
              yes /           \ no
          weekend?            weekend?
        yes /   \ no        yes /   \ no
     predict 20  predict 25  predict 29  predict 35.5

Its total squared error is 6.5, down from 263.9. Nobody wrote "weekends need fewer meals"; the search found it.

Strengths: no need to standardise; handles yes/no, category and number inputs together; a small tree can be read and checked by a person. Weakness: a deep tree keeps splitting until each leaf holds one example, which is memorisation (Module 1 §3), while a shallow tree is too crude. A single tree is rarely the best model.

Many small trees: gradient boosting

Gradient boosting builds a strong model by adding small trees one at a time, each one fitted to the errors that remain:

  1. Start by predicting the average for every day: 27.375. Mean squared error: 33.0.
  2. Compute each day's residual (actual minus prediction). Fit a one-question tree to the residuals. It picks "patients ≤ 25?" and predicts −4.875 on the yes side and +4.875 on the no side. Add that to the predictions: now 22.5 or 32.25. Mean squared error: 9.2.
  3. Compute the new residuals (for example day 1: 24 − 22.5 = +1.5; day 5: 19 − 22.5 = −3.5). Fit another one-question tree to them. It picks "Weekend?": +2.875 on weekdays, −2.875 at weekends. Add it. Mean squared error: 0.95.

Each tree corrects what the trees before it got wrong. In practice each correction is shrunk (say, multiplied by 0.1, a learning rate) and hundreds of small trees are added, with validation data used to decide when to stop, exactly as in Module 6's early stopping. The name comes from the fact that residuals are the (negative) slope of the squared error with respect to the predictions, so each tree is a step of gradient descent taken in "prediction space".

Where it's used: gradient-boosted trees (in libraries such as XGBoost and LightGBM, or scikit-learn's version) are usually the strongest off-the-shelf model for tables of numbers: demand forecasts, risk scores, waste predictions. They are a poor fit for raw photos, where single pixels are meaningless features (Module 1 §5); there, deep learning wins.

Model Best for Explainability In this course
Linear / logistic regression Tables; a strong, simple baseline High: one weight per input §1–§2; Module 12 baselines
Gradient-boosted trees Tables, when interactions matter Medium: needs tools to explain §6; Module 12's forecast
Softmax regression on learned features Images, text, sound Low for the features, high for the last layer §3; TrayCheck's head

How this connects to TrayCheck

photo ──► [ MobileNetV2: 2.26 M parameters ] ──► 1280 features ──► Dense(96, ReLU) ──► Dropout ──► Dense(4) + softmax
          learned feature extractor                                  small learned layer           softmax regression
          (pre-trained on ImageNet)                                                                (388 parameters)

On 8 × 8 digits, raw pixels are good enough features for a linear model to reach 97%. On 96 × 96 food photos they are hopeless: the same dish photographed from a different angle shares almost no pixel values. Deep learning's contribution is the box on the left: a function that turns pixels into features where the classes become easy to separate, almost linearly. Modules 5–8 build up to it.


Check your understanding

1. Rule B (w = 1, b = 4) has MSE 0.5; the least squares line (w = 1.02, b = 3.5) has 0.45. Why can't any other line do better than 0.45 on these four days?

The least squares formula gives the exact minimum of the MSE for this family of rules: it is where both slopes are zero. Gradient descent, run long enough, arrives at the same point.

2. Why does gradient descent struggle on raw patient counts, and what fixes it?

The slope for w is multiplied by the inputs, so with inputs of 10–40 it is about 30 times larger than the slope for b. A learning rate safe for w barely moves b. Standardising the inputs (mean 0, SD 1) makes the slopes comparable, and training converges in about 100 steps instead of 10,000.

3. A logistic regression for "tray mostly uneaten" has a weight of 0.7 on "texture-modified diet". What does that mean?

Being on a texture-modified diet adds 0.7 to the log-odds, so it multiplies the odds of a mostly uneaten tray by e⁰·⁷ ≈ 2, holding the other inputs fixed.

4. A model gives probabilities [0.1, 0.6, 0.2, 0.1] and the correct class is the third. What is the slope on each of the four scores?

p − one-hot = [0.1, 0.6, 0.2 − 1, 0.1] = [0.1, 0.6, −0.8, 0.1]. Gradient descent raises the third score and lowers the others, the second most.

5. Why is the first training loss of a 10-class model with zero weights equal to 2.3026?

All scores are 0, so softmax gives 1/10 to every class, and the loss is −ln(0.1) = ln(10) ≈ 2.3026. If an untrained model's loss is far from ln(K), something is wrong.

6. What do the columns of W in a linear classifier represent?

One template per class. The score for a class is the dot product between the input and that class's template, plus a bias.

7. Why compute the standardisation mean and standard deviation on the training set only?

Anything learned from data, even a mean, should come from training data only. Otherwise information from the validation or test set leaks into the model, and the evaluation becomes optimistic.

8. How does a decision tree choose its first question?

It tries every candidate question (every input, every split point), predicts each side by its own average, and keeps the question that leaves the smallest total squared error. Then it repeats inside each side.

9. In gradient boosting, what is each new tree trained to predict?

The residuals: the part of each target that the trees so far haven't explained. Adding its (shrunk) predictions moves every prediction towards the truth, like a gradient descent step.

10. TrayCheck's food_class layer has 388 parameters. Where does that number come from?

96 inputs × 4 classes = 384 weights, plus 4 biases.


Go deeper

The module above is self-contained. These offer a second explanation, more examples, or the statistics behind the models.

Recommended (free)

  • James, Witten, Hastie, Tibshirani & Taylor, An Introduction to Statistical Learning with Python (ISLP): Chapter 3, Linear Regression (§3.1–3.2), Chapter 4, Classification (§4.3, logistic regression) and Chapter 8, Tree-Based Methods (§8.1 trees, §8.2.3 boosting). The best statistics-side companion. statlearning.com
  • Stanford CS231n notes, Linear classification: templates and the softmax classifier, with interactive pictures. cs231n.github.io/linear-classify
  • Google Machine Learning Crash Course: the Linear regression and Logistic regression modules, with short exercises. developers.google.com/machine-learning/crash-course

Optional

  • Dive into Deep Learning, chapters Linear Neural Networks for Regression and …for Classification, including softmax regression from scratch. d2l.ai
  • Stanford CS229 lecture notes (Andrew Ng): linear regression, logistic regression and softmax as generalised linear models. cs229.stanford.edu
  • StatQuest (Josh Starmer), videos on Decision Trees and Gradient Boost (parts 1–2): the residual-fitting idea step by step, on small tables like §6's.
  • Andrej Karpathy, A Recipe for Training Neural Networks (2019): includes "verify loss at initialisation". karpathy.github.io/2019/04/25/recipe

Interview angle

"The classification layer is softmax regression: a linear score per dish turned into probabilities by softmax, trained with cross-entropy. Its gradient is simply predicted probability minus the true label, times the input. What deep learning adds is the feature extractor in front of it.

For predictive analytics on tables, like meals needed per ward, I'd start with linear or logistic regression as a baseline, standardise the inputs, and then try gradient-boosted trees, which build many small trees each correcting the last one's errors. The question is always whether the more complex model beats the simple one on later dates by enough to matter."