File size: 1,890 Bytes
21419ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""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)