Loss & Training · Medium
Sample Weighting
Implement Sample Weighting with production-minded edge case handling.
Task
Implement weighted_mean(losses: list[float], sample_weights: list[float]) -> float. Compute the sample-weighted mean of a sequence of per-example losses.
Requirements
- losses and sample_weights have equal length, and every sample weight is non-negative.
- Multiply each loss by its corresponding sample weight and sum the products.
- Divide the weighted sum by the sum of the sample weights, not by the number of examples.
- Return 0.0 when the inputs are empty or the total sample weight is zero.
- Zero-weight examples must have no effect on the result.
- Do not mutate either input.
Example
weighted_mean([0.2, 0.8, 1.4], [2.0, 1.0, 0.0])
# 0.4