Last active
June 20, 2022 17:15
-
-
Save alex-vasilchenko-md/79ac41a33e50dffb7792edd7ff7779d5 to your computer and use it in GitHub Desktop.
A little composition wrapper for Pytorch loss functions. It calculates weighted sum of multiple loss functions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections.abc import Collection | |
from torch import nn | |
class WeightedSumCompositionLoss(nn.Module): | |
def __init__(self, loss_funcs: Collection, weights: Collection): | |
super().__init__() | |
self.loss_funcs = loss_funcs | |
self.weights = weights | |
def forward(self, output, target): | |
loss = 0. | |
for idx in range(len(self.loss_funcs)): | |
loss += self.loss_funcs[idx].forward(output, target) * self.weights[idx] | |
return loss | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A little composition wrapper for Pytorch loss functions. It calculates weighted sum of multiple loss functions.
Example how to use: