Calculate the mean binary cross-entropy (BCE) loss between true labels and predicted probabilities. BCE loss quantifies dissimilarity between true labels (0 or 1) and predicted probabilities. It's widely used in binary classification tasks. BCE = -Σ(y_true * ln(y_pred) + (1 -
(
y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15
)
| 2 | |
| 3 | |
| 4 | def binary_cross_entropy( |
| 5 | y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15 |
| 6 | ) -> float: |
| 7 | """ |
| 8 | Calculate the mean binary cross-entropy (BCE) loss between true labels and predicted |
| 9 | probabilities. |
| 10 | |
| 11 | BCE loss quantifies dissimilarity between true labels (0 or 1) and predicted |
| 12 | probabilities. It's widely used in binary classification tasks. |
| 13 | |
| 14 | BCE = -Σ(y_true * ln(y_pred) + (1 - y_true) * ln(1 - y_pred)) |
| 15 | |
| 16 | Reference: https://en.wikipedia.org/wiki/Cross_entropy |
| 17 | |
| 18 | Parameters: |
| 19 | - y_true: True binary labels (0 or 1) |
| 20 | - y_pred: Predicted probabilities for class 1 |
| 21 | - epsilon: Small constant to avoid numerical instability |
| 22 | |
| 23 | >>> true_labels = np.array([0, 1, 1, 0, 1]) |
| 24 | >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8]) |
| 25 | >>> float(binary_cross_entropy(true_labels, predicted_probs)) |
| 26 | 0.2529995012327421 |
| 27 | >>> true_labels = np.array([0, 1, 1, 0, 1]) |
| 28 | >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2]) |
| 29 | >>> binary_cross_entropy(true_labels, predicted_probs) |
| 30 | Traceback (most recent call last): |
| 31 | ... |
| 32 | ValueError: Input arrays must have the same length. |
| 33 | """ |
| 34 | if len(y_true) != len(y_pred): |
| 35 | raise ValueError("Input arrays must have the same length.") |
| 36 | |
| 37 | y_pred = np.clip(y_pred, epsilon, 1 - epsilon) # Clip predictions to avoid log(0) |
| 38 | bce_loss = -(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred)) |
| 39 | return np.mean(bce_loss) |
| 40 | |
| 41 | |
| 42 | def binary_focal_cross_entropy( |
nothing calls this directly
no outgoing calls
no test coverage detected