Regression and Classification

How models predict a number (regression) or a category (classification), how a bias, the sigmoid and a threshold work, and how to choose between them.

15 minLesson 3 of 7
On this page
  1. How regression works
  2. How classification works
  3. Training a classifier
  4. Binary, multiclass and ordered outputs
  5. Choosing the loss for regression
  6. Pitfalls and nuances
  7. What this changes in practice
  8. What to practise next

Regression is a model that predicts a number, such as the rent for a flat or the minutes a delivery will take. Classification is a model that picks a category, such as spam or not spam. Most practical machine learning is one of the two, and the choice decides what the model outputs, which loss it trains on and how you judge its answers.

If you pick the wrong one, the model still trains, but its output is awkward to use. A line fitted to spam labels of 0 and 1 produces values like 1.4 and −0.3, and a classifier used to guess a rent can only choose between fixed price bands. Both are trained by gradient descent on labelled examples, but they use different output functions and different loss functions.

How regression works

In How Models Learn, the model minutes = w × km was forced to pass through zero. That is a poor fit for many problems. Take these three flats:

Size (m²)Monthly rent
30800
501,100
701,400

The best line through zero is about rent = 21.33 × size. It predicts 640 for the smallest flat and 1,493 for the largest, so it is too low and then too high. The model needs a second parameter, the bias b, which lets the line start at any height:

rent = w × size + b

Gradient descent now adjusts two values. The gradient for w is still the average of 2 × error × input. Changing b raises every prediction by the same amount, so its gradient is the average of 2 × error. The lowest loss is at w = 15 and b = 350, which fits all three flats exactly: 15 × 30 + 350 = 800. The 60 m² flat is then predicted at 15 × 60 + 350 = 1,250. A real model has one weight for each feature, such as size, floor and distance to the station, plus one bias.

How classification works

A classifier starts the same way, with a score computed from the features. For spam detection with one feature, the number of links, the score is w × links + b. This score can be any number, such as −2.3 or 4.4, so it cannot be read as a probability directly. The sigmoid function converts it into a number between 0 and 1:

P(spam) = 1 / (1 + e−score)

Here e is a fixed constant, about 2.718. A score of 0 gives exactly 0.5, large positive scores give values close to 1, and large negative scores give values close to 0. The output never reaches 0 or 1, so the model never claims to be completely certain.

size (m²) rent Regression 0.5 1 0 links in message (0 to 5) Classification
Left: regression draws a line through numbers. Right: classification fits an S-shaped curve to examples labelled 0 (not spam) or 1 (spam), read as a probability.

Training on the seven labelled messages in the code below gives w ≈ 1.34 and b ≈ −2.34. The trace uses these rounded values, so its probabilities can differ from the model's by 0.01.

Scoring messages by number of linksUse the arrows or ← → keys
score = 1.34 * links - 2.34p = 1 / (1 + e^(-score))if p >= threshold: spamelse: not spam
  1. links
    00msg
    11
    22
    33
    44
    55
    score
    0-2.34
    1
    2
    3
    4
    5
    P(spam)
    00.09
    1
    2
    3
    4
    5
    threshold
    0.5
    flagged
    0

    10 links: the score is −2.34, so p is 0.09. The message is not spam.

  2. links
    00
    11msg
    22
    33
    44
    55
    score
    0-2.34
    1-1
    2
    3
    4
    5
    P(spam)
    00.09
    10.27
    2
    3
    4
    5
    threshold
    0.5
    flagged
    0

    21 link: the score is 1.34 − 2.34 = −1.00, so p is 0.27. The message is not spam.

  3. links
    00
    11
    22msg
    33
    44
    55
    score
    0-2.34
    1-1
    20.34
    3
    4
    5
    P(spam)
    00.09
    10.27
    20.58
    3
    4
    5
    threshold
    0.5
    flagged
    1

    32 links: the score is 0.34, so p is 0.58. The message is flagged, but only just, so the model is unsure.

  4. links
    00
    11
    22
    33msg
    44
    55
    score
    0-2.34
    1-1
    20.34
    31.68
    4
    5
    P(spam)
    00.09
    10.27
    20.58
    30.84
    4
    5
    threshold
    0.5
    flagged
    2

    43 links: the score is 1.68 and p is 0.84, so the message is flagged as spam.

  5. links
    00
    11
    22
    33
    44msg
    55
    score
    0-2.34
    1-1
    20.34
    31.68
    43.02
    5
    P(spam)
    00.09
    10.27
    20.58
    30.84
    40.95
    5
    threshold
    0.5
    flagged
    3

    54 links: the score is 3.02 and p is 0.95. Each link adds the same 1.34 to the score, but the probability grows more slowly as it nears 1.

  6. links
    00
    11
    22
    33
    44
    55msg
    score
    0-2.34
    1-1
    20.34
    31.68
    43.02
    54.36
    P(spam)
    00.09
    10.27
    20.58
    30.84
    40.95
    50.99
    threshold
    0.5
    flagged
    4

    65 links: the score is 4.36 and p is 0.99. At a threshold of 0.5, four of the six messages are flagged.

  7. links
    00
    11
    22
    33
    44
    55
    score
    0-2.34
    1-1
    20.34
    31.68
    43.02
    54.36
    P(spam)
    00.09
    10.27
    20.58
    30.84
    40.95
    50.99
    threshold
    0.9
    flagged
    2

    7Losing a real message costs more than seeing one spam, so the threshold is raised to 0.9. Now only the messages with 4 and 5 links are flagged. The model is the same, but the decision is different.

1 / 7

