Tensor.shape[0]的理解

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,..)Tensorshape[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列的矩阵。

  • 13
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值