Sign in

Logistic regression

A two-class classifier that turns a weighted sum of the features into a probability with the sigmoid function, trained by minimising the log loss.

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

  1. Map the two labels to 0 and 1. The larger label in sorted order, classes_[1], is the positive class.
  2. Start with zero weights and bias, so every row begins with probability 0.5.
  3. Compute z=w⊤x+bz = \mathbf{w}^\top \mathbf{x} + b and p=σ(z)p = \sigma(z) for every row.
  4. Measure the mean log loss, plus 12λ∥w∥2\tfrac{1}{2}\lambda \lVert \mathbf{w} \rVert^2 if l2 is set.
  5. With solver gd, step against the gradient with size η\eta. With solver newton, solve a small linear system using the curvature matrix HH, which usually converges in 10 to 25 steps.
  6. Predict the positive class when pp 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 d×dd \times d 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

IfUse instead
There are more than two classesSoftmax regression (the multiclass classifier lesson)
Feature interactions and non-linear effects dominateGradient boosted trees such as XGBoost, or an MLP
Features are word counts and the training data is smallNaive Bayes

Math foundations

  1. The sigmoid

    σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}

    Maps any real number to a value between 0 and 1. It is 0.5 at zero and its slope is σ(z)(1−σ(z))\sigma(z)(1 - \sigma(z)).

  2. The model

    p=P(y=1∣x)=σ ⁣(w⊤x+b)p = P(y = 1 \mid \mathbf{x}) = \sigma\!\left(\mathbf{w}^\top \mathbf{x} + b\right)

    The probability of the positive class. Inverting the sigmoid shows that w⊤x+b\mathbf{w}^\top \mathbf{x} + b is the log-odds, log⁡p1−p\log\frac{p}{1 - p}.

  3. The log loss

    L(w,b)=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]+λ2∥w∥2L(\mathbf{w}, b) = -\frac{1}{n}\sum_{i=1}^{n}\left[y_i \log p_i + (1 - y_i)\log(1 - p_i)\right] + \frac{\lambda}{2}\lVert \mathbf{w} \rVert^2

    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.

  4. The gradient

    ∇wL=1nX⊤(p−y)+λw,∂L∂b=1n∑i(pi−yi)\nabla_{\mathbf{w}} L = \frac{1}{n} X^\top (\mathbf{p} - \mathbf{y}) + \lambda \mathbf{w}, \qquad \frac{\partial L}{\partial b} = \frac{1}{n}\sum_{i}(p_i - y_i)

    The error pi−yip_i - y_i 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.

  5. The gradient step

    w←w−η ∇wL\mathbf{w} \leftarrow \mathbf{w} - \eta \, \nabla_{\mathbf{w}} L

    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.

  6. The Newton step

    w←w−H−1∇wL,H=1nX⊤diag⁡ ⁣(pi(1−pi))X+λI\mathbf{w} \leftarrow \mathbf{w} - H^{-1} \nabla_{\mathbf{w}} L, \qquad H = \frac{1}{n} X^\top \operatorname{diag}\!\big(p_i (1 - p_i)\big) X + \lambda I

    Uses the curvature HH to pick both the direction and the length of the step. Rows with pp near 0.5 carry the most weight. The template adds the bias as an extra unpenalised column.

Symbols

xi\mathbf{x}_i
feature vector of row i
yiy_i
label of row i, coded 0 or 1
pip_i
predicted probability that row i is positive
w,b\mathbf{w}, b
weights and bias
σ\sigma
the sigmoid function
λ\lambda
L2 strength, the l2 parameter
η\eta
step size, the lr parameter
HH
Hessian: the matrix of second derivatives of the loss
nn
number of rows

Worked by hand

One training row with x=2x = 2 and y=1y = 1, one weight, no bias, no penalty. Start at w=0w = 0 and take one gradient step with η=0.5\eta = 0.5.

p=σ(0×2)=0.5,L=−ln⁡0.5=0.6931p = \sigma(0 \times 2) = 0.5, \qquad L = -\ln 0.5 = 0.6931
∂L∂w=(p−y) x=(0.5−1)×2=−1\frac{\partial L}{\partial w} = (p - y)\,x = (0.5 - 1) \times 2 = -1
w←0−0.5×(−1)=0.5w \leftarrow 0 - 0.5 \times (-1) = 0.5
p=σ(0.5×2)=σ(1)=0.7311,L=−ln⁡0.7311=0.3133p = \sigma(0.5 \times 2) = \sigma(1) = 0.7311, \qquad L = -\ln 0.7311 = 0.3133

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.9
Read 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

  1. 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 p(1−p)p(1 - p). Ask what that factor does when the model is confidently wrong.

  2. 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 pip_i and to the loss. Then add the penalty term and ask which force wins as the weights get large.

  3. 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 d×dd \times d system for d=10d = 10 and d=100000d = 100000.

  4. 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.