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/50776548/

相关文章:

linear-regression - 模型参数初始化

python - Boto3 - 删除具有特定分区键的所有项目

python - Keras准确率和实际准确率正好相反

python - 格式化数据的快速查询

python - required_grad 在 PyTorch 中做什么? (不要求_grad)

pytorch - `*** RuntimeError: mat1 dim 1 must match mat2 dim 0` 每当我运行模型(图像)

python - 解析二维数组中的字符串推送值

python - Django REST 框架 : how to make verbose name of field differ from its field_name?

python - numpy - 尝试计算成本函数时出现形状错误

python - 加速 Numpy Meshgrid 命令