Pytorch 如何计算Pytork?中二元分类的交叉熵损失;

Pytorch 如何计算Pytork?中二元分类的交叉熵损失;,pytorch,Pytorch,对于二进制分类,我的输出和标签如下 output = [0.7, 0.3, 0.1, 0.9 ... ] label = [1, 0, 0, 1 ... ] 其中,输出是精确标签=1的概率 我想要这样的交叉熵: def cross_entropy(output, label): return sum(-label * log(output) - (1 - label) * log(1 - output)) 但是,这给了我一个NaN错误,因为在log(output)中,output可能

对于二进制分类,我的输出和标签如下

output = [0.7, 0.3, 0.1, 0.9 ... ]
label = [1, 0, 0, 1 ... ]
其中,输出是
精确标签=1的概率

我想要这样的交叉熵:

def cross_entropy(output, label):
    return sum(-label * log(output) - (1 - label) * log(1 - output))
但是,这给了我一个NaN错误,因为在
log(output)
中,
output
可能为零

我知道有
torch.nn.CrossEntropyLoss
,但它不适用于我的数据格式

import torch
import torch.nn.functional as F
def my_binary_cross_entrophy(output,label):
    label = label.float()
    #print(label)
    loss = 0
    for i in range(len(label)):
        loss += -(label[i]*math.log(output[i])+(1-label[i])*math.log(1-output[i]))
        #print(loss)
    return loss/len(label)

label1 = torch.randint(0,2,(3,)).float()
output = torch.rand(3)
my_binary_cross_entrophy(output,label1)
它返回的值与F.binary\u cross\u熵值相同

F.binary_cross_entropy(output,label1)

正如在对该问题的评论中所提到的,(意思是“二进制交叉熵损失”似乎正是所要求的。

使用
torch.nn.functional.Binary\u Cross\u Entropy
怎么样?或者
torch.nn.BCELoss
?BCE指的是“二进制交叉熵”@Leonard2你为什么不写这个作为答案?需要一点解释来理解你的解决方案。