MCPcopy Create free account
hub / github.com/MotrixLab/FineMoGen / weighted_loss

Function weighted_loss

mogen/models/losses/utils.py:52–90  ·  view source on GitHub ↗

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 argu

(loss_func)

Source from the content-addressed store, hash-verified

50
51
52def weighted_loss(loss_func):
53 """Create a weighted version of a given loss function.
54 To use this decorator, the loss function must have the signature like
55 `loss_func(pred, target, **kwargs)`. The function only needs to compute
56 element-wise loss without any reduction. This decorator will add weight
57 and reduction arguments to the function. The decorated function will have
58 the signature like `loss_func(pred, target, weight=None, reduction='mean',
59 avg_factor=None, **kwargs)`.
60 :Example:
61 >>> import torch
62 >>> @weighted_loss
63 >>> def l1_loss(pred, target):
64 >>> return (pred - target).abs()
65 >>> pred = torch.Tensor([0, 2, 3])
66 >>> target = torch.Tensor([1, 1, 1])
67 >>> weight = torch.Tensor([1, 0, 1])
68 >>> l1_loss(pred, target)
69 tensor(1.3333)
70 >>> l1_loss(pred, target, weight)
71 tensor(1.)
72 >>> l1_loss(pred, target, reduction='none')
73 tensor([1., 1., 2.])
74 >>> l1_loss(pred, target, weight, avg_factor=2)
75 tensor(1.5000)
76 """
77
78 @functools.wraps(loss_func)
79 def wrapper(pred,
80 target,
81 weight=None,
82 reduction='mean',
83 avg_factor=None,
84 **kwargs):
85 # get element-wise loss
86 loss = loss_func(pred, target, **kwargs)
87 loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
88 return loss
89
90 return wrapper
91
92
93def convert_to_one_hot(targets: torch.Tensor, classes) -> torch.Tensor:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected