Sign in

Binary classifier

Binary classifier (logistic regression)

Logistic regression: a linear score passed through the sigmoid function to give the probability of the positive class.

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

  1. Standardise every feature to mean 0 and standard deviation 1 inside the model, and add an intercept.
  2. Compute the score z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b for every row and the probability p=σ(z)p = \sigma(z).
  3. 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.
  4. Compute the gradient and the Hessian (the matrix of second derivatives) of the loss.
  5. Take a Newton step: solve a linear system for the step, and halve it until the loss does not go up.
  6. Stop when the largest weight change is below tol or after max_iter steps, then convert the weights back to the original feature units.
  7. 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 l2 above 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_weight or a lower threshold.
  • 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

IfUse instead
There are three or more classesSoftmax regression (the multiclass classifier lesson)
The classes are separated by a curved or irregular boundaryA random forest, gradient boosted trees or an MLP
You need a number, not a classLinear regression

Math foundations

  1. The model

    p=P(y=1∣x)=σ(w⋅x+b),σ(z)=11+e−zp = P(y = 1 \mid \mathbf{x}) = \sigma(\mathbf{w} \cdot \mathbf{x} + b), \qquad \sigma(z) = \frac{1}{1 + e^{-z}}

    A linear score squashed into the range 0 to 1. The sigmoid is 0.5 at z=0z = 0, so the decision boundary at threshold 0.5 is where the score is zero.

  2. Log-odds are linear

    log⁡p1−p=w⋅x+b\log \frac{p}{1 - p} = \mathbf{w} \cdot \mathbf{x} + b

    Inverting the sigmoid shows what the model assumes: each feature adds a fixed amount wjw_j to the log of the odds per unit.

  3. Log-loss with L2 penalty

    L(w,b)=−1n∑i=1n[tilog⁡pi+(1−ti)log⁡(1−pi)]+λ2∥w∥2\mathcal{L}(\mathbf{w}, b) = -\frac{1}{n} \sum_{i=1}^{n} \big[ t_i \log p_i + (1 - t_i) \log (1 - p_i) \big] + \frac{\lambda}{2} \|\mathbf{w}\|^2

    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.

  4. Gradient

    ∇wL=1nX⊤(p−t)+λw\nabla_{\mathbf{w}} \mathcal{L} = \frac{1}{n} X^{\top} (\mathbf{p} - \mathbf{t}) + \lambda \mathbf{w}

    Each row pulls the weights in the direction of its features, in proportion to its error pi−tip_i - t_i.

  5. Hessian

    H=1nX⊤SX+λI,S=diag⁡(pi(1−pi))H = \frac{1}{n} X^{\top} S X + \lambda I, \qquad S = \operatorname{diag}\big(p_i (1 - p_i)\big)

    The curvature of the loss. Every entry of SS is positive, so HH is positive definite and the loss is convex: it has exactly one minimum.

  6. Newton step

    w←w−H−1∇wL\mathbf{w} \leftarrow \mathbf{w} - H^{-1} \nabla_{\mathbf{w}} \mathcal{L}

    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

x\mathbf{x}
feature vector of one row
w,b\mathbf{w}, b
weights and intercept
zz
the linear score, also the log-odds
σ\sigma
the sigmoid function
pip_i
predicted probability that row i is positive
tit_i
true label of row i, 0 or 1
XX
matrix of standardised features, one row per example
λ\lambda
the l2 penalty strength
SS
diagonal matrix of the values p(1 - p)
HH
Hessian of the loss
nn
number of rows

Worked by hand

Weights w=(1.5,−1)\mathbf{w} = (1.5, -1), intercept b=−0.5b = -0.5, and one row x=(2,1)\mathbf{x} = (2, 1) whose true label is 1.

z=1.5⋅2+(−1)⋅1−0.5=1.5z = 1.5 \cdot 2 + (-1) \cdot 1 - 0.5 = 1.5
p=11+e−1.5=11.2231=0.8176p = \frac{1}{1 + e^{-1.5}} = \frac{1}{1.2231} = 0.8176
loss=−ln⁡0.8176=0.2014\text{loss} = -\ln 0.8176 = 0.2014
p−t=0.8176−1=−0.1824p - t = 0.8176 - 1 = -0.1824
p(1−p)=0.8176×0.1824=0.1491p(1 - p) = 0.8176 \times 0.1824 = 0.1491

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, f1
Read 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

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

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

  3. 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 e0.7≈2e^{0.7} \approx 2. Describe what happens to the odds when the feature goes up by one unit and everything else stays the same.

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

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