|
| 1 | +# Copyright (c) OpenMMLab. All rights reserved. |
| 2 | +"""Modified from |
| 3 | +https://github.com/JunMa11/SegLoss/blob/master/losses_pytorch/dice_loss.py#L333 |
| 4 | +(Apache-2.0 License)""" |
| 5 | +import torch |
| 6 | +import torch.nn as nn |
| 7 | +import torch.nn.functional as F |
| 8 | + |
| 9 | +from ..builder import LOSSES |
| 10 | +from .utils import get_class_weight, weighted_loss |
| 11 | + |
| 12 | + |
| 13 | +@weighted_loss |
| 14 | +def tversky_loss(pred, |
| 15 | + target, |
| 16 | + valid_mask, |
| 17 | + alpha=0.3, |
| 18 | + beta=0.7, |
| 19 | + smooth=1, |
| 20 | + class_weight=None, |
| 21 | + ignore_index=255): |
| 22 | + assert pred.shape[0] == target.shape[0] |
| 23 | + total_loss = 0 |
| 24 | + num_classes = pred.shape[1] |
| 25 | + for i in range(num_classes): |
| 26 | + if i != ignore_index: |
| 27 | + tversky_loss = binary_tversky_loss( |
| 28 | + pred[:, i], |
| 29 | + target[..., i], |
| 30 | + valid_mask=valid_mask, |
| 31 | + alpha=alpha, |
| 32 | + beta=beta, |
| 33 | + smooth=smooth) |
| 34 | + if class_weight is not None: |
| 35 | + tversky_loss *= class_weight[i] |
| 36 | + total_loss += tversky_loss |
| 37 | + return total_loss / num_classes |
| 38 | + |
| 39 | + |
| 40 | +@weighted_loss |
| 41 | +def binary_tversky_loss(pred, |
| 42 | + target, |
| 43 | + valid_mask, |
| 44 | + alpha=0.3, |
| 45 | + beta=0.7, |
| 46 | + smooth=1): |
| 47 | + assert pred.shape[0] == target.shape[0] |
| 48 | + pred = pred.reshape(pred.shape[0], -1) |
| 49 | + target = target.reshape(target.shape[0], -1) |
| 50 | + valid_mask = valid_mask.reshape(valid_mask.shape[0], -1) |
| 51 | + |
| 52 | + TP = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) |
| 53 | + FP = torch.sum(torch.mul(pred, 1 - target) * valid_mask, dim=1) |
| 54 | + FN = torch.sum(torch.mul(1 - pred, target) * valid_mask, dim=1) |
| 55 | + tversky = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth) |
| 56 | + |
| 57 | + return 1 - tversky |
| 58 | + |
| 59 | + |
| 60 | +@LOSSES.register_module() |
| 61 | +class TverskyLoss(nn.Module): |
| 62 | + """TverskyLoss. This loss is proposed in `Tversky loss function for image |
| 63 | + segmentation using 3D fully convolutional deep networks. |
| 64 | +
|
| 65 | + <https://arxiv.org/abs/1706.05721>`_. |
| 66 | + Args: |
| 67 | + smooth (float): A float number to smooth loss, and avoid NaN error. |
| 68 | + Default: 1. |
| 69 | + class_weight (list[float] | str, optional): Weight of each class. If in |
| 70 | + str format, read them from a file. Defaults to None. |
| 71 | + loss_weight (float, optional): Weight of the loss. Default to 1.0. |
| 72 | + ignore_index (int | None): The label index to be ignored. Default: 255. |
| 73 | + alpha(float, in [0, 1]): |
| 74 | + The coefficient of false positives. Default: 0.3. |
| 75 | + beta (float, in [0, 1]): |
| 76 | + The coefficient of false negatives. Default: 0.7. |
| 77 | + Note: alpha + beta = 1. |
| 78 | + loss_name (str, optional): Name of the loss item. If you want this loss |
| 79 | + item to be included into the backward graph, `loss_` must be the |
| 80 | + prefix of the name. Defaults to 'loss_tversky'. |
| 81 | + """ |
| 82 | + |
| 83 | + def __init__(self, |
| 84 | + smooth=1, |
| 85 | + class_weight=None, |
| 86 | + loss_weight=1.0, |
| 87 | + ignore_index=255, |
| 88 | + alpha=0.3, |
| 89 | + beta=0.7, |
| 90 | + loss_name='loss_tversky'): |
| 91 | + super(TverskyLoss, self).__init__() |
| 92 | + self.smooth = smooth |
| 93 | + self.class_weight = get_class_weight(class_weight) |
| 94 | + self.loss_weight = loss_weight |
| 95 | + self.ignore_index = ignore_index |
| 96 | + assert (alpha + beta == 1.0), 'Sum of alpha and beta but be 1.0!' |
| 97 | + self.alpha = alpha |
| 98 | + self.beta = beta |
| 99 | + self._loss_name = loss_name |
| 100 | + |
| 101 | + def forward(self, pred, target, **kwargs): |
| 102 | + if self.class_weight is not None: |
| 103 | + class_weight = pred.new_tensor(self.class_weight) |
| 104 | + else: |
| 105 | + class_weight = None |
| 106 | + |
| 107 | + pred = F.softmax(pred, dim=1) |
| 108 | + num_classes = pred.shape[1] |
| 109 | + one_hot_target = F.one_hot( |
| 110 | + torch.clamp(target.long(), 0, num_classes - 1), |
| 111 | + num_classes=num_classes) |
| 112 | + valid_mask = (target != self.ignore_index).long() |
| 113 | + |
| 114 | + loss = self.loss_weight * tversky_loss( |
| 115 | + pred, |
| 116 | + one_hot_target, |
| 117 | + valid_mask=valid_mask, |
| 118 | + alpha=self.alpha, |
| 119 | + beta=self.beta, |
| 120 | + smooth=self.smooth, |
| 121 | + class_weight=class_weight, |
| 122 | + ignore_index=self.ignore_index) |
| 123 | + return loss |
| 124 | + |
| 125 | + @property |
| 126 | + def loss_name(self): |
| 127 | + """Loss Name. |
| 128 | +
|
| 129 | + This function must be implemented and will return the name of this |
| 130 | + loss function. This name will be used to combine different loss items |
| 131 | + by simple sum operation. In addition, if you want this loss item to be |
| 132 | + included into the backward graph, `loss_` must be the prefix of the |
| 133 | + name. |
| 134 | + Returns: |
| 135 | + str: The name of this loss item. |
| 136 | + """ |
| 137 | + return self._loss_name |
0 commit comments