torch.nn.BCELoss,torch.nn.BCEWithLogitsLoss中的weight参数和torch.nn.CrossEntropyLoss的weight参数意义不一样,torch.nn.CrossEntropyLoss,torch.nn.BCEWithLogitsLoss的weight是每个class的权重,torch.nn.BCELoss中的weight是每个样本的权重;torch.nn.BCEWithLogitsLoss对于输入都要做一个sigmoid操作再做average(-ylogx-(1-y)log(1-x),这里的x指sigmoid(输入),和torch.nn.CrossEntropyLoss相似,torch.nn.CrossEntropyLoss对于输入都要做一个softmax操作再做average(-ylogx),这里x指softmax(输入)
这里主要详细说明torch.nn.CrossEntropyLoss
https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss
上说torch.nn.CrossEntropyLoss combines nn.LogSoftmax() and nn.NLLLoss()
(即torch.nn.CrossEntropyLoss是nn.LogSoftmax()和nn.NLLLoss()两个操作的结合)
根据上面公式可知torch.nn.CrossEntropyLoss计算一个样本的损失是先对输入做了softmax再做log,但一般softmax这个操作在自己的写的网络的最后一步就有了,在有softmax层的情况下再使用torch.nn.CrossEntropyLoss就对softmax层前的logits进行了两次softmax再进行log计算损失,所以在网络的最后一层为softmax层的时候,不能用torch.nn.CrossEntropyLoss,需要修改
loss_logsoftmax=torch.nn.CrossEntropyLoss()
loss=torch.nn.NLLLoss()
input=tensor([[-0.3209, 0.0796],
[-1.1043, 0.3333],
[ 1.1423, 1.5803]])
input_softmax=torch.nn.Softmax(dim