Loss & Training ยท Easy
Binary Cross-Entropy
Implement stable binary cross entropy with optional weights.
Task
Implement binary_cross_entropy(labels: list[int], probabilities: list[float], sample_weights: list[float] | None = None) -> float. Compute stable binary cross-entropy with optional non-negative sample weights.
Requirements
- Clip every probability to [1e-15, 1 - 1e-15] before taking logarithms.
- Without weights, return the mean loss across examples.
- With weights, divide the weighted loss sum by the sum of weights.
- Return 0.0 for empty inputs or when the total sample weight is zero.
Example
labels = [1, 0]
probabilities = [0.9, 0.2]
sample_weights = [1.0, 3.0]
binary_cross_entropy(labels, probabilities, sample_weights)
# 0.1936977924