Sign in

Binary cross entropy

Binary cross-entropy

The loss for yes or no predictions: the negative log of the probability the model gave to the true answer, for one label or many.

Overview

A binary classifier outputs a probability that the answer is yes. Binary cross-entropy asks how surprised the model was by the truth. If the answer was yes and the model said 0.9, the loss is small. If the model said 0.01, the loss is large, and it grows without limit as the model becomes confidently wrong. The same rule is applied to every element, so it also handles multi-label problems where each label is its own yes or no question. Working from the raw score instead of the probability keeps the arithmetic stable.

A short history

Cross-entropy comes from Claude Shannon's 1948 information theory, where it measures the cost of coding events from one distribution with a code built for another. For yes or no labels it equals the negative log-likelihood of a Bernoulli model, which is the quantity logistic regression has minimised since statisticians such as David Cox developed it in the 1950s. Neural networks took it over as the standard loss for a sigmoid output.

How it works

  1. Take a prediction for each element: a raw score zz when from_logits is on, otherwise a probability pp.
  2. From a score, the probability is p=σ(z)p = \sigma(z). From a probability, clip it to [ϵ,1−ϵ][\epsilon, 1 - \epsilon] so the logarithm stays finite.
  3. For a positive target the loss is −ln⁡p-\ln p. For a negative target it is −ln⁡(1−p)-\ln(1 - p).
  4. Multiply the positive term by pos_weight if positives should count more.
  5. Reduce over all elements with reduction: mean, sum, or none.
  6. In backward, the gradient for each score is σ(z)−y\sigma(z) - y when pos_weight is 1, divided by the element count for the mean.

Watch out for

  • Passing probabilities when from_logits is on, or scores when it is off, gives a finite but wrong loss. Nothing raises an error, so check which form your model outputs.
  • Computing the sigmoid first and the log second loses precision once the probability rounds to 0 or 1. The logits path avoids this with a softplus identity.
  • With heavy class imbalance the many easy negatives dominate the mean, and the model can score well by always answering no.
  • For one label out of several exclusive classes this is the wrong loss. Use softmax cross-entropy, which makes the classes compete.

Use cases

When to use it

Binary classification and multi-label classification, where each output is an independent yes or no. Raise pos_weight when positives are rare and missing them is costly.

In industry

Online advertising
Click prediction models are trained with binary cross-entropy on logged impressions, where each label says whether the ad was clicked.
Email and messaging
Spam filters learn from messages labelled spam or not spam, and the predicted probability sets how aggressively to filter.
Medical imaging
Chest X-ray classifiers use one binary cross-entropy term per finding, since a single image can show several conditions.

Choosing it: what must hold

  • Labels that are 0 or 1, or probabilities between them, for one or several independent questions per example.
  • A model that outputs a raw score per label, with the sigmoid applied inside the loss for numerical stability.
  • Classes that are not extremely imbalanced, or a positive class weight to correct for it.

When to choose something else

IfUse instead
Exactly one of several classes is correctSoftmax cross-entropy
Positives are very rare and easy negatives dominate the lossFocal loss
You care about the order of items, not calibrated probabilitiesBPR or another ranking loss

