【问题标题】:How to concatenate a list of tensors on a specific axis?如何连接特定轴上的张量列表?
【发布时间】:2021-09-09 17:47:30
【问题描述】:

我有一个张量列表 (my_list),所有张量都具有相同的形状。我想在通道轴上连接它们。 帮助代码

for i in my_list:
    print(i.shape) #[1, 3, 128, 128] => [batch, channel, width, height]

我想获得一个新的张量,即 new_tensor = [1, 3*len(my_list), width, height]

我不想使用torch.stack() 添加新维度。而且我无法弄清楚如何使用torch.cat() 来做到这一点?

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    给定一个示例 list,其中包含 10 个形状为 (1, 3, 128, 128) 的张量:

    >>> my_list = [torch.rand(1, 3, 128, 128) for _ in range(10)]
    

    您希望在axis=1 上连接张量,因为第二维是张量连接在一起的位置。您可以使用torch.cat

    >>> res = torch.cat(my_list, axis=1)
    >>> res.shape
    torch.Size([1, 30, 128, 128])
    

    这实际上相当于在my_list 中垂直堆叠张量,使用torch.vstack

    >>> res = torch.vstack(my_list)
    

    【讨论】:

      猜你喜欢
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2021-06-18
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多