Weighted cross-entropyEasynumpylossclassificationimbalancecross-entropy
Weighted cross-entropy
Background
Weighted cross-entropy scales each class's contribution to the loss — the standard fix for class imbalance. Rare classes get larger weights so the model can't ignore them. It generalises plain cross-entropy, which is the special case where all weights equal 1.
Problem statement
Implement weighted_cross_entropy(probs, labels, weights, epsilon=1e-12):
with one-hot labels , predicted probabilities (clipped to avoid ), and per-class weights .
Input
probs—np.ndarray(N, C): predicted class probabilities.labels—np.ndarray(N, C): one-hot true labels.weights—np.ndarray(C,): per-class weights.epsilon—float: clipping constant.
Output
Returns a float: the mean weighted cross-entropy.
Examples
Example 1
Input: probs = [[0.7, 0.3], [0.2, 0.8]], labels = [[1,0],[0,1]], weights = [1.0, 2.0]
Output: 0.4015
Explanation: sample 0 (class 0, weight 1) contributes ; sample 1 (class 1, weight 2) contributes ; the mean is .
Constraints
- Clip
probsto before the log. - Weight each class's log-prob term by
weights[c], sum over classes, then average over samples. - With all weights this reduces to plain cross-entropy.
Notes
- Up-weighting rare classes raises their loss contribution, pushing the optimiser to fit them instead of collapsing to the majority class.
- It is equivalent in expectation to over/under-sampling, but cheaper — it reweights rather than resamples.
Python
Loading...
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example: 0.4015
- •All weights = 1 reduces to plain cross-entropy
- •Higher class weight increases the loss
- •Confident correct predictions -> near 0