pytorch 中的dim 的作用范围

1. 二维矩阵时

不同的运算, dim 的作用域都是一样的思想;

当数据是二维矩阵时, 可以按照下面的思想理解

对于矩阵:
dim=0 按列操作(沿列向下)。
dim=1 按行操作(跨行)。

解释如下:

dim=0 :这是指张量的第一个维度,通常被视为行。如果您沿此维度应用函数,它将按列处理数据。换句话说,该函数独立地应用于每一列。

dim=1 :这是指张量的第二维,通常被视为列。当您沿此维度应用函数时,它会按行处理数据。也就是说,该函数独立地应用于每一行。

1.1 求和

>> a = torch.Tensor([[1,2,3], [4,5,6]])
>> print(a.shape)
torch.Size([2, 3])

>> print(torch.sum(a, dim=0))
tensor([5., 7., 9.])

>> print(torch.sum(a, dim=1))
tensor([ 6., 15.])

1.2 softmax

dim = 0) #对每一列进行softmax;
dim =1) #对每一行进行softmax;

import torch

import torch.nn.functional as F

x= torch.Tensor( [ [1,2,3,4],[1,2,3,4],[1,2,3,4]])

y1= F.softmax(x, dim = 0) #对每一列进行softmax
print(y1)

y2 = F.softmax(x,dim =1) #对每一行进行softmax
print(y2)

x1 = torch.Tensor([1,2,3,4])
print(x1)

y3 = F.softmax(x1,dim=0) #一维时使用dim=0,使用dim=1报错
print(y3)
(deeplearning) userdeMBP:pytorch user$ python test.py 
tensor([[0.3333, 0.3333, 0.3333, 0.3333],
        [0.3333, 0.3333, 0.3333, 0.3333],
        [0.3333, 0.3333, 0.3333, 0.3333]])
tensor([[0.0321, 0.0871, 0.2369, 0.6439],
        [0.0321, 0.0871, 0.2369, 0.6439],
        [0.0321, 0.0871, 0.2369, 0.6439]])
tensor([1., 2., 3., 4.])
tensor([0.0321, 0.0871, 0.2369, 0.6439])

2. 三维张量时

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

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

在这里插入图片描述
dim= 0,
在这里插入图片描述

dim=1,
在这里插入图片描述

dim =2

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/chumingqian/article/details/134766384