Download src/binaryforecast/core/loss/focal.py from SPARK-LAB/ST-DTKD: direct link, hf CLI and curl.
- Browser
- Download file 1.89 kB
-
https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/core/loss/focal.py
- Command line
-
hf download hf://SPARK-LAB/ST-DTKD/src/binaryforecast/core/loss/focal.py
-
curl -L -o focal.py https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/core/loss/focal.py
1.89 kB
| """Focal classification loss and training-label class weights.""" | |
| from typing import Optional, Sequence | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| class FocalLoss(nn.Module): | |
| def __init__(self, alpha: Optional[torch.Tensor]=None, gamma: float=2.0, reduction: str='mean'): | |
| super().__init__() | |
| self.gamma = gamma | |
| self.reduction = reduction | |
| if alpha is not None and (not torch.is_tensor(alpha)): | |
| alpha = torch.tensor(alpha, dtype=torch.float32) | |
| self.register_buffer('alpha', alpha if alpha is not None else None) | |
| def forward(self, inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: | |
| ce_loss = F.cross_entropy(inputs, targets, reduction='none') | |
| focal_weight = (1.0 - torch.exp(-ce_loss)) ** self.gamma | |
| if self.alpha is not None: | |
| focal_weight = focal_weight * self.alpha.to(inputs.device)[targets] | |
| loss = focal_weight * ce_loss | |
| if self.reduction == 'mean': | |
| return loss.mean() | |
| if self.reduction == 'sum': | |
| return loss.sum() | |
| if self.reduction == 'none': | |
| return loss | |
| raise ValueError(f'Unsupported reduction: {self.reduction}') | |
| def build_class_weights(counts: Sequence[int], mode: str='sqrt_inv') -> torch.Tensor: | |
| counts_array = np.asarray(counts, dtype=np.float64) | |
| if np.any(counts_array <= 0): | |
| raise ValueError(f'Every training class must be present; counts={counts_array.tolist()}') | |
| if mode == 'none': | |
| weights = np.ones_like(counts_array) | |
| elif mode == 'sqrt_inv': | |
| weights = 1.0 / np.sqrt(counts_array) | |
| elif mode == 'inverse': | |
| weights = 1.0 / counts_array | |
| else: | |
| raise ValueError(f'Unknown class-weight mode: {mode}') | |
| weights /= weights.mean() | |
| return torch.tensor(weights, dtype=torch.float32) | |