实例化:
lossfn_class = nn.NLLLoss()
lossfn_center = Centerloss(lambdas=2, feature_num=2, class_num=10).to(device)
使用:
loss_class = lossfn_class(output, y)
y = y.float()
loss_center = lossfn_center(feature, y)
loss = loss_class + loss_center
class Centerloss(nn.Module):
def __init__(self, lambdas=2, feature_num=2, class_num=10):
super().__init__()
self.lambdas = lambdas
self.center = nn.Parameter(torch.randn(class_num, feature_num), requires_grad=True)
def forward(self, feature, label):
'''每个lable对应的中心点列成一个新的矩阵'''
feature=nn.functional.normalize(feature)
center_exp = self.center.index_select(dim=0, index=label.long())
count = torch.histc(label, bins=int(max(label).item() + 1), min=0, max=int(max(label).item()))
'''每个lable对应种类的个数形成的一个新的一维向量'''
count_exp = count.index_select(dim=0, index=label.long())
loss = self.lambdas / 2 * torch.mean(torch.div(torch.sum(torch.pow(feature - center_exp, 2), dim=1), count_exp))
return loss