最近需要一种自定义loss,可以对每个实例的loss进行不同的加权。在网上找到的代码,没有我想要的,因此首先对torch的loss进行了研究。
torch的loss有包装在nn.Module之中的,有在nn.functional之中的,两种的区别就是前者需要torch对参数进行维护,如果没有parameter不用算梯度的话,就是多占了几个参数的区别而已。torch本身的nn.BCEloss就是调用了一个functional叫binary_cross_entropy,代码非常简单。
class BCELoss(_WeightedLoss):
__constants__ = ['reduction', 'weight']
def __init__(self, weight=None, size_average=None, reduce=None, reduction='mean'):
super(BCELoss, self).__init__(weight, size_average, reduce, reduction)
def forward(self, input, target):
return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
而torch之中是有两个loss的大类的,分别是_Loss和_WeightedLoss
class _Loss(Module):
def __init__(self, size_average=None, reduce=None, reduction='mean'):
supe