【问题标题】:Expand the tensor by several dimensions将张量扩展几个维度
【发布时间】:2022-07-08 09:35:58
【问题描述】:

在 PyTorch 中,给定一个 size=[3] 的张量,如何将其扩展几个维度到 size=[3,2,5,5] 使得添加的维度具有原始张量的对应值。例如,使 size=[3] vector=[1,2,3] 使得大小为 [2,5,5] 的第一个张量具有值 1,第二个具有所有值 2,第三个具有所有值3.

另外,如何将大小为[3,2]的向量扩展为[3,2,5,5]?

我能想到的一种方法是先用 one-Like 然后用 einsum 创建一个大小相同的向量,但我认为应该有一种更简单的方法。

【问题讨论】:

    标签: pytorch tensor


    【解决方案1】:

    您可以先解压适当数量的单例维度,然后使用torch.Tensor.expand 扩展为目标形状的视图:

    >>> x = torch.rand(3)
    >>> target = [3,2,5,5]
    
    >>> x[:, None, None, None].expand(target)
    

    一个很好的解决方法是使用torch.Tensor.reshapetorch.Tensor.view 来执行多次解压:

    >>> x.view(-1, 1, 1, 1).expand(target)
    

    这允许使用更通用的方法来处理任意目标形状:

    >>> x.view(len(x), *(1,)*(len(target)-1)).expand(target)
    

    对于更一般的实现,x 可以是多维的:

    >>> x = torch.rand(3, 2)
    
    # just to make sure the target shape is valid w.r.t to x
    >>> assert list(x.shape) == list(target[:x.ndim])
    
    >>> x.view(*x.shape, *(1,)*(len(target)-x.ndim)).expand(target)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-10
      • 2018-08-23
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2017-06-02
      相关资源
      最近更新 更多