Compute total and average binary cross-entropy loss
Quick Overview
Write a function that returns both the total and the average binary cross-entropy for a set of labels and predicted probabilities. It tests the log-loss formula, vectorized NumPy, returning native Python floats, and when a summed loss is more useful than a mean.
Compute total and average binary cross-entropy loss
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `total_and_average_cost(y_true, y_pred)` returning `(total_cost, average_cost)` for binary cross-entropy: the sum of the per-sample losses, and that sum divided by `n`.
The function must follow these rules:
- `y_true` is a 1-D array of 0/1 labels with shape `(n,)`. `y_pred` is a 1-D array of predicted P(y=1) with shape `(n,)`, strictly inside `(0, 1)`.
- The per-sample loss is `-(y*ln(p) + (1-y)*ln(1-p))`, using the natural log.
- Return a 2-tuple of native Python floats (cast with `float(...)`).
For example:
```python
y_true = [1, 0, 1, 1, 0]
y_pred = [0.9, 0.1, 0.8, 0.6, 0.3]
total_and_average_cost(y_true, y_pred)
# (1.3013651503345853, 0.26027303006691704)
```
```hint Look at one sample at a time
Write out the loss for a sample with y = 1 and for one with y = 0. Only one of the two log terms survives in each case.
```
### Constraints & Assumptions
- Inputs are guaranteed valid: every prediction is strictly between 0 and 1, so no clipping or epsilon is needed.
- `y_true` and `y_pred` have the same length `n`.
### What a Strong Answer Covers
- The per-sample binary cross-entropy with the natural log, computed in a vectorized way.
- The total as the sum and the average as that sum divided by `n`, so the two always agree.
- Native Python floats in the returned tuple.
- What would break in a real implementation if a prediction reached exactly 0 or 1.
### Follow-up Questions
- Why guard against `p = 0` or `p = 1` in a real implementation?
- When would you prefer total cost over average cost?
- How would you compute the same loss from logits without forming probabilities first?
Overview: Write a function that returns both the total and the average binary cross-entropy for a set of labels and predicted probabilities. It tests the log-loss formula, vectorized NumPy, returning native Python floats, and when a summed loss is more useful than a mean.
Compute total and average binary cross-entropy loss
General
Nov 25, 2026
easyData ScientistOtherMachine Learning
0
0
Implement total_and_average_cost(y_true, y_pred) returning (total_cost, average_cost) for binary cross-entropy: the sum of the per-sample losses, and that sum divided by n.
The function must follow these rules:
y_true
is a 1-D array of 0/1 labels with shape
(n,)
.
y_pred
is a 1-D array of predicted P(y=1) with shape
(n,)
, strictly inside
(0, 1)
.
The per-sample loss is
-(y*ln(p) + (1-y)*ln(1-p))
, using the natural log.
Return a 2-tuple of native Python floats (cast with
float(...)
).