Keras weighted binary crossentropy
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Weighted binary crossentropy assigns different penalties to false positives and false negatives during training. This is essential for imbalanced datasets where one class is much rarer than the other — for example, fraud detection (1% fraud, 99% legitimate) or medical diagnosis (rare diseases). Without weighting, the model learns to predict the majority class and ignores the minority class.
Standard Binary Crossentropy
The standard (unweighted) loss treats both classes equally:
Method 1: class_weight in model.fit()
The simplest approach — pass class weights directly to fit():
This multiplies the loss of each sample by its class weight during backpropagation.
Method 2: Custom Weighted Loss Function
For more control, define a custom loss:
Method 3: Using sample_weight
Apply per-sample weights for fine-grained control:
This is useful when different samples within the same class should have different weights (e.g., based on confidence or importance).
Method 4: tf.nn.weighted_cross_entropy_with_logits
TensorFlow provides a built-in weighted crossentropy that works on logits (pre-sigmoid values):
This is numerically more stable than applying sigmoid first then computing log.
Method 5: Focal Loss
Focal loss down-weights easy examples and focuses on hard ones — useful for extreme imbalance:
Choosing the Right Weight
| Imbalance Ratio | Suggested pos_weight | Notes |
| 1:2 | 2.0 | Mild imbalance |
| 1:10 | 10.0 | Moderate imbalance |
| 1:100 | 50-100 | Severe — consider focal loss |
| 1:1000 | 100-500 | Extreme — combine with resampling |
Evaluation Metrics for Imbalanced Data
Accuracy is misleading with imbalanced data. Use these instead:
Common Pitfalls
- Using accuracy as a metric: A model that predicts all-negative achieves 99% accuracy on a 1:100 dataset. Use precision, recall, F1, and AUC instead.
- Too high pos_weight: Overweighting the positive class causes too many false positives. Start with the inverse class ratio and tune down if precision drops.
- Sigmoid with logits loss:
tf.nn.weighted_cross_entropy_with_logitsexpects raw logits. If your model has a sigmoid output layer, the loss computation is wrong (double sigmoid). Remove the final sigmoid when using logits-based losses. - class_weight vs sample_weight:
class_weightapplies the same weight to all samples of a class.sample_weightallows per-sample weights. They cannot be used simultaneously inmodel.fit(). - Ignoring threshold tuning: The default 0.5 classification threshold is often suboptimal for imbalanced data. Use precision-recall curves to find the best threshold for your use case.
Summary
- Use
class_weightinmodel.fit()for the simplest weighted binary crossentropy approach - Define a custom loss function for more control over the weighting formula
- Use
tf.nn.weighted_cross_entropy_with_logitsfor numerically stable computation on logits - Consider focal loss for extreme class imbalance
- Evaluate with precision, recall, F1, and AUC — never accuracy alone
Related reading
- Keras weighted merge
- Keras why does entire epoch take longer time when it shows all batches are complete?
- Keras with tensorflow-gpu totally freezes PC
- Keras with TensorFlow backend not using GPU
- Keras what does class_weight actually try to balance?
- keras what is the difference between model.predict and model.predict_proba
- Keras,models.add missing 1 required positional argument ''layer''
- KerasRegressor Coefficient of Determination R2 `Score`
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.