|
| 1 | +""" |
| 2 | +Binary Cross-Entropy (BCE) Loss Function |
| 3 | +
|
| 4 | +Description: |
| 5 | +Quantifies dissimilarity between true labels (0 or 1) and predicted probabilities. |
| 6 | +It's widely used in binary classification tasks. |
| 7 | +
|
| 8 | +Formula: |
| 9 | +BCE = -Σ(y_true * log(y_pred) + (1 - y_true) * log(1 - y_pred)) |
| 10 | +
|
| 11 | +Source: |
| 12 | +[Wikipedia - Cross entropy](https://en.wikipedia.org/wiki/Cross_entropy) |
| 13 | +""" |
| 14 | + |
| 15 | +import numpy as np |
| 16 | + |
| 17 | + |
| 18 | +def binary_cross_entropy( |
| 19 | + y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 |
| 20 | +) -> float: |
| 21 | + """ |
| 22 | + Calculate the BCE Loss between true labels and predicted probabilities. |
| 23 | +
|
| 24 | + Parameters: |
| 25 | + - y_true: True binary labels (0 or 1). |
| 26 | + - y_pred: Predicted probabilities for class 1. |
| 27 | + - epsilon: Small constant to avoid numerical instability. |
| 28 | +
|
| 29 | + Returns: |
| 30 | + - bce_loss: Binary Cross-Entropy Loss. |
| 31 | +
|
| 32 | + Example Usage: |
| 33 | + >>> true_labels = np.array([0, 1, 1, 0, 1]) |
| 34 | + >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8]) |
| 35 | + >>> binary_cross_entropy(true_labels, predicted_probs) |
| 36 | + 0.2529995012327421 |
| 37 | + >>> true_labels = np.array([0, 1, 1, 0, 1]) |
| 38 | + >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2]) |
| 39 | + >>> binary_cross_entropy(true_labels, predicted_probs) |
| 40 | + Traceback (most recent call last): |
| 41 | + ... |
| 42 | + ValueError: Input arrays must have the same length. |
| 43 | + """ |
| 44 | + if len(y_true) != len(y_pred): |
| 45 | + raise ValueError("Input arrays must have the same length.") |
| 46 | + # Clip predicted probabilities to avoid log(0) and log(1) |
| 47 | + y_pred = np.clip(y_pred, epsilon, 1 - epsilon) |
| 48 | + |
| 49 | + # Calculate binary cross-entropy loss |
| 50 | + bce_loss = -(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred)) |
| 51 | + |
| 52 | + # Take the mean over all samples |
| 53 | + return np.mean(bce_loss) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + import doctest |
| 58 | + |
| 59 | + doctest.testmod() |
0 commit comments