Tensor.shape[0]的理解
初学python和pytorch,一直对 T e n s o r . s h a p e [ 0 ] , T e n s o r . s h a p e [ 1 ] , T e n s o r . s h a p e [ 2 ] Tensor.shape[0],Tensor.shape[1],Tensor.shape[2] Tensor.shape[0],Tensor.shape[1],Tensor.shape[2]等等的理解有疑惑。
对于 t o r c h . r a n d ( 3 , 4 , 5 , . . ) 这 种 超 过 二 维 的 T e n s o r , s h a p e [ 0 ] torch.rand(3,4,5,..)这种超过二维的Tensor,shape[0] torch.rand(3,4,5,..)这种超过二维的Tensor,shape[0]等等代表了它的对应维度的数值,这很好理解:
b = torch.rand(3,4)
tensor([[0.2079, 0.2861, 0.8555, 0.3366],
[0.1264, 0.6924, 0.6601, 0.8238],
[0.2413, 0.6084, 0.3180, 0.3877]])
b.shape
torch.Size([3, 4])
b.shape[0]
3
以此类推, t o r c h . r a n d ( 6 ) . s h a p e [ 0 ] = 6 torch.rand(6).shape[0] = 6 torch.rand(6).shape[0]=6是毫无疑问的:
b = torch.rand(6)
tensor([0.1015, 0.2721, 0.3469, 0.7138, 0.5913, 0.6235])
b.shape
torch.Size([6])
b.shape[0]
6
等等,明明打印的是一行Tensor,为什么会是6呢?
这有一个思维误区,即 t o r c h . r a n d ( 6 ) 与 t o r c h . r a n d ( 1 , 6 ) torch.rand(6)与torch.rand(1,6) torch.rand(6)与torch.rand(1,6)的区别
b = torch.rand(1,6)
tensor([[0.9991, 0.9873, 0.8410, 0.5159, 0.1541, 0.8908]])
b.shape
torch.Size([1, 6])
b.shape[0]
1
仔细观察二者区别,虽然都是平铺打印出来的,但是 t o r c h . r a n d ( 1 , 6 ) 比 t o r c h . r a n d ( 6 ) torch.rand(1,6)比torch.rand(6) torch.rand(1,6)比torch.rand(6)多了一个维度,即多了一个中括号。
t o r c h . r a n d ( 6 ) torch.rand(6) torch.rand(6)看起来一个1行6列的矩阵,实际上它只有一个维度6,帮助理解的话就是:创建Tensor的时候优先创建行,行是第一维,所以它其实是没有列的,可以认为它是一个6行的张量,也就是应该是竖过来打印。
本质上: t o r c h . r a n d ( 6 ) torch.rand(6) torch.rand(6)只有一个维度的概念,不要把它理解为一个1行6列的矩阵。