简单明了的Softmax解析

Pytorch Softmax用法

原文链接:https://blog.csdn.net/sinat_40258777/article/details/120275989


pytorch中的softmax主要存在于两个包中分别是:
torch.nn.Softmax(dim=None)
torch.nn.functional.softmax(input, dim=None, _stacklevel=3, dtype=None)
下面分别介绍其用法:
torch.nn.Softmax
torch.nn.Softmax中只要一个参数:来制定归一化维度如果是dim=0指代的是行,dim=1指代的是列。

import torch 
import torch.nn as nn
input_0 = torch.Tensor([1,2,3,4])
input_1 = torch.Tensor([[1,2,3,4],[5,6,7,8]])
#规定不同方向的softmax
softmax_0 = nn.Softmax(dim=0)
softmax_1 = nn.Softmax(dim=1 )
#对不同维度的张量试验
output_0 = softmax_0(input_0)
output_1 = softmax_1(input_1)
output_2 = softmax_0(input_1)
#输出
print(output_0)
print(output_1)
print(output_2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
输出:

tensor([0.0321, 0.0871, 0.2369, 0.6439])
tensor([[0.0321, 0.0871, 0.2369, 0.6439],
        [0.0321, 0.0871, 0.2369, 0.6439]])
tensor([[0.0180, 0.0180, 0.0180, 0.0180],
        [0.9820, 0.9820, 0.9820, 0.9820]])
1
2
3
4
5
torch.nn.functional.softmax
与上面介绍不同的是torch.nn.Softmax,多了一个参数(input:输入的张量)

import torch 
import  torch.nn.functional as F
input_0 = torch.Tensor([1,2,3,4])
input_1 = torch.Tensor([[1,2,3,4],[5,6,7,8]])
output_0 = F.softmax(input_0)
output_1 = F.softmax(input_1,dim=0)
output_2 = F.softmax(input_1,dim=1)
print(output_0)
print(output_1)
print(output_2)
1
2
3
4
5
6
7
8
9
10
输出

tensor([0.0321, 0.0871, 0.2369, 0.6439])
tensor([[0.0180, 0.0180, 0.0180, 0.0180],
        [0.9820, 0.9820, 0.9820, 0.9820]])
tensor([[0.0321, 0.0871, 0.2369, 0.6439],
        [0.0321, 0.0871, 0.2369, 0.6439]])
1
2
3
4
5
对于log_softmax和softmax用法一模一样,但是输出结果不一样本
对于一些较大的数可以采取log_softmax,来防止溢出
 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值