tensor[None] ...

假设有一个 torch 的 tensor 类型的变量 T
T 的 shape 为shape,那么 T[None] 的shape 会变成 (1,shape)。
T[None] 会在 T 的基础上增加一个 dim。该 dim 的值为 1。

为什么要这样呢?

因为 PyTorch 需要 tensor 的形状 是 (B,C,H,W) 的
但是如果某个 tensor 是由一张 RGB 图像得到的,那么它的 shape 会是 (C,H,W),所以要增加第 0 维度,

举个例子

import torch

T = torch.randn((3,2))
print("T.shape: ",T.shape)
print("T:\n ",T)

print("\n\nT[None].shape: ",T[None].shape)
print("T[None]: \n",T[None])
print("Type(T[None]): ",type(T[None]))

输出如下:

T.shape:  torch.Size([3, 2])
T:
  tensor([[-0.2009,  0.5363],
        [ 1.0295, -0.0239],
        [ 0.9514, -1.2469]])


T[None].shape:  torch.Size([1, 3, 2])
T[None]: 
 tensor([[[-0.2009,  0.5363],
         [ 1.0295, -0.0239],
         [ 0.9514, -1.2469]]])
Type(T[None]):  <class 'torch.Tensor'>

可以看出,T 的shape: ( 3 , 2 ) → ( 1 , 3 , 2 ) (3,2) \rightarrow (1,3,2) (3,2)(1,3,2)

拓展一下

下面这条代码最后 有 [0],因为它的 shape是 (B,C,H,W) ,具体地即 (1,C,H,W) 那么 [0]之后便得到 形状为 (C,H,W) 的 tensor

=color_data = F.interpolate(
       color_data[None], self.crop_size, mode='bilinear', align_corners=True)[0]

T = torch.rand([2,6])
print(T)

T1 = T[...,None,None,1:]
print("T1 size",T1.shape)
print("T1",T1)
tensor([[0.5393, 0.4695, 0.2123, 0.4500, 0.1761, 0.7912],
        [0.5652, 0.5397, 0.0455, 0.1156, 0.1900, 0.0085]])
T1 size torch.Size([2, 1, 1, 5])
T1 tensor([[[[0.4695, 0.2123, 0.4500, 0.1761, 0.7912]]],


        [[[0.5397, 0.0455, 0.1156, 0.1900, 0.0085]]]])

注意,T1,的shape 首先看 1:,然后看...
... 是剩余维度吧

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

培之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值