torch.softmax()

这里区别于max,argmax,这里参数始终都有dim!!!

torch.nn.functional.softmax(inputdim=None_stacklevel=3dtype=None)[SOURCE]

Applies a softmax function.

Softmax is defined as:

\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}Softmax(xi​)=∑j​exp(xj​)exp(xi​)​

It is applied to all slices along dim, and will re-scale them so that the elements lie in the range [0, 1] and sum to 1.

See Softmax for more details.

Parameters

  • input (Tensor) – input

  • dim (int) – A dimension along which softmax will be computed.

  • dtype (torch.dtype, optional) – the desired data type of returned tensor. If specified, the input tensor is casted to before the operation is performed. This is useful for preventing data type overflows. Default: None.dtype

NOTE

This function doesn’t work directly with NLLLoss, which expects the Log to be computed between the Softmax and itself. Use log_softmax instead (it’s faster and has better numerical properties).

softmax作用与模型应用

首先说一下Softmax函数,公式如下:

1. 三维tensor(C,H,W)

一般会设置成dim=0,1,2,-1的情况(可理解为维度索引)。其中2与-1等价,相同效果。

用一张图片来更好理解这个参数dim数值变化:

dim=0时, 是对每一维度相同位置的数值进行 softmax运算,和为1
dim=1时, 是对某一维度的列进行 softmax运算,和为1
dim=2时, 是对某一维度的行进行 softmax运算,和为1

准备工作:先随机生成一个(2,5,4)的矩阵,即两个维度的(5,4)矩阵

import torch 
import torch.nn.functional as F 
input= torch.randn(2,2,3))
print(input)

随机3维矩阵

(1) dim=0

dim=0

(2) dim=1

dim=1

(3) dim=2 或dim=-1

dim=2

dim=-1

2. 四维tensor(B,C,H,W)

是三维tensor的推广,其实三维tensor也可以是batchsize=1的四维tensor,只是dim的索引需要加1.

dim取值0,1,2,3,-1

准备工作:先随机生成一个(2,2,5,4)矩阵。其实随着dim增加(从0到3),相当于一层层剥开。

(1) dim=0

这时的视野应该放在整个tensor,每个batch(不同B)对应位置(相同CHW)求softmax

(2) dim=1

这时向里剥,每小块(不同C)对应位置(相同BHW)求softmax。

(3) dim=2

继续向里剥,每小块(不同H)对应位置(相同BCW)求Softmax。

(4) dim=3 或dim=-1

继续向里剥,也是最后一次。每个小块(不同W)对应元素(相同BCH)求softmax。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值