对于二维
参考:torch.sum(),dim=0,dim=1解析_(torch.sum(self.v.patch_embed.proj.weight, dim=1)._天青色的瓷的博客-CSDN博客
1.dim=0
纵向压缩
2.dim=1
横向压缩
3.dim=-1(对于高维,维度≥3)
直接看例子
import torch
a = torch.Tensor([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]],
[[[9, 10], [11, 12]], [[13, 14], [15, 16]]],
[[[17, 18], [19, 20]], [[21, 22], [23, 24]]],
[[[25, 26], [27, 28]], [[29, 30], [31, 32]]]])
print(a[-2]) #取该维度下(四维)的倒数第二个元素,即17-24的值
print(torch.sum(a[-2],dim=0))
print(torch.sum(a[-2],dim=1))
print(torch.sum(a[-2],dim=-1))
#输出
'''
tensor([[[17., 18.],
[19., 20.]],
[[21., 22.],
[23., 24.]]])
tensor([[38., 40.],
[42., 44.]])
tensor([[36., 38.],
[44., 46.]])
tensor([[35., 39.],
[43., 47.]])
'''
计算参考示意图
pytorch | softmax(x,dim=-1)参数dim的理解 - 知乎 (zhihu.com)
虽然是softmax的示意图,但是经过我做实验发现当该例子使用该图对得上
dim=0
38=17+21
40=18+22
42=19+23
44=20+24
dim=1
36=17+19
38=18+20
44=21+23
46=22+24
dim=-1/dim=2
35=17+18
39=19+20
43=21+22
47=23+24
即dim=-1时为倒数第一维,即等同于dim=2
经过我做实验确实如此:
学会在实践中成长!!!
fighting!!!