A model that computes a score from the features, passes it through a sigmoid and reads the result as a probability is called logistic regression, despite the word "regression" in its name. The model learns the probability from data. You choose the threshold, which is the probability above which a message is flagged, based on what each kind of mistake costs. Because the sigmoid passes 0.5 exactly when the score is 0, a threshold of 0.5 puts the decision boundary where w × links + b = 0.

Training a classifier

Squared error works badly together with a sigmoid. When the model is confidently wrong, the sigmoid is nearly flat, so the gradient is tiny and learning is very slow. Classifiers therefore use log loss, also called cross-entropy, which punishes confident mistakes heavily. For a real message, predicting a spam probability of 0.99 costs about five times as much as predicting 0.6.

With log loss, the gradient for each weight is the average of (p − label) × input, where the label is 1 for spam and 0 otherwise. This has the same form as in regression: the error multiplied by the input.

function sigmoid(z) {
  return 1 / (1 + Math.exp(-z));
}
 
// Learn w and b for: P(spam) = sigmoid(w * links + b)
function trainSpam(links, spam, rate, steps) {
  let w = 0;
  let b = 0;
  for (let s = 0; s < steps; s++) {
    let gradW = 0;
    let gradB = 0;
    for (let i = 0; i < links.length; i++) {
      const p = sigmoid(w * links[i] + b);
      const error = p - spam[i];      // spam[i] is 1 or 0
      gradW += error * links[i];
      gradB += error;
    }
    w -= rate * gradW / links.length;
    b -= rate * gradB / links.length;
  }
  return { w, b };
}
 
trainSpam([0, 1, 1, 2, 3, 4, 5], [0, 0, 1, 0, 1, 1, 1], 0.5, 2000);
// { w: 1.34..., b: -2.34... }
import math
 
def sigmoid(z):
    return 1 / (1 + math.exp(-z))
 
def train_spam(links, spam, rate, steps):
    """Learn w and b for: P(spam) = sigmoid(w * links + b)."""
    w, b = 0.0, 0.0
    for _ in range(steps):
        grad_w = grad_b = 0.0
        for x, y in zip(links, spam):
            p = sigmoid(w * x + b)
            error = p - y            # y is 1 or 0
            grad_w += error * x
            grad_b += error
        w -= rate * grad_w / len(links)
        b -= rate * grad_b / len(links)
    return w, b
 
train_spam([0, 1, 1, 2, 3, 4, 5], [0, 0, 1, 0, 1, 1, 1], 0.5, 2000)
# (1.34..., -2.34...)

The training data contains a 1-link message that is spam and a 2-link message that is not, so no threshold classifies every example correctly. The learned probabilities reflect that mix, which is why the model gives a middling value for 2 links.

Binary, multiclass and ordered outputs

Two categories

With two categories, such as spam or not spam, the model outputs one probability and you apply a threshold. This is the case the sigmoid handles. The model's job is to rank messages by how likely they are to be spam, and the threshold is a separate decision that you can change at any time without retraining.

More than two categories

To sort support tickets into billing, bug or account, the model computes one score for each category, each with its own weights. Softmax turns the scores into probabilities that add up to 1. For scores of 2, 1 and 0, the probabilities are about 0.67, 0.24 and 0.09, and the highest one wins. Language models use the same step to pick the next token, as described in Sampling and Temperature. When no category is clearly ahead, the better design is often to send the ticket to a person instead of taking the top answer.

Ordered values such as ratings

A star rating from 1 to 5 can be treated either way. As classification, each star is a separate category, and the model has no idea that 4 is closer to 5 than to 1. As regression, the model keeps the order and can output 3.5, but you must round or interpret that value. Choose regression when an answer that is close to correct is still useful, and classification when only the exact answer counts.

Choosing the loss for regression

Regression is usually trained on squared error, which is what the gradients above use. Squared error penalises a large miss much more than a small one, so a single wrong label, such as a flat listed at ten times its real rent, can pull the whole line towards it. Mean absolute error, the average of the absolute differences, grows only in proportion to the miss and is less affected by such outliers. Use squared error when large misses are genuinely much worse than small ones, and absolute error when the data contains occasional bad values you do not want to dominate the fit.

Pitfalls and nuances

What this changes in practice

Start by looking at what the answer will be used for. If the next step needs a quantity, such as a price, a duration or a count, use regression. If the next step is a choice between options, use classification and keep the probability, because it lets you set the threshold, rank the results and send uncertain cases to a person.

The same distinction applies when you use a language model for a task. Asking it to label a message as one of a fixed list of categories is classification, so list the allowed labels in the prompt and check that the reply is one of them. Asking it to estimate a quantity is regression, and the estimates need to be compared with real values before you rely on them.

Try it: Number or category?

For each task, say whether it is regression or classification, and what the model's output looks like.

Show a sample answer
  1. This is regression, and the output is a number such as 18.5 °C.
  2. This is classification with two categories. The output is a probability of disease, which you compare with a threshold.
  3. This is classification with five categories. Softmax gives one probability for each team. You pick the highest, or ask a person when no team is clearly ahead.
  4. This is regression, and the output is a number of minutes.
  5. This can be either. As classification, each star is a category and the model never says 3.5. As regression, it can say 3.5 and it keeps the order, so 4 is closer to 5 than to 1. Choose by whether an answer like "almost 4" is useful to you.

A quick test is to ask whether the gap between two answers means something. If it does, the task is usually regression.

Quick check

A classifier's score for a message is exactly 0. What probability does the sigmoid give?

Why add a bias b to the rent model?

You raise a spam filter's threshold from 0.5 to 0.9 without retraining. What changes?

Why code the colours red, green and blue as three yes-or-no features instead of 1, 2 and 3?

What to practise next

To code one gradient step for a line with a bias, try Delivery Time Nudge. Then Overfitting and Evaluation shows how to test a model honestly and which numbers to look at besides percent correct.