【发布时间】:2021-04-04 02:39:21
【问题描述】:
我找到了here 的帖子。在这里,我们尝试在 PyTorch 中找到 tf.nn.softmax_cross_entropy_with_logits 的等价物。答案仍然让我感到困惑。
这是Tensorflow 2 代码
import tensorflow as tf
import numpy as np
# here we assume 2 batch size with 5 classes
preds = np.array([[.4, 0, 0, 0.6, 0], [.8, 0, 0, 0.2, 0]])
labels = np.array([[0, 0, 0, 1.0, 0], [1.0, 0, 0, 0, 0]])
tf_preds = tf.convert_to_tensor(preds, dtype=tf.float32)
tf_labels = tf.convert_to_tensor(labels, dtype=tf.float32)
loss = tf.nn.softmax_cross_entropy_with_logits(logits=tf_preds, labels=tf_labels)
它给了我loss
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.2427604, 1.0636061], dtype=float32)>
这是PyTorch 代码
import torch
import numpy as np
preds = np.array([[.4, 0, 0, 0.6, 0], [.8, 0, 0, 0.2, 0]])
labels = np.array([[0, 0, 0, 1.0, 0], [1.0, 0, 0, 0, 0]])
torch_preds = torch.tensor(preds).float()
torch_labels = torch.tensor(labels).float()
loss = torch.nn.functional.cross_entropy(torch_preds, torch_labels)
但是,它提出了:
RuntimeError: 一维目标张量,不支持多目标
看来问题还是没有解决。如何在 PyTorch 中实现tf.nn.softmax_cross_entropy_with_logits?
tf.nn.sigmoid_cross_entropy_with_logits 呢?
【问题讨论】:
标签: python pytorch tensorflow2.0 softmax