Data Science & ML
Advanced

Binary Cross-Entropy Loss

Loss function for binary classification.

Formula

L=−1n∑[ylog⁡(y^)+(1−y)log⁡(1−y^)]L = -\frac{1}{n}\sum[y\log(\hat{y}) + (1-y)\log(1-\hat{y})]

Variables

yTrue label (0 or 1)
\hat{y}Predicted probability
nSamples

Example

y=1, p=0.9: loss = -log(0.9) = 0.105

How it works

Binary cross-entropy measures how well a model’s predicted probability matches the true 0/1 label by penalizing confident wrong answers very heavily and confident correct answers only lightly. It comes directly from the negative log-likelihood of a Bernoulli outcome, so minimizing it is equivalent to maximizing the probability assigned to the observed labels. The two terms, y log(ŷ) and (1-y) log(1-ŷ), ensure the loss only rewards the probability of the correct class and ignores the other one for each sample.

When to use it

Use this loss for binary classification tasks where the model outputs a probability for one class, such as spam detection, disease screening, fraud detection, or yes/no prediction. It is the standard choice when you want probabilistic predictions and a smooth objective that works well with gradient-based optimization.

Worked example, step by step

Suppose there are n = 4 samples with true labels y = [1, 0, 1, 0] and predicted probabilities ŷ = [0.8, 0.3, 0.6, 0.1]. For each sample, compute the loss term: Sample 1: -[1·log(0.8) + 0·log(1-0.8)] = -log(0.8) = 0.2231 Sample 2: -[0·log(0.3) + 1·log(1-0.3)] = -log(0.7) = 0.3567 Sample 3: -[1·log(0.6) + 0·log(1-0.6)] = -log(0.6) = 0.5108 Sample 4: -[0·log(0.1) + 1·log(1-0.1)] = -log(0.9) = 0.1054 Average loss: L = (0.2231 + 0.3567 + 0.5108 + 0.1054) / 4 = 1.1960 / 4 = 0.2990

Common mistakes to avoid

  • Using predicted class labels 0/1 instead of predicted probabilities in the logarithms
  • Forgetting to average over all n samples when computing the final loss
  • Taking log(0) or using exact 0 and 1 probabilities without numerical clipping, which causes undefined or infinite loss

Did You Know?

Cross-entropy comes from information theory and measures surprise.

Share this formula

Reviewed & maintained by the FormulaWon editorial teamLast reviewed September 2026