相当于Keras';PyTorch中的二元交叉熵?

相当于Keras';PyTorch中的二元交叉熵?,keras,pytorch,Keras,Pytorch,我想将一些代码从keras移植到pytorch,但在pytorch中找不到keras的二进制交叉熵的等价物。PyTorch的二元交叉熵与keras的行为不同 import torch import torch.nn.functional as F input = torch.tensor([[ 0.6845, 0.2454], [ 0.7186, 0.3710], [ 0.3480, 0.3374]])

我想将一些代码从keras移植到pytorch,但在pytorch中找不到keras的二进制交叉熵的等价物。PyTorch的二元交叉熵与keras的行为不同

import torch
import torch.nn.functional as F
input = torch.tensor([[ 0.6845,  0.2454],
                      [ 0.7186,  0.3710],
                      [ 0.3480,  0.3374]])
target = torch.tensor([[ 0.,  1.],
                       [ 1.,  1.],
                       [ 1.,  1.]])
F.binary_cross_entropy(input, target, reduce=False)
#tensor([[ 1.1536,  1.4049],
#    [ 0.3305,  0.9916],
#    [ 1.0556,  1.0865]])
import keras.backend as K
K.eval(K.binary_crossentropy(K.variable(input.detach().numpy()), K.variable(target.detach().numpy())))

 #[[11.032836 12.030124]
 #[ 4.486187 10.02776 ]
 #[10.394435 10.563424]]

有人知道为什么这两个结果不同吗?谢谢

Keras二进制交叉熵取
y\u真,y\u pred
,而Pytorch取相反的顺序,因此需要将Keras行更改为

K.eval(K.binary_crossentropy(K.variable(target.detach().numpy()), K.variable(input.detach().numpy())))
通过这种方式,您可以获得正确的输出:

array([[ 1.15359652,  1.40486574],
       [ 0.33045045,  0.99155325],
       [ 1.05555284,  1.0864861 ]], dtype=float32)

Keras二进制交叉熵取
y_true,y_pred
,而Pytorch取相反的顺序,因此需要将Keras行更改为

K.eval(K.binary_crossentropy(K.variable(target.detach().numpy()), K.variable(input.detach().numpy())))
通过这种方式,您可以获得正确的输出:

array([[ 1.15359652,  1.40486574],
       [ 0.33045045,  0.99155325],
       [ 1.05555284,  1.0864861 ]], dtype=float32)