python - Pytorch - 在 softmax 层之后选择最佳概率

标签 python numpy pytorch softmax

我有一个使用 Pytorch 0.4.0 的逻辑回归模型,其中我的输入是高维的,我的输出必须是标量 - 012.

我使用线性层与 softmax 层相结合来返回 n x 3 张量,其中每列表示输入属于三个类别之一的概率 (0 12)。

但是,我必须返回一个 n x 1 张量,因此我需要以某种方式为每个输入选择最高概率,并创建一个张量来指示哪个类具有最高概率。我如何使用 Pytorch 实现这一目标?

为了说明这一点,我的 Softmax 输出如下:

[[0.2, 0.1, 0.7],
 [0.6, 0.2, 0.2],
 [0.1, 0.8, 0.1]]

我必须返回这个:

[[2],
 [0],
 [1]]

最佳答案

torch.argmax()可能是您想要的:

import torch

x = torch.FloatTensor([[0.2, 0.1, 0.7],
                       [0.6, 0.2, 0.2],
                       [0.1, 0.8, 0.1]])

y = torch.argmax(x, dim=1)
print(y.detach())
# tensor([ 2,  0,  1])

# If you want to reshape:
y = y.view(1, -1)
print(y.detach())
# tensor([[ 2,  0,  1]])

关于python - Pytorch - 在 softmax 层之后选择最佳概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55545995/

相关文章:

python - 在远程 Unix 计算机上执行本地脚本时出现问题

Python tarfile 压缩内存中的一个对象

python - 将一个空的 pandas DataFrame 与一个 Multiindex DataFrame 连接起来

php - 类似于Django的runserver的PHP本地测试服务器

python - 使用 == 比较 numpy 数组的规则是什么?

python - 关于梯度累积的澄清

python - 如何从自定义数据格式创建 scipy 数组?

python - 在 Numpy 中遍历二维线?

python - Pytorch 获取运行时错误 : Found dtype Double but expected Float

python - Pytorch 教程损失没有按预期减少