_focal_loss
focal_loss
¶
Calculate the focal loss between two tensors.
Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py . Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
This method can be used with TensorFlow tensors:
true = tf.constant([[1], [1], [1], [0], [0], [0]])
pred = tf.constant([[0.97], [0.91], [0.73], [0.27], [0.09], [0.03]])
b = fe.backend.focal_loss(y_pred=pred, y_true=true, gamma=None, alpha=None) #0.1464
b = fe.backend.focal_loss(y_pred=pred, y_true=true, gamma=2.0, alpha=0.25) #0.00395
This method can be used with PyTorch tensors:
true = torch.tensor([[1], [1], [1], [0], [0], [0]])
pred = torch.tensor([[0.97], [0.91], [0.73], [0.27], [0.09], [0.03]])
b = fe.backend.focal_loss(y_pred=pred, y_true=true, gamma=None, alpha=None) #0.1464
b = fe.backend.focal_loss(y_pred=pred, y_true=true, gamma=2.0, alpha=0.25) #0.004
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y_true |
Tensor
|
Ground truth class labels with shape([batch_size, d0, .. dN]), which should take values of 1 or 0. |
required |
y_pred |
Tensor
|
Prediction score for each class, with a shape like y_true. dtype: float32 or float16. |
required |
alpha |
float
|
Weighting factor in range (0,1) to balance positive vs negative examples or (-1/None) to ignore. Default = 0.25 |
0.25
|
gamma |
float
|
Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. |
2.0
|
normalize |
bool
|
Whether to normalize focal loss along samples based on number of positive classes per samples. |
True
|
from_logits |
bool
|
Whether y_pred is logits (without sigmoid). |
False
|
reduction |
str
|
'none' | 'mean' | 'sum' 'none': No reduction will be applied to the output. 'mean': The output will be averaged. 'sum': The output will be summed. |
'mean'
|
Returns:
Type | Description |
---|---|
Tensor
|
The Focal loss between |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in fastestimator\fastestimator\backend\_focal_loss.py
pytorch_focal_loss
¶
Calculate the focal loss between two tensors.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y_true |
torch.Tensor
|
Ground truth class labels with shape([batch_size, d0, .. dN]), which should take values of 1 or 0. |
required |
y_pred |
torch.Tensor
|
Prediction score for each class, with a shape like y_true. dtype: float32 or float16. |
required |
alpha |
float
|
Weighting factor in range (0,1) to balance positive vs negative examples or (-1/None) to ignore. Default = 0.25 |
0.25
|
gamma |
float
|
Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. |
2
|
from_logits |
bool
|
Whether y_pred is logits (without sigmoid). |
False
|
Returns:
Type | Description |
---|---|
torch.Tensor
|
Loss tensor. |