Math foundations

  1. Probability from a score

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

    The sigmoid turns a raw score, the logit, into the model's probability that the label is 1.

  2. The loss for one element

    ℓ(p,y)=−[ w yln⁡p+(1−y)ln⁡(1−p) ]\ell(p, y) = -\big[\,w\,y \ln p + (1 - y)\ln(1 - p)\,\big]

    Only one term is active for a hard label: −ln⁡p-\ln p when y=1y = 1 and −ln⁡(1−p)-\ln(1 - p) when y=0y = 0. It is the negative log-likelihood of a Bernoulli outcome. The weight ww scales the positive term.

  3. The same loss written on the score

    ℓ(z,y)=w y ln⁡ ⁣(1+e−z)+(1−y) ln⁡ ⁣(1+ez)\ell(z, y) = w\,y\,\ln\!\big(1 + e^{-z}\big) + (1 - y)\,\ln\!\big(1 + e^{z}\big)

    Since −ln⁡σ(z)=ln⁡(1+e−z)-\ln\sigma(z) = \ln(1 + e^{-z}) and −ln⁡(1−σ(z))=ln⁡(1+ez)-\ln(1 - \sigma(z)) = \ln(1 + e^{z}). This form never takes the log of a rounded probability, and is what the template evaluates.

  4. The mean over elements

    L=1n∑i=1nℓ(zi,yi)\mathcal{L} = \frac{1}{n}\sum_{i=1}^{n} \ell(z_i, y_i)

    The default reduction. Every element, across examples and labels, has equal weight.

  5. Gradient with respect to the score

    ∂ℓ∂z=(1−y) p−w y (1−p)  =  p−ywhen w=1\frac{\partial \ell}{\partial z} = (1 - y)\,p - w\,y\,(1 - p) \;=\; p - y \quad \text{when } w = 1

    Predicted minus target. The sigmoid's slope cancels against the logarithm's, so the gradient does not vanish when the model is confidently wrong.

Symbols

zz
the raw score (logit) for one element
pp
the predicted probability that the label is 1
yy
the target, 0 or 1 (a value in between is allowed as a soft label)
ww
weight on the positive term, pos_weight in the config, default 1
σ\sigma
the logistic sigmoid
ϵ\epsilon
clipping bound for probabilities, eps in the config
ℓ\ell
the loss for one element
L\mathcal{L}
the reduced loss over all n elements
nn
the number of elements

Worked by hand

One element with score z=2z = 2 and w=1w = 1. Compute the loss and gradient when the label is 1, then when it is 0. Use σ(2)=0.8808\sigma(2) = 0.8808.

y=1:ℓ=−ln⁡0.8808=0.1269,∂ℓ∂z=0.8808−1=−0.1192y = 1: \quad \ell = -\ln 0.8808 = 0.1269, \qquad \frac{\partial \ell}{\partial z} = 0.8808 - 1 = -0.1192
y=0:ℓ=−ln⁡(1−0.8808)=−ln⁡0.1192=2.1269,∂ℓ∂z=0.8808−0=0.8808y = 0: \quad \ell = -\ln(1 - 0.8808) = -\ln 0.1192 = 2.1269, \qquad \frac{\partial \ell}{\partial z} = 0.8808 - 0 = 0.8808

The same confident score costs 0.1269 when right and 2.1269 when wrong. The gradient is seven times larger for the mistake.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import BinaryCrossEntropy
from config import BinaryCrossEntropyConfig

