Spaces:
Running
Running
File size: 8,048 Bytes
9bf4bd7 |
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional, Union
import torch
import torch.nn as nn
from mmocr.registry import MODELS
@MODELS.register_module()
class MaskedBalancedBCEWithLogitsLoss(nn.Module):
"""This loss combines a Sigmoid layers and a masked balanced BCE loss in
one single class. It's AMP-eligible.
Args:
reduction (str, optional): The method to reduce the loss.
Options are 'none', 'mean' and 'sum'. Defaults to 'none'.
negative_ratio (float or int, optional): Maximum ratio of negative
samples to positive ones. Defaults to 3.
fallback_negative_num (int, optional): When the mask contains no
positive samples, the number of negative samples to be sampled.
Defaults to 0.
eps (float, optional): Eps to avoid zero-division error. Defaults to
1e-6.
"""
def __init__(self,
reduction: str = 'none',
negative_ratio: Union[float, int] = 3,
fallback_negative_num: int = 0,
eps: float = 1e-6) -> None:
super().__init__()
assert reduction in ['none', 'mean', 'sum']
assert isinstance(negative_ratio, (float, int))
assert isinstance(fallback_negative_num, int)
assert isinstance(eps, float)
self.eps = eps
self.negative_ratio = negative_ratio
self.reduction = reduction
self.fallback_negative_num = fallback_negative_num
self.loss = nn.BCEWithLogitsLoss(reduction=reduction)
def forward(self,
pred: torch.Tensor,
gt: torch.Tensor,
mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Forward function.
Args:
pred (torch.Tensor): The prediction in any shape.
gt (torch.Tensor): The learning target of the prediction in the
same shape as pred.
mask (torch.Tensor, optional): Binary mask in the same shape of
pred, indicating positive regions to calculate the loss. Whole
region will be taken into account if not provided. Defaults to
None.
Returns:
torch.Tensor: The loss value.
"""
assert pred.size() == gt.size() and gt.numel() > 0
if mask is None:
mask = torch.ones_like(gt)
assert mask.size() == gt.size()
positive = (gt * mask).float()
negative = ((1 - gt) * mask).float()
positive_count = int(positive.sum())
if positive_count == 0:
negative_count = min(
int(negative.sum()), self.fallback_negative_num)
else:
negative_count = min(
int(negative.sum()), int(positive_count * self.negative_ratio))
assert gt.max() <= 1 and gt.min() >= 0
loss = self.loss(pred, gt)
positive_loss = loss * positive
negative_loss = loss * negative
negative_loss, _ = torch.topk(negative_loss.view(-1), negative_count)
balance_loss = (positive_loss.sum() + negative_loss.sum()) / (
positive_count + negative_count + self.eps)
return balance_loss
@MODELS.register_module()
class MaskedBalancedBCELoss(MaskedBalancedBCEWithLogitsLoss):
"""Masked Balanced BCE loss.
Args:
reduction (str, optional): The method to reduce the loss.
Options are 'none', 'mean' and 'sum'. Defaults to 'none'.
negative_ratio (float or int): Maximum ratio of negative
samples to positive ones. Defaults to 3.
fallback_negative_num (int): When the mask contains no
positive samples, the number of negative samples to be sampled.
Defaults to 0.
eps (float): Eps to avoid zero-division error. Defaults to
1e-6.
"""
def __init__(self,
reduction: str = 'none',
negative_ratio: Union[float, int] = 3,
fallback_negative_num: int = 0,
eps: float = 1e-6) -> None:
super().__init__()
assert reduction in ['none', 'mean', 'sum']
assert isinstance(negative_ratio, (float, int))
assert isinstance(fallback_negative_num, int)
assert isinstance(eps, float)
self.eps = eps
self.negative_ratio = negative_ratio
self.reduction = reduction
self.fallback_negative_num = fallback_negative_num
self.loss = nn.BCELoss(reduction=reduction)
def forward(self,
pred: torch.Tensor,
gt: torch.Tensor,
mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Forward function.
Args:
pred (torch.Tensor): The prediction in any shape.
gt (torch.Tensor): The learning target of the prediction in the
same shape as pred.
mask (torch.Tensor, optional): Binary mask in the same shape of
pred, indicating positive regions to calculate the loss. Whole
region will be taken into account if not provided. Defaults to
None.
Returns:
torch.Tensor: The loss value.
"""
assert pred.max() <= 1 and pred.min() >= 0
return super().forward(pred, gt, mask)
@MODELS.register_module()
class MaskedBCEWithLogitsLoss(nn.Module):
"""This loss combines a Sigmoid layers and a masked BCE loss in one single
class. It's AMP-eligible.
Args:
eps (float): Eps to avoid zero-division error. Defaults to
1e-6.
"""
def __init__(self, eps: float = 1e-6) -> None:
super().__init__()
assert isinstance(eps, float)
self.eps = eps
self.loss = nn.BCEWithLogitsLoss(reduction='none')
def forward(self,
pred: torch.Tensor,
gt: torch.Tensor,
mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Forward function.
Args:
pred (torch.Tensor): The prediction in any shape.
gt (torch.Tensor): The learning target of the prediction in the
same shape as pred.
mask (torch.Tensor, optional): Binary mask in the same shape of
pred, indicating positive regions to calculate the loss. Whole
region will be taken into account if not provided. Defaults to
None.
Returns:
torch.Tensor: The loss value.
"""
assert pred.size() == gt.size() and gt.numel() > 0
if mask is None:
mask = torch.ones_like(gt)
assert mask.size() == gt.size()
assert gt.max() <= 1 and gt.min() >= 0
loss = self.loss(pred, gt)
return (loss * mask).sum() / (mask.sum() + self.eps)
@MODELS.register_module()
class MaskedBCELoss(MaskedBCEWithLogitsLoss):
"""Masked BCE loss.
Args:
eps (float): Eps to avoid zero-division error. Defaults to
1e-6.
"""
def __init__(self, eps: float = 1e-6) -> None:
super().__init__()
assert isinstance(eps, float)
self.eps = eps
self.loss = nn.BCELoss(reduction='none')
def forward(self,
pred: torch.Tensor,
gt: torch.Tensor,
mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Forward function.
Args:
pred (torch.Tensor): The prediction in any shape.
gt (torch.Tensor): The learning target of the prediction in the
same shape as pred.
mask (torch.Tensor, optional): Binary mask in the same shape of
pred, indicating positive regions to calculate the loss. Whole
region will be taken into account if not provided. Defaults to
None.
Returns:
torch.Tensor: The loss value.
"""
assert pred.max() <= 1 and pred.min() >= 0
return super().forward(pred, gt, mask)
|