首页 > 解决方案 > torch.nn.Softmax 中的 dim 参数的用途是什么

问题描述

我不明白 dim 参数在 torch.nn.Softmax 中适用什么。有一个警告告诉我使用它,我将它设置为 1,但我不明白我在设置什么。它在公式中的位置:

Softmax(xi​)=exp(xi)/∑j​exp(xj​)​

这里没有暗淡,那么它适用于什么?

标签: pytorchsoftmax

解决方案


torch.nn.Softmax 上的 Pytorch文档指出: dim (int) – 计算 Softmax 的维度(因此沿 dim 的每个切片总和为 1)。

例如,如果您有一个二维矩阵,您可以选择是将 softmax 应用于行还是列:

import torch 
import numpy as np

softmax0 = torch.nn.Softmax(dim=0) # Applies along columns
softmax1 = torch.nn.Softmax(dim=1) # Applies along rows 

v = np.array([[1,2,3],
              [4,5,6]])
v =  torch.from_numpy(v).float()

softmax0(v)
# Returns
#[[0.0474, 0.0474, 0.0474],
# [0.9526, 0.9526, 0.9526]])


softmax1(v)
# Returns
#[[0.0900, 0.2447, 0.6652],
# [0.0900, 0.2447, 0.6652]]

注意 softmax0 的列如何加到 1,而 softmax1 的行如何加到 1。


推荐阅读