Create a weighted version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arg
(loss_func: Callable)
| 66 | |
| 67 | |
| 68 | def weighted_loss(loss_func: Callable) -> Callable: |
| 69 | """Create a weighted version of a given loss function. |
| 70 | |
| 71 | To use this decorator, the loss function must have the signature like |
| 72 | `loss_func(pred, target, **kwargs)`. The function only needs to compute |
| 73 | element-wise loss without any reduction. This decorator will add weight |
| 74 | and reduction arguments to the function. The decorated function will have |
| 75 | the signature like `loss_func(pred, target, weight=None, reduction='mean', |
| 76 | avg_factor=None, **kwargs)`. |
| 77 | |
| 78 | :Example: |
| 79 | |
| 80 | >>> import torch |
| 81 | >>> @weighted_loss |
| 82 | >>> def l1_loss(pred, target): |
| 83 | >>> return (pred - target).abs() |
| 84 | |
| 85 | >>> pred = torch.Tensor([0, 2, 3]) |
| 86 | >>> target = torch.Tensor([1, 1, 1]) |
| 87 | >>> weight = torch.Tensor([1, 0, 1]) |
| 88 | |
| 89 | >>> l1_loss(pred, target) |
| 90 | tensor(1.3333) |
| 91 | >>> l1_loss(pred, target, weight) |
| 92 | tensor(1.) |
| 93 | >>> l1_loss(pred, target, reduction='none') |
| 94 | tensor([1., 1., 2.]) |
| 95 | >>> l1_loss(pred, target, weight, avg_factor=2) |
| 96 | tensor(1.5000) |
| 97 | """ |
| 98 | |
| 99 | @functools.wraps(loss_func) |
| 100 | def wrapper(pred: Tensor, |
| 101 | target: Tensor, |
| 102 | weight: Optional[Tensor] = None, |
| 103 | reduction: str = 'mean', |
| 104 | avg_factor: Optional[int] = None, |
| 105 | **kwargs) -> Tensor: |
| 106 | """ |
| 107 | Args: |
| 108 | pred (Tensor): The prediction. |
| 109 | target (Tensor): Target bboxes. |
| 110 | weight (Optional[Tensor], optional): The weight of loss for each |
| 111 | prediction. Defaults to None. |
| 112 | reduction (str, optional): Options are "none", "mean" and "sum". |
| 113 | Defaults to 'mean'. |
| 114 | avg_factor (Optional[int], optional): Average factor that is used |
| 115 | to average the loss. Defaults to None. |
| 116 | |
| 117 | Returns: |
| 118 | Tensor: Loss tensor. |
| 119 | """ |
| 120 | # get element-wise loss |
| 121 | loss = loss_func(pred, target, **kwargs) |
| 122 | loss = weight_reduce_loss(loss, weight, reduction, avg_factor) |
| 123 | return loss |
| 124 | |
| 125 | return wrapper |
nothing calls this directly
no outgoing calls
no test coverage detected