我正在计算损失的多类(7)分类程序使用pytorch。
class AFL(nn.Module):
def __init__(self, delta=0.7, gamma=2., epsilon=1e-07):
super(AFL, self).__init__()
self.delta = delta
self.gamma = gamma
self.epsilon = epsilon
def forward(self, y_pred, y_true):
#y_pred=y_pred.size()[1]
print(y_pred.shape) #[32,7]
print(y_true.shape) #[32]
y_pred = torch.clamp(y_pred, self.epsilon, 1. - self.epsilon)
cross_entropy = np.empty(y_pred.shape)
for i in range(len(y_pred)):
for j in range(len(y_pred[i])):
cross_entropy[i][j] = -y_true * torch.log(y_pred[i][j])
#cross_entropy = -y_true * torch.log(y_pred[0][0]) #here i want to calculate cross_entropy for for each class
# Calculate losses separately for each class, only suppressing background class
back_ce = torch.pow(1 - y_pred[:,0], self.gamma) * cross_entropy[:,0]
back_ce = (1 - self.delta) * back_ce
fore_ce = cross_entropy[:,1,:,:]
fore_ce = self.delta * fore_ce
loss = torch.mean(torch.sum(torch.stack([back_ce, fore_ce], axis=-1), axis=-1))
return loss
我想分别计算每个类的back_ce,但得到的误差为:
back_ce = torch.pow(1 - y_pred[:,0], self.gamma) * cross_entropy[:,0]
IndexError: too many indices for tensor of dimension 1
有人能告诉我哪里做错了吗?提到了y_pred和y_true的大小。
1条答案
按热度按时间ycl3bljg1#
以下是具有多个常见类和罕见类的多类的AFL。
为了使用这个,
输出: