【问题标题】:Explanation for slicing in PytorchPytorch中切片的解释
【发布时间】:2019-08-19 07:57:21
【问题描述】:

为什么每次输出都一样?

a = torch.tensor([0, 1, 2, 3, 4])
a[-2:] = torch.tensor([[[5, 6]]])
a

张量([0, 1, 2, 5, 6])

a = torch.tensor([0, 1, 2, 3, 4])
a[-2:] = torch.tensor([[5, 6]])
a

张量([0, 1, 2, 5, 6])

a = torch.tensor([0, 1, 2, 3, 4])
a[-2:] = torch.tensor([5, 6])
a

张量([0, 1, 2, 5, 6])

【问题讨论】:

    标签: pytorch slice


    【解决方案1】:

    Pytorch 在此处跟随 Numpy allows assignment 进行切片,只要形状兼容,这意味着两侧具有相同的形状或右侧可广播到切片的形状。从尾随维度开始,如果两个数组仅在其中一个为 1 的维度上有所不同,则它们是 broadcastable。所以在这种情况下

    a = torch.tensor([0, 1, 2, 3, 4])
    b = torch.tensor([[[5, 6]]])
    print(a[-2:].shape, b.shape)
    >> torch.Size([2]) torch.Size([1, 1, 2])
    

    Pytorch 将执行以下比较:

    1. a[-2:].shape[-1]b.shape[-1] 相等,所以最后一个维度是兼容的
    2. a[-2:].shape[-2] 不存在,但 b.shape[-2] 为 1,因此它们是兼容的
    3. a[-2:].shape[-3] 不存在,但 b.shape[-3] 为 1,因此它们是兼容的
    4. 所有维度都兼容,所以b可以广播到a

    最后,Pytorch 将在执行分配之前将b 转换为tensor([5, 6]),从而产生结果:

    a[-2:] = b
    print(a)
    >> tensor([0, 1, 2, 5, 6])
    

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2018-09-28
      • 2020-11-08
      • 1970-01-01
      • 2020-12-30
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多