📘
Binary Cross-Entropy Loss
EasyClassification
Compute the binary cross-entropy loss (log loss) for a set of predictions.
Given true labels yi∈{0,1} and predicted probabilities y^i∈(0,1):
BCE=−n1∑i=1n[yilog(y^i)+(1−yi)log(1−y^i)]
To avoid log(0), clip predictions to the range [ϵ,1−ϵ] where ϵ=10−7.
Return the loss rounded to 4 decimal places.
Example:
Input:
y_true = [1, 0, 1] y_pred = [0.9, 0.1, 0.8]
Output:
0.1446
Reasoning:
- First, we clip the predicted probabilities to the range [ϵ,1−ϵ] where ϵ=10−7: ypred=[0.9,0.1,0.8] remains the same since all values are within the range.
- Then, we calculate the binary cross-entropy loss for each sample:
- For yi=1 and y^i=0.9, the loss is −log(0.9)
- For yi=0 and y^i=0.1, the loss is −log(1−0.1)=−log(0.9)
- For yi=1 and y^i=0.8, the loss is −log(0.8)
- Next, we calculate the total loss by summing the individual losses and dividing by the number of samples n=3: BCE=−31[log(0.9)+log(0.9)+log(0.8)]
- The final output is the loss rounded to 4 decimal places: BCE≈0.1446
Constraints:
- y_true: list of 0s and 1s
- y_pred: list of predicted probabilities (0 to 1)
- Clip predictions to [1e-7, 1-1e-7] before computing log
- Return a single float rounded to 4 decimal places
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.