【Pytorch】torch.nn. Softmax()

117 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

在这里插入图片描述

简介

Hello!

非常感谢您阅读海轰的文章,倘若文中有错误的地方,欢迎您指出~  

ଘ(੭ˊᵕˋ)੭

昵称:海轰

标签:程序猿|C++选手|学生

简介:因C语言结识编程,随后转入计算机专业,获得过国家奖学金,有幸在竞赛中拿过一些国奖、省奖...已保研

学习经验:扎实基础 + 多做笔记 + 多敲代码 + 多思考 + 学好英语!

唯有努力💪

torch.nn.Softmax()

语法

torch.nn.Softmax(dim=None)

  • dim (int) :计算 Softmax 的维度(因此沿 dim 的每个切片的总和为 1)。

return

  • 一个与输入具有相同维度和形状的张量,其值在 [0, 1] 范围内

作用

将 Softmax 函数应用于 n 维输入张量,重新缩放它们,使 n 维输出张量的元素位于 [0,1] 范围内并且总和为 1

Applies the Softmax function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range [0,1] and sum to 1.

Softmax定义:

在这里插入图片描述

当输入张量是稀疏张量时,未指定的值将被视为 -inf

举例

m = nn.Softmax(dim=0)
input = torch.tensor([[1.,2,3],[4,5,6]])
output = m(input)

print('input : \n', input)
print('output : \n', output)

在这里插入图片描述


m = nn.Softmax(dim=1)
input = torch.tensor([[1.,2,3],[4,5,6]])
output = m(input)

print('input : \n', input)
print('output : \n', output)

在这里插入图片描述

以上的区别在于dim=0 or dim=1

也就是进行softmax运算选择的那一维度

dim=0,第一维,Pytorch是列优先

在这里插入图片描述

dim=1,第二维,按行

在这里插入图片描述

注意:

  • dim = -1 也就是按最后一维
  • 进入softmax需为float类型

参考

结语

文章仅作为个人学习笔记记录,记录从0到1的一个过程

希望对您有一点点帮助,如有错误欢迎小伙伴指正

在这里插入图片描述