skills/cv/weighted-bce-loss/SKILL.md
BCE loss with per-class asymmetric positive/negative weights to match competition metrics or handle class imbalance in multilabel classification.
npx skillsauth add wenmin-wu/ds-skills cv-weighted-bce-lossInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Standard BCE treats false positives and false negatives equally across all classes. In medical imaging and multilabel tasks, certain classes matter more (e.g., missing a fracture is worse than a false alarm). This loss applies separate positive and negative weights per class, normalizing per sample so that the total contribution stays balanced. Matches competition scoring functions that penalize certain errors more heavily.
import torch
import torch.nn.functional as F
def weighted_bce_loss(logits, targets, pos_weights, neg_weights, reduction='mean'):
"""BCE with per-class asymmetric weights.
Args:
logits: (B, C) raw model output
targets: (B, C) binary targets
pos_weights: (C,) weight for positive samples per class
neg_weights: (C,) weight for negative samples per class
"""
loss = F.binary_cross_entropy_with_logits(logits, targets, reduction='none')
weights = targets * pos_weights.unsqueeze(0) + (1 - targets) * neg_weights.unsqueeze(0)
loss = loss * weights
# Normalize per sample
norm = weights.sum(dim=1, keepdim=True)
loss = (loss / norm).sum(dim=1)
return loss.mean() if reduction == 'mean' else loss
# Example: fracture detection — penalize missed fractures 2x
pos_w = torch.tensor([14., 2., 2., 2., 2., 2., 2., 2.])
neg_w = torch.tensor([7., 1., 1., 1., 1., 1., 1., 1.])
loss = weighted_bce_loss(logits, targets, pos_w, neg_w)
pos_weight = neg_count / pos_count)BCEWithLogitsLoss(pos_weight=...) only supports positive weights, not separate pos/negdata-ai
Scaled Pinball Loss (SPL) metric for evaluating quantile forecasts, normalized by mean absolute successive differences of training data
data-ai
Walk backward through a time series and multiplicatively rescale segments when jumps exceed a fraction of the running mean to correct data collection anomalies
testing
Transform forecasting target to next/current ratio minus one so that optimizing MAE or squared error implicitly minimizes SMAPE
tools
Convert point forecasts to prediction intervals by scaling with logit-transformed quantile ratios passed through a Normal CDF