skills/cv/focal-loss/SKILL.md
Alpha-weighted focal loss that down-weights easy examples to focus training on hard, misclassified pixels in imbalanced segmentation tasks.
npx skillsauth add wenmin-wu/ds-skills cv-focal-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.
Focal loss addresses extreme class imbalance in segmentation (e.g., defects covering <1% of pixels). Standard BCE treats all pixels equally, so the loss is dominated by easy negatives. Focal loss adds a modulating factor (1-p_t)^gamma that suppresses the contribution of well-classified examples. With gamma=2, a pixel classified at 0.9 confidence contributes 100x less loss than one at 0.5. Combined with alpha-weighting for positive/negative balance, focal loss typically improves recall on rare classes by 5-15%.
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
def __init__(self, alpha=0.8, gamma=2.0):
super().__init__()
self.alpha = alpha
self.gamma = gamma
def forward(self, inputs, targets):
inputs = torch.sigmoid(inputs).view(-1)
targets = targets.view(-1)
bce = F.binary_cross_entropy(inputs, targets, reduction='none')
p_t = inputs * targets + (1 - inputs) * (1 - targets)
focal_weight = self.alpha * (1 - p_t) ** self.gamma
return (focal_weight * bce).mean()
# Usage
criterion = FocalLoss(alpha=0.8, gamma=2.0)
loss = criterion(logits, masks)
(1-p_t)^gamma to down-weight easy examplesdata-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