Overview
To predict yes or no, logistic regression first adds up the evidence: each feature is multiplied by a weight and the results are summed into one score. A large positive score means yes, a large negative score means no. The sigmoid function then turns that score into a probability between 0 and 1. Training finds the weights that make the observed labels as probable as possible. Because the loss has a single lowest point, the fit does not depend on a lucky start, and each weight can be read as the change in the log-odds for one unit of its feature.
A short history
The logistic function was introduced by Pierre François Verhulst in the 1830s and 1840s to model population growth. Statisticians adopted it for yes or no outcomes in the twentieth century: Joseph Berkson promoted the logit model in 1944 and David Cox set out logistic regression in 1958. It became the default method for binary outcomes in medicine, credit and marketing because its weights are easy to read and its probabilities are usually well calibrated.
How it works
- Standardise every feature to mean 0 and standard deviation 1 inside the model, and add an intercept.
- Compute the score for every row and the probability .
- Measure the log-loss, averaged over the rows, plus the L2 penalty on the weights. With
class_weight="balanced"each class gets the same total weight. - Compute the gradient and the Hessian (the matrix of second derivatives) of the loss.
- Take a Newton step: solve a linear system for the step, and halve it until the loss does not go up.
- Stop when the largest weight change is below
tolor aftermax_itersteps, then convert the weights back to the original feature units. - Predict the positive class when the probability is at least
threshold.
Watch out for
- When the classes can be separated perfectly, the best weights without a penalty are infinite, because a steeper sigmoid always fits better. Keep
l2above zero. - With rare positives the default threshold of 0.5 can label almost everything negative while accuracy still looks high. Read precision and recall, and use
class_weightor a lowerthreshold. - The boundary is a straight line or flat plane in the features. An effect that depends on a product or a curve is missed unless you add that term as a feature.
- Strongly correlated features make individual weights unstable: the model can trade weight between them with little change in the loss, so their signs and sizes are hard to interpret.
Use cases
When to use it
The first model to try for any yes or no target: it is fast, its fit is unique and its weights can be read. Move on only when the boundary is clearly not linear in the features.
In industry
- Email and messaging
- Spam filtering: a linear score over word and sender features gives the probability that a message is spam.
- Healthcare
- Risk scores that estimate the probability of an outcome, such as readmission, from a small set of patient measurements.
- Subscription businesses
- Churn prediction: estimating which customers are likely to cancel so that retention offers can be targeted.
Choosing it: what must hold
- A target with exactly two classes.
- A boundary between the classes that is roughly linear in the features, or features engineered to make it so.
- Features on comparable scales when training with gradient descent.
When to choose something else
| If | Use instead |
|---|---|
| There are three or more classes | Softmax regression (the multiclass classifier lesson) |
| The classes are separated by a curved or irregular boundary | A random forest, gradient boosted trees or an MLP |
| You need a number, not a class | Linear regression |
Math foundations
The model
A linear score squashed into the range 0 to 1. The sigmoid is 0.5 at , so the decision boundary at threshold 0.5 is where the score is zero.
Log-odds are linear
Inverting the sigmoid shows what the model assumes: each feature adds a fixed amount to the log of the odds per unit.
Log-loss with L2 penalty
Minus the average log-probability of the observed labels, plus a penalty that keeps the weights small. The intercept is not penalised. With class weights the average becomes a weighted average.
Gradient
Each row pulls the weights in the direction of its features, in proportion to its error .
Hessian
The curvature of the loss. Every entry of is positive, so is positive definite and the loss is convex: it has exactly one minimum.
Newton step
Uses the curvature to jump towards the minimum of the local quadratic approximation. It usually converges in a handful of steps, where gradient descent would need hundreds.
Symbols
- feature vector of one row
- weights and intercept
- the linear score, also the log-odds
- the sigmoid function
- predicted probability that row i is positive
- true label of row i, 0 or 1
- matrix of standardised features, one row per example
- the l2 penalty strength
- diagonal matrix of the values p(1 - p)
- Hessian of the loss
- number of rows
Worked by hand
Weights , intercept , and one row whose true label is 1.
The model gives the true class a probability of 0.82. The error of -0.18 pushes the weights a little further in the direction of this row's features, and 0.149 is the weight this row gets in the Hessian.
Visual example
Loading the example.
Try this
- Move the threshold: you trade missed positives for false alarms.
- Find the threshold where both kinds of mistake are equal.
Code sample
import numpy as np
from impl import BinaryClassifier
from config import BinaryClassifierConfig
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(-1, 1, size=(100, 2)), rng.normal(1, 1, size=(100, 2))])
y = np.array([0] * 100 + [1] * 100)
clf = BinaryClassifier(BinaryClassifierConfig(l2=0.01)).fit(X, y)
print(clf.predict_proba(X[:3])) # probability of class 1
print(clf.score(X, y)) # accuracy, precision, recall, f1Read the implementation (107 lines)
"""BinaryClassifier: logistic regression for two classes.
NumPy only. The model is p(y = 1 | x) = sigmoid(w . x + b), fitted by Newton's method (iteratively reweighted
least squares), which converges in a handful of steps on the convex log-loss. Features are standardised
inside the model, so the L2 penalty treats every feature alike and the learned weights are reported back in
the original units.
"""
from __future__ import annotations
import numpy as np
try:
from .config import BinaryClassifierConfig
except ImportError: # run from the template's own folder
from config import BinaryClassifierConfig
def sigmoid(z: np.ndarray) -> np.ndarray:
"""Numerically stable logistic function."""
z = np.asarray(z, dtype=float)
out = np.empty_like(z)
pos = z >= 0
out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
e = np.exp(z[~pos])
out[~pos] = e / (1.0 + e)
return out
class BinaryClassifier:
"""Logistic regression with an L2 penalty, optional class balancing and a decision threshold."""
def __init__(self, config: BinaryClassifierConfig | None = None) -> None:
self.config = config or BinaryClassifierConfig()
self.coef_: np.ndarray | None = None # (d,) weights in the units of the original features
self.intercept_: float = 0.0
self.classes_: np.ndarray | None = None # [negative label, positive label]
self.loss_history: list[float] = [] # penalised log-loss after each Newton step
self.n_iter_ = 0
def _loss(self, Z: np.ndarray, t: np.ndarray, sw: np.ndarray, w: np.ndarray) -> float:
"""Weighted mean log-loss plus the L2 penalty. Z: (n, d + 1) standardised features with a ones column."""
z = Z @ w
log_loss = np.sum(sw * (np.logaddexp(0.0, z) - t * z)) / sw.sum()
return float(log_loss + 0.5 * self.config.l2 * np.sum(w[:-1] ** 2))
def fit(self, X: np.ndarray, y: np.ndarray) -> "BinaryClassifier":
"""Fit the weights. X: (n, d) features. y: (n,) labels with exactly two distinct values.
The larger label (by sort order) is the positive class.
"""
cfg = self.config
X = np.asarray(X, dtype=float)
self.classes_, t = np.unique(np.asarray(y), return_inverse=True)
if len(self.classes_) != 2:
raise ValueError(f"y must hold exactly two classes, got {len(self.classes_)}")
t = t.astype(float)
n, d = X.shape
mean = X.mean(axis=0)
scale = X.std(axis=0)
scale[scale == 0] = 1.0
Z = np.hstack([(X - mean) / scale, np.ones((n, 1))])
sw = np.ones(n)
if cfg.class_weight == "balanced": # each class gets the same total weight
sw = np.where(t == 1, n / (2.0 * t.sum()), n / (2.0 * (n - t.sum())))
penalty = np.full(d + 1, cfg.l2)
penalty[-1] = 0.0 # the intercept is not penalised
w = np.zeros(d + 1)
self.loss_history = [self._loss(Z, t, sw, w)]
for it in range(1, cfg.max_iter + 1):
p = sigmoid(Z @ w)
grad = Z.T @ (sw * (p - t)) / sw.sum() + penalty * w
hess = (Z * (sw * p * (1 - p))[:, None]).T @ Z / sw.sum() + np.diag(penalty + 1e-10)
step = np.linalg.solve(hess, grad)
# Halve the step until the loss does not go up (guards against overshooting on separable data).
scale_step, current = 1.0, self.loss_history[-1]
while self._loss(Z, t, sw, w - scale_step * step) > current + 1e-12 and scale_step > 1e-6:
scale_step *= 0.5
w = w - scale_step * step
self.loss_history.append(self._loss(Z, t, sw, w))
self.n_iter_ = it
if np.max(np.abs(scale_step * step)) < cfg.tol:
break
self.coef_ = w[:-1] / scale
self.intercept_ = float(w[-1] - np.sum(w[:-1] * mean / scale))
return self
def decision_function(self, X: np.ndarray) -> np.ndarray:
"""Log-odds of the positive class. X: (n, d) -> (n,)."""
return np.asarray(X, dtype=float) @ self.coef_ + self.intercept_
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Probability of the positive class. X: (n, d) -> (n,)."""
return sigmoid(self.decision_function(X))
def predict(self, X: np.ndarray) -> np.ndarray:
"""Labels: the positive class where its probability is at least `threshold`. X: (n, d) -> (n,)."""
return self.classes_[(self.predict_proba(X) >= self.config.threshold).astype(int)]
def score(self, X: np.ndarray, y: np.ndarray) -> dict:
"""Accuracy, precision, recall and F1 of `predict` against y, with the positive class as the target."""
pred = self.predict(X) == self.classes_[1]
true = np.asarray(y) == self.classes_[1]
tp = float(np.sum(pred & true))
precision = tp / float(pred.sum()) if pred.sum() else 0.0
recall = tp / float(true.sum()) if true.sum() else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return {"accuracy": float(np.mean(pred == true)), "precision": precision, "recall": recall, "f1": f1}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Create two Gaussian clouds as in the template's README and fit BinaryClassifier. Print n_iter_ and loss_history to see how few Newton steps are needed. Then make the positives rare (keep 10 of the 100) and compare score with class_weight="none" and with class_weight="balanced".
Check on learning
- Why does the model use the log-loss and not simply the number of wrong predictions as its training objective?
A way to think about it
Try to take a derivative of the error count with respect to a weight. Then consider what each objective says about a correct prediction made with probability 0.51.
- On perfectly separable data with
l2=0, what happens to the weights as training continues, and why does the penalty fix it?A way to think about it
Multiply all weights by 10 and see what happens to every predicted probability and to the loss. Then add the cost of large weights.
- A weight of 0.7 on a feature is reported in original units. How would you explain its meaning to someone who does not know what log-odds are?
A way to think about it
Use . Describe what happens to the odds when the feature goes up by one unit and everything else stays the same.
- Lowering the threshold from 0.5 to 0.2 changes precision and recall but not the fitted weights. Why, and which of the two metrics goes up?
A way to think about it
The threshold is applied after training. Count which rows change their predicted label and what kind of error each change adds or removes.
- Newton's method needs far fewer steps than gradient descent here. What does each step cost, and when would that cost become a problem?
A way to think about it
Look at the size of the Hessian and at what solving a linear system of that size costs as the number of features grows.