首页 > 解决方案 > 相当于 PyTorch 中 Keras 的 binary_crossentropy?

问题描述

我想将一些代码从 keras 移植到 pytorch,但我在 PyTorch 中找不到与 Keras 的 binary_crossentropy 等效的东西。PyTorch 的 binary_cross_entropy 与 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]]

有谁知道为什么这两个结果不同?谢谢!

标签: keraspytorch

解决方案


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)

推荐阅读