Overview
Linear regression outputs any number, but a probability must stay between 0 and 1. Logistic regression keeps the weighted sum and then squeezes it through an S-shaped curve, the sigmoid. A sum of zero gives a probability of one half, large positive sums approach 1 and large negative sums approach 0. The weighted sum itself is the log-odds: each weight says how much the odds of the positive class multiply when its feature rises by one. Training looks for the weights under which the observed labels are most probable.
A short history
The logistic curve comes from Pierre François Verhulst's work on population growth in 1838. Joseph Berkson coined the term logit in 1944 and argued for the model in bioassay, and David Cox gave the regression form its standard statistical treatment in 1958. Its place in medicine was fixed by studies such as the Framingham heart study, which used it to relate risk factors to disease.
How it works
- Map the two labels to 0 and 1. The larger label in sorted order, classes_[1], is the positive class.
- Start with zero weights and bias, so every row begins with probability 0.5.
- Compute and for every row.
- Measure the mean log loss, plus if l2 is set.
- With solver gd, step against the gradient with size . With solver newton, solve a small linear system using the curvature matrix , which usually converges in 10 to 25 steps.
- Predict the positive class when is at least the threshold, 0.5 by default.
Watch out for
- If the classes can be separated perfectly by a plane, the loss keeps falling as the weights grow without bound. Set l2 above zero to keep them finite.
- The decision boundary is a straight plane in feature space, so curved boundaries are missed unless you add transformed features.
- Newton's method builds and solves a system at each step, which becomes slow when there are many features.
- With rare positives, a threshold of 0.5 can label almost nothing positive even when the probabilities are sound. Choose the threshold from the costs of the two kinds of error.
Use cases
When to use it
Two-class problems where you want a calibrated probability and readable weights: churn, click or default prediction. It is the standard baseline before any non-linear classifier.
In industry
- Medicine and public health
- Estimating how risk factors such as age, smoking and blood pressure change the odds of a disease.
- Credit scoring
- Scorecards that turn applicant attributes into points; the weights are easy to explain to customers and regulators.
- Online advertising
- Large sparse click prediction models, where logistic regression was the industry standard before deep models.
Choosing it: what must hold
- A target with exactly two classes, such as yes or no.
- Classes that a straight boundary in feature space separates reasonably well.
- Regularisation or more data when the classes are perfectly separable, because the weights otherwise grow without limit.
When to choose something else
| If | Use instead |
|---|---|
| There are more than two classes | Softmax regression (the multiclass classifier lesson) |
| Feature interactions and non-linear effects dominate | Gradient boosted trees such as XGBoost, or an MLP |
| Features are word counts and the training data is small | Naive Bayes |
Math foundations
The sigmoid
Maps any real number to a value between 0 and 1. It is 0.5 at zero and its slope is .
The model
The probability of the positive class. Inverting the sigmoid shows that is the log-odds, .
The log loss
The negative mean log-likelihood of the labels. A confident wrong answer costs a great deal, a confident right answer costs almost nothing. The bias is not penalised.
The gradient
The error of each row, weighted by its features. It has the same form as in linear regression, which is why the sigmoid and the log loss are paired.
The gradient step
The gd solver repeats this for the configured number of epochs. The loss is convex, so there is one minimum and no bad local ones.
The Newton step
Uses the curvature to pick both the direction and the length of the step. Rows with near 0.5 carry the most weight. The template adds the bias as an extra unpenalised column.
Symbols
- feature vector of row i
- label of row i, coded 0 or 1
- predicted probability that row i is positive
- weights and bias
- the sigmoid function
- L2 strength, the l2 parameter
- step size, the lr parameter
- Hessian: the matrix of second derivatives of the loss
- number of rows
Worked by hand
One training row with and , one weight, no bias, no penalty. Start at and take one gradient step with .
One step raises the probability of the true label from 0.50 to 0.73 and cuts the loss from 0.69 to 0.31.
Visual example
Loading the example.
Try this
- Switch to the moons data: a straight line cannot follow the curve.
- Add points far from the line: they barely move it.
Code sample
import numpy as np
from impl import LogRegression
from config import LogRegressionConfig
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(-1.0, 1.0, size=(100, 2)), rng.normal(1.0, 1.0, size=(100, 2))])
y = np.array([0] * 100 + [1] * 100)
model = LogRegression(LogRegressionConfig(l2=0.01)).fit(X, y)
print(model.predict_proba(X[:3])) # probability of class 1 for three rows
print((model.predict(X) == y).mean()) # training accuracy, about 0.9Read the implementation (107 lines)
"""Logistic regression for two classes, trained by gradient descent or by Newton's method.
NumPy only. The model is P(y = 1 | x) = sigmoid(x . w + b). The objective is
mean over rows of [ -y log p - (1 - y) log (1 - p) ] + 0.5 * l2 * ||w||^2
"""
from __future__ import annotations
import numpy as np
try:
from .config import LogRegressionConfig
except ImportError: # run from the template's own folder
from config import LogRegressionConfig
def sigmoid(z: np.ndarray) -> np.ndarray:
"""Numerically stable 1 / (1 + exp(-z)): never exponentiates a large positive number."""
z = np.asarray(z, dtype=float)
e = np.exp(-np.abs(z))
return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))
class LogRegression:
"""Binary logistic regression. After `fit`: `coef_` (d,), `intercept_` float, `classes_` (2,)."""
def __init__(self, config: LogRegressionConfig | None = None) -> None:
self.config = config or LogRegressionConfig()
self.coef_: np.ndarray | None = None
self.intercept_ = 0.0
self.classes_: np.ndarray | None = None
self.loss_history_: list[float] = []
def _targets(self, y: np.ndarray) -> np.ndarray:
"""Map the two labels to 0.0 and 1.0. y: shape (n,)."""
return (np.asarray(y) == self.classes_[1]).astype(float)
def loss(self, X: np.ndarray, y: np.ndarray) -> float:
"""Objective value at the current weights. X: (n, d). y: labels, shape (n,)."""
z = np.asarray(X, dtype=float) @ self.coef_ + self.intercept_
t = self._targets(y)
# -t log p - (1 - t) log(1 - p) = log(1 + exp(z)) - t z
data = np.mean(np.logaddexp(0.0, z) - t * z)
return float(data + 0.5 * self.config.l2 * np.sum(self.coef_**2))
def gradient(self, X: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, float]:
"""Gradient of `loss` with respect to (coef_, intercept_). Returns (shape (d,), float)."""
X = np.asarray(X, dtype=float)
error = sigmoid(X @ self.coef_ + self.intercept_) - self._targets(y)
grad_w = X.T @ error / len(X) + self.config.l2 * self.coef_
grad_b = float(error.mean()) if self.config.fit_intercept else 0.0
return grad_w, grad_b
def fit(self, X: np.ndarray, y: np.ndarray) -> "LogRegression":
"""Fit the model. X: features, shape (n, d). y: labels with exactly two distinct values, shape (n,)."""
X = np.asarray(X, dtype=float)
y = np.asarray(y)
if X.ndim != 2 or len(X) != len(y):
raise ValueError("X must have shape (n, d) and y must have n entries")
self.classes_ = np.unique(y)
if len(self.classes_) != 2:
raise ValueError(f"y must hold exactly two classes, found {len(self.classes_)}")
self.coef_ = np.zeros(X.shape[1])
self.intercept_ = 0.0
self.loss_history_ = []
step = self._newton_step if self.config.solver == "newton" else self._gd_step
for _ in range(self.config.epochs):
self.loss_history_.append(self.loss(X, y))
step(X, y)
return self
def _gd_step(self, X: np.ndarray, y: np.ndarray) -> None:
grad_w, grad_b = self.gradient(X, y)
self.coef_ = self.coef_ - self.config.lr * grad_w
self.intercept_ -= self.config.lr * grad_b
def _newton_step(self, X: np.ndarray, y: np.ndarray) -> None:
"""One Newton step: solve H delta = gradient, where H = X^T diag(p (1 - p)) X / n + l2 I."""
n, d = X.shape
p = sigmoid(X @ self.coef_ + self.intercept_)
grad_w, grad_b = self.gradient(X, y)
weight = p * (1.0 - p)
if self.config.fit_intercept:
A = np.hstack([X, np.ones((n, 1))])
grad = np.append(grad_w, grad_b)
penalty = np.diag(np.append(np.full(d, self.config.l2), 0.0))
else:
A, grad, penalty = X, grad_w, self.config.l2 * np.eye(d)
H = (A * weight[:, None]).T @ A / n + penalty + 1e-10 * np.eye(A.shape[1])
delta = np.linalg.solve(H, grad)
self.coef_ = self.coef_ - delta[:d]
if self.config.fit_intercept:
self.intercept_ -= float(delta[d])
def decision_function(self, X: np.ndarray) -> np.ndarray:
"""Log-odds of the positive class. X: (n, d). Returns shape (n,)."""
if self.coef_ is None:
raise RuntimeError("call fit before predicting")
return np.asarray(X, dtype=float) @ self.coef_ + self.intercept_
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Probability of the positive class `classes_[1]`. X: (n, d). Returns shape (n,)."""
return sigmoid(self.decision_function(X))
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predicted labels, taken from `classes_`. X: (n, d). Returns shape (n,)."""
return self.classes_[(self.predict_proba(X) >= self.config.threshold).astype(int)]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build two overlapping clouds of points in two dimensions. Fit LogRegression with LogRegressionConfig solver set to gd and 500 epochs, then with solver set to newton and 15 epochs. Compare coef_, intercept_ and the final value of loss_history_. Then call gradient at the fitted weights and confirm it is close to zero.
Check on learning
- Why is squared error a poor loss for a sigmoid output, when it works well for linear regression?
A way to think about it
Write the gradient of squared error through the sigmoid. It contains the factor . Ask what that factor does when the model is confidently wrong.
- On perfectly separable data the weights keep growing. Why does the loss never reach a minimum, and why does l2 stop the growth?
A way to think about it
Scale every weight by 2 and see what happens to each and to the loss. Then add the penalty term and ask which force wins as the weights get large.
- Newton's method needs about 15 steps where gradient descent needs hundreds. What does it know that gradient descent does not, and what does it pay for that?
A way to think about it
Compare the information in a gradient with the information in a Hessian. Then count the work of solving a system for and .
- You raise the threshold from 0.5 to 0.9. Predict what happens to false positives and false negatives, and say when that trade is worth making.
A way to think about it
The probabilities do not change, only the cut. Think of a case where acting on a wrong positive is expensive, such as blocking a payment.