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
- Take a prediction for each element: a raw score when
from_logitsis on, otherwise a probability . - From a score, the probability is . From a probability, clip it to so the logarithm stays finite.
- For a positive target the loss is . For a negative target it is .
- Multiply the positive term by
pos_weightif positives should count more. - Reduce over all elements with
reduction: mean, sum, or none. - In
backward, the gradient for each score is whenpos_weightis 1, divided by the element count for the mean.
Watch out for
- Passing probabilities when
from_logitsis 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
| If | Use instead |
|---|---|
| Exactly one of several classes is correct | Softmax cross-entropy |
| Positives are very rare and easy negatives dominate the loss | Focal loss |
| You care about the order of items, not calibrated probabilities | BPR or another ranking loss |
Math foundations
Probability from a score
The sigmoid turns a raw score, the logit, into the model's probability that the label is 1.
The loss for one element
Only one term is active for a hard label: when and when . It is the negative log-likelihood of a Bernoulli outcome. The weight scales the positive term.
The same loss written on the score
Since and . This form never takes the log of a rounded probability, and is what the template evaluates.
The mean over elements
The default reduction. Every element, across examples and labels, has equal weight.
Gradient with respect to the score
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
- the raw score (logit) for one element
- the predicted probability that the label is 1
- the target, 0 or 1 (a value in between is allowed as a soft label)
- weight on the positive term,
pos_weightin the config, default 1 - the logistic sigmoid
- clipping bound for probabilities,
epsin the config - the loss for one element
- the reduced loss over all n elements
- the number of elements
Worked by hand
One element with score and . Compute the loss and gradient when the label is 1, then when it is 0. Use .
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) / 3Read 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
- 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 , which is near zero at the extremes. Cross-entropy cancels it.
- Positives make up 1 percent of the data. Predict what a model trained with
pos_weightof 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.
- The loss is 0.69 after many epochs and will not move. What does that number suggest?
A way to think about it
Compute . 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.
- Why does the template clip probabilities only on the path where
from_logitsis 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.
- 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.