Logistic Regression

How a linear model becomes a principled probability model for yes or no decisions.

Why Linear Regression Fails

Linear regression predicts continuous numbers. That works when the target is a price, a temperature, or a number of sales. Many prediction problems ask for a yes or no answer instead.

  • Will this email be spam?
  • Will this customer cancel?
  • Is this transaction fraudulent?

This is binary classification. We usually encode the two classes as 00 and 11. It is tempting to fit a line and treat the output as the probability of class 11.

y^=wTx+b\hat{y}=w^T x+b

The problem is that a line can output any real number. A prediction of 1.3-1.3 cannot mean negative probability. A prediction of 2.42.4 cannot mean a probability greater than one. Probabilities must always stay between zero and one.

0p10 \le p \le 1

We need a model that keeps the useful part of linear regression while producing valid probabilities. Logistic regression begins by changing what the line is allowed to model.

Log-Odds

Logistic regression does not model the probability directly. It models the log-odds. To see why, start with odds.

odds=p1p\text{odds}=\frac{p}{1-p}

If an event has probability p=0.8p=0.8, then the probability it happens is 0.80.8 and the probability it does not happen is 0.20.2. The odds are 0.8/0.2=40.8/0.2=4. The event is four times as likely to happen as not happen.

Odds are positive, but a linear model can be negative. Taking the logarithm gives log-odds, which can be any real number.

log(p1p)\log\left(\frac{p}{1-p}\right)

This is the modelling assumption. Linear regression assumes the target itself is a linear function of the features. Logistic regression assumes the log-odds of the positive class are a linear function of the features.

log(p1p)=wTx+b\log\left(\frac{p}{1-p}\right)=w^T x+b

This choice is attractive because probabilities are trapped between zero and one, while log-odds can move across the whole number line. A linear model naturally fits the log-odds scale.

Now we need to turn the log-odds back into a probability. Let z=wTx+bz=w^T x+b.

log(p1p)=z\log\left(\frac{p}{1-p}\right)=z
p1p=ez\frac{p}{1-p}=e^z
p=ez(1p)p=e^z(1-p)
p=ezezpp=e^z-e^z p
p+ezp=ezp+e^z p=e^z
p(1+ez)=ezp(1+e^z)=e^z
p=ez1+ezp=\frac{e^z}{1+e^z}
p=11+ezp=\frac{1}{1+e^{-z}}

This final expression is the sigmoid function. It is not chosen arbitrarily. It appears when we decide that a linear model should explain log-odds.

P(y=1)=11+ez,z=wTx+bP(y=1)=\frac{1}{1+e^{-z}},\qquad z=w^T x+b

The model can now output valid probabilities. The next question is how to choose the weights and bias so the probabilities match the labels we observed.

Interactive Demo

From line to probability: the sigmoid
valid probability rangeout of bounds0.5-0.500.511.5-2024681012xP(y=1|x)
Decision boundary4.00
σ(0)0.018
σ(5)0.731

Toggle the linear line to see how it extends beyond [0, 1], producing invalid probabilities. The sigmoid always stays within bounds.

Move the weight and bias sliders. The weight changes how sharply the probability moves from near zero to near one. The bias shifts the transition left or right.

Toggle the linear attempt. The straight line can leave the valid probability range, while the sigmoid always stays inside it.

Maximum Likelihood

A probability model should give high probability to what actually happened. This idea is maximum likelihood.

Suppose a model makes these predictions for three examples.

True labelModel predictionProbability of observed outcome
10.90.9
10.80.8
00.30.7

For the first two examples, the observed label is 11. The model assigned probabilities 0.90.9 and 0.80.8 to the observed outcome. For the third example, the model predicted p=0.3p=0.3 for class 11, but the observed label was 00. The probability assigned to what happened is therefore 10.3=0.71-0.3=0.7.

If the examples are treated as independent, the probability of seeing the whole dataset under this model is the product of those probabilities.

0.9×0.8×0.7=0.5040.9 \times 0.8 \times 0.7=0.504

For one observation, there is a compact way to select the right probability.

py(1p)1yp^y(1-p)^{1-y}

This works because the label is either 00 or 11. When y=1y=1, the first factor remains and the second factor becomes one.

p1(1p)0=pp^1(1-p)^0=p

When y=0y=0, the first factor becomes one and the second factor remains.

p0(1p)1=1pp^0(1-p)^1=1-p

Across a dataset, likelihood multiplies the probability assigned to every observed label.

L(w,b)=i=1npiyi(1pi)1yi\mathcal{L}(w,b)=\prod_{i=1}^{n}p_i^{y_i}(1-p_i)^{1-y_i}

Products of many probabilities become tiny very quickly because every factor is at most one. Tiny products are awkward for computers and hard to reason about. Logs solve this by turning products into sums.

log(ab)=loga+logb\log(ab)=\log a+\log b
logL(w,b)=i=1n[yilog(pi)+(1yi)log(1pi)]\log \mathcal{L}(w,b)=\sum_{i=1}^{n}\left[y_i\log(p_i)+(1-y_i)\log(1-p_i)\right]

We want the log-likelihood to be as large as possible. Most optimisation tools are written as minimisers, which means they search for the smallest value of an objective. To use the same tools, we minimise the negative log-likelihood instead.

logL(w,b)=i=1n[yilog(pi)+(1yi)log(1pi)]-\log \mathcal{L}(w,b)=-\sum_{i=1}^{n}\left[y_i\log(p_i)+(1-y_i)\log(1-p_i)\right]

Averaging over the number of examples gives binary cross-entropy. So cross-entropy is not a random penalty. It is exactly the negative log-likelihood for binary labels.

BCE=1ni=1n[yilog(pi)+(1yi)log(1pi)]\text{BCE}=-\frac{1}{n}\sum_{i=1}^{n}\left[y_i\log(p_i)+(1-y_i)\log(1-p_i)\right]

Cross-Entropy

Mean squared error treats probability mistakes too gently when the model is confidently wrong. Cross-entropy behaves like a betting score. The more confidence the model places on the wrong outcome, the more it should pay.

If the true label is 11, the loss for one prediction is log(p)-\log(p).

Predicted probabilityCross-entropy loss
0.90.105
0.50.693
0.12.303
0.014.605

A prediction of 0.90.9 is confident and correct, so the loss is small. A prediction of 0.010.01 is confidently wrong, so the loss is much larger. The model is being taught that confident mistakes are worse than uncertain mistakes.

Probability loss lab
01234500.250.500.751predicted probabilityloss
Cross-entropyMSE
Cross-entropy0.288
MSE0.063

Implementation

This implementation trains logistic regression with gradient descent. Each update moves the weights in the direction that reduces binary cross-entropy.

import numpy as np

class LogisticRegression:
    def __init__(self, lr=0.1, epochs=1000):
        self.lr = lr
        self.epochs = epochs

    def sigmoid(self, z):
        z = np.clip(z, -500, 500)
        return 1 / (1 + np.exp(-z))

    def fit(self, X, y):
        n, d = X.shape
        self.w = np.zeros(d)
        self.b = 0.0

        for _ in range(self.epochs):
            z = X @ self.w + self.b
            p = self.sigmoid(z)
            error = p - y

            self.w -= self.lr * (X.T @ error) / n
            self.b -= self.lr * np.sum(error) / n

    def predict_proba(self, X):
        return self.sigmoid(X @ self.w + self.b)

    def predict(self, X, threshold=0.5):
        return (self.predict_proba(X) >= threshold).astype(int)

    def binary_cross_entropy(self, X, y):
        p = np.clip(self.predict_proba(X), 1e-15, 1 - 1e-15)
        return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

Interview Discussion

IdeaLinear RegressionLogistic Regression
Prediction targetContinuous numberBinary class probability
OutputAny real valueA value between zero and one
ActivationNoneSigmoid
Loss functionMean squared errorBinary cross-entropy
Optimisation objectiveMinimise squared residualsMaximise likelihood or minimise negative log-likelihood
InterpretationExpected target valueProbability of class one
ApplicationsPrices, demand, measurementsSpam, churn, fraud, medical risk
Why is it called logistic regression if it is used for classification?

It learns a continuous probability through a regression style model on log-odds, then a threshold converts that probability into a class.

What is the main modelling assumption?

The log-odds of the positive class are linear in the input features.

Where does the sigmoid come from?

It comes from solving the log-odds equation for probability.

What is the decision boundary?

With threshold 0.5, the boundary is where the log-odds are zero, which gives w transpose x plus b equals zero.

What misconception should you avoid?

Logistic regression is not non-linear in the decision boundary. The sigmoid bends probabilities, but the boundary in feature space is still linear.

Active Recall

1. Explain why a straight line cannot be used directly as a probability.

2. Derive the sigmoid from the log-odds equation without skipping algebra steps.

3. For y equals zero and p equals 0.2, what probability did the model assign to the observed outcome?

4. Why do we take logs when working with likelihoods?

5. LeetCode style prompt. Given a list of labels and predicted probabilities, compute binary cross-entropy without using a library.

6. Suggested exercise. Implement logistic regression and plot how the decision boundary changes during training.