如何解释张量大小?

2024-05-16 09:09:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解以下两者之间的差异:

x1 = torch.tensor([1, 2, 3]) # single brackets

x2 = torch.tensor([[1, 2, 3]]) # double brackets

检查尺寸时: x1.size()和{}我们得到以下结果:

torch.Size([3])
torch.Size([1, 3])

我将其解释为x1是(3x1)列向量,而x2是(1x3)行向量

但是,当尝试转置两个向量时: print(x1.T)print(x2.T),我们得到:

tensor([1, 2, 3])
tensor([[1],
        [2],
        [3]])

x1似乎不受转位的影响? 此外,当尝试使用“.view()”强制x1成为(1x3)行向量时: print(x1.view(1, -1))我们得到:

tensor([[1, 2, 3]])  # double brackets

那么为什么“.T”没有做到这一点,但是“.view(1,-1)”能够将x1转换成(1x3)行向量呢

当我们第一次分配它时,它到底是什么


Tags: viewsize尺寸torch差异向量doubletensor
1条回答
网友
1楼 · 发布于 2024-05-16 09:09:53

根据official documentation-

Expects input to be <= 2-D tensor and transposes dimensions 0 and 1. 0-D and 1-D tensors are returned as is. When input is a 2-D tensor this is equivalent to transpose(input, 0, 1).

x = torch.randn(())
torch.t(x)
#tensor(0.1995)

x = torch.randn(3)
x
#tensor([ 2.4320, -0.4608,  0.7702])

torch.t(x)
#tensor([ 2.4320, -0.4608,  0.7702])

x = torch.randn(2, 3)
x
#tensor([[ 0.4875,  0.9158, -0.5872],
#        [ 0.3938, -0.6929,  0.6932]])

torch.t(x)
#tensor([[ 0.4875,  0.3938],
#        [ 0.9158, -0.6929],
#        [-0.5872,  0.6932]])

这就是x1没有效果的原因。它现在是一维张量,而不是二维张量。(3,)(3,1)的形状之间存在差异。第一个轴只有一个轴,而另一个轴有两个轴(类似于您添加的双括号)

这句话在某种程度上是不正确的

x1 #(3,) 1D tensor
x1.reshape((3,1) #(3,1) #2D tensor

x1.T #(1,3) 2D tensor with successful transpose

相关问题 更多 >