loss = BinaryCrossEntropy(BinaryCrossEntropyConfig(from_logits=True))
logits = np.array([[2.0, -1.0, 0.5]])          # one sample, three independent labels
labels = np.array([[1.0, 0.0, 1.0]])
print(loss.forward(logits, labels))            # 0.3048
print(loss.backward(logits, labels))           # (sigmoid(logits) - labels) / 3
Read the implementation (76 lines)
"""Binary cross-entropy, from logits or from probabilities, for binary and multi-label targets.

NumPy only. `forward` returns the loss, `backward` its gradient with respect to the prediction.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import BinaryCrossEntropyConfig
except ImportError:  # run from the template's own folder
    from config import BinaryCrossEntropyConfig

def _pair(pred, target) -> tuple[np.ndarray, np.ndarray]:
    """Both inputs as float arrays of one shape. Raises ValueError when the shapes differ."""
    pred, target = np.asarray(pred, dtype=float), np.asarray(target, dtype=float)
    if pred.shape != target.shape:
        raise ValueError(f"pred and target must have the same shape, got {pred.shape} and {target.shape}")
    return pred, target


def _reduce(values: np.ndarray, reduction: str):
    """Reduce per-element losses: "mean" and "sum" give a float, "none" returns the array unchanged."""
    if reduction == "mean":
        return float(values.mean())
    if reduction == "sum":
        return float(values.sum())
    return values


def _grad_scale(count: int, reduction: str) -> float:
    """Factor the reduction puts on every per-element gradient: 1 / count for "mean", otherwise 1."""
    return 1.0 / count if reduction == "mean" else 1.0


def _sigmoid(x: np.ndarray) -> np.ndarray:
    """Logistic function 1 / (1 + exp(-x)), written so that large |x| cannot overflow."""
    return np.exp(-np.logaddexp(0.0, -x))


class BinaryCrossEntropy:
    """-(w * y * log(p) + (1 - y) * log(1 - p)) per element, with p = sigmoid(pred) when from_logits is on."""

    def __init__(self, config: BinaryCrossEntropyConfig | None = None) -> None:
        self.config = config or BinaryCrossEntropyConfig()

    def forward(self, pred: np.ndarray, target: np.ndarray):
        """pred: scores (or probabilities), any shape, e.g. (N,) or (N, labels). target: same shape, values in
        [0, 1]. Returns a float, or the per-element array for "none"."""
        pred, target = _pair(pred, target)
        w = self.config.pos_weight
        if self.config.from_logits:
            # -log(sigmoid(z)) = softplus(-z) and -log(1 - sigmoid(z)) = softplus(z); logaddexp cannot overflow
            values = w * target * np.logaddexp(0.0, -pred) + (1.0 - target) * np.logaddexp(0.0, pred)
        else:
            p = np.clip(pred, self.config.eps, 1.0 - self.config.eps)
            values = -(w * target * np.log(p) + (1.0 - target) * np.log1p(-p))
        return _reduce(values, self.config.reduction)

    def backward(self, pred: np.ndarray, target: np.ndarray) -> np.ndarray:
        """Gradient of the reduced loss with respect to pred, same shape as pred.

        From logits with pos_weight 1 the per-element derivative is sigmoid(pred) - target. For "none" the
        per-element derivative is returned unscaled (the gradient of the sum).
        """
        pred, target = _pair(pred, target)
        w = self.config.pos_weight
        if self.config.from_logits:
            p = _sigmoid(pred)
            local = (1.0 - target) * p - w * target * (1.0 - p)
        else:
            p = np.clip(pred, self.config.eps, 1.0 - self.config.eps)
            local = (1.0 - target) / (1.0 - p) - w * target / p
        return local * _grad_scale(pred.size, self.config.reduction)

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Build BinaryCrossEntropy(BinaryCrossEntropyConfig(from_logits=True)) and call forward and backward on scores 2, -1, 0.5 with targets 1, 0, 1. Then pass the sigmoid of those scores to a second instance with from_logits=False and confirm the loss matches. Try a score of 800 in both.

Check on learning

  1. Squared error could also compare a sigmoid output with a 0 or 1 target. Why does cross-entropy train faster when the model is confidently wrong?
    A way to think about it

    Differentiate both with respect to the score. Squared error keeps the factor p(1−p)p(1 - p), which is near zero at the extremes. Cross-entropy cancels it.

  2. Positives make up 1 percent of the data. Predict what a model trained with pos_weight of 1 learns first, and how setting it to 99 changes the gradient balance.
    A way to think about it

    Add up the gradient contributed by all negatives and by all positives at the start, when every prediction is 0.5. Then rescale the positive part.

  3. The loss is 0.69 after many epochs and will not move. What does that number suggest?
    A way to think about it

    Compute −ln⁡0.5-\ln 0.5. A loss stuck there means the model outputs one half for everything, so look for inputs or labels that carry no usable signal, or a broken gradient path.

  4. Why does the template clip probabilities only on the path where from_logits is false?
    A way to think about it

    On the logits path the logarithm of a probability is never formed. Look at which expression could produce the log of zero.

  5. A photo can contain a cat, a dog, both or neither. Why is this loss right and softmax cross-entropy wrong?
    A way to think about it

    Softmax forces the class probabilities to sum to 1. Check whether the four possible answers can all be represented under that constraint.