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 and . It is tempting to fit a line and treat the output as the probability of class .
The problem is that a line can output any real number. A prediction of cannot mean negative probability. A prediction of cannot mean a probability greater than one. Probabilities must always stay between zero and one.
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.
If an event has probability , then the probability it happens is and the probability it does not happen is . The odds are . 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.
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.
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 .
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.
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
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 label | Model prediction | Probability of observed outcome |
|---|---|---|
| 1 | 0.9 | 0.9 |
| 1 | 0.8 | 0.8 |
| 0 | 0.3 | 0.7 |
For the first two examples, the observed label is . The model assigned probabilities and to the observed outcome. For the third example, the model predicted for class , but the observed label was . The probability assigned to what happened is therefore .
If the examples are treated as independent, the probability of seeing the whole dataset under this model is the product of those probabilities.
For one observation, there is a compact way to select the right probability.
This works because the label is either or . When , the first factor remains and the second factor becomes one.
When , the first factor becomes one and the second factor remains.
Across a dataset, likelihood multiplies the probability assigned to every observed label.
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.
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.
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.
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 , the loss for one prediction is .
| Predicted probability | Cross-entropy loss |
|---|---|
| 0.9 | 0.105 |
| 0.5 | 0.693 |
| 0.1 | 2.303 |
| 0.01 | 4.605 |
A prediction of is confident and correct, so the loss is small. A prediction of is confidently wrong, so the loss is much larger. The model is being taught that confident mistakes are worse than uncertain mistakes.
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
| Idea | Linear Regression | Logistic Regression |
|---|---|---|
| Prediction target | Continuous number | Binary class probability |
| Output | Any real value | A value between zero and one |
| Activation | None | Sigmoid |
| Loss function | Mean squared error | Binary cross-entropy |
| Optimisation objective | Minimise squared residuals | Maximise likelihood or minimise negative log-likelihood |
| Interpretation | Expected target value | Probability of class one |
| Applications | Prices, demand, measurements | Spam, 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.