Pytorch - Pick best probability after softmax layer(Pytorch - 在 softmax 层之后选择最佳概率)
问题描述
我有一个使用 Pytorch 0.4.0 的逻辑回归模型,其中我的输入是高维的,我的输出必须是标量 - 0、1 或 2.
I have a logistic regression model using Pytorch 0.4.0, where my input is high-dimensional and my output must be a scalar - 0, 1 or 2.
我使用一个线性层和一个 softmax 层组合来返回一个 nx 3 张量,其中每一列代表输入落入三个类别之一的概率(0、1 或 2).
I'm using a linear layer combined with a softmax layer to return a n x 3 tensor, where each column represents the probability of the input falling in one of the three classes (0, 1 or 2).
但是,我必须返回一个 n x 1 张量,因此我需要以某种方式为每个输入选择最高概率并创建一个张量,指示哪个类别的概率最高.如何使用 Pytorch 实现这一目标?
However, I must return a n x 1 tensor, so I need to somehow pick the highest probability for each input and create a tensor indicating which class had the highest probability. How can I achieve this using Pytorch?
为了说明,我的 Softmax 输出如下:
To illustrate, my Softmax outputs this:
[[0.2, 0.1, 0.7],
[0.6, 0.2, 0.2],
[0.1, 0.8, 0.1]]
我必须返回这个:
[[2],
[0],
[1]]
推荐答案
torch.argmax() 可能就是你想要的:
torch.argmax() is probably what you want:
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]])
这篇关于Pytorch - 在 softmax 层之后选择最佳概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Pytorch - 在 softmax 层之后选择最佳概率
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
