【问题标题】:How to stack matrices with different size如何堆叠不同大小的矩阵
【发布时间】:2021-05-02 13:34:12
【问题描述】:

我有一个大小为(63,32,1,600,600) 的矩阵列表,当我想将它与torch.stack(matrices).cpu().detach().numpy() 堆叠时,它会出现错误:

“堆栈期望每个张量大小相等,但在条目 0 处得到 [32, 1, 600, 600],在条目 62 处得到 [16, 1, 600, 600]”。尝试调整大小,但没有奏效。我感谢任何建议。

【问题讨论】:

  • 您是否尝试过设置矩阵堆叠的维度。
  • 是的,我尝试了 torch.stack(matrices, dim=0).cpu().detach().numpy() 并引发了同样的错误。
  • 您确定所有张量的大小都相同吗?您能否发送一个示例列表。
  • (63,32,1,600,600) 是您要从(*, 1, 600, 600) 张量列表中获取的张量的形状吗?
  • @Dwight,是的,我确信这是我的 cnn 网络的输出,包含 32 个批次和大小为 600x600 像素的图像。我不确定如何从我的主代码中生成一个示例。

标签: python matrix pytorch stack resize


【解决方案1】:

当我们的张量仅在第一维 as of PyTorch v1.7.0 上大小不同时,我们可以使用 torch.vstack() 将其沿轴 0 堆叠。使用 torch.stack() 在这里失败,因为它期望所有张量都相同形状。

这是与您的问题描述相匹配的可重现插图:

# sample tensors (as per your size)
In [65]: t1 = torch.randn([32, 1, 600, 600])
In [66]: t2 = torch.randn([16, 1, 600, 600])

# vertical stacking (i.e., stacking along axis 0)
In [67]: stacked = torch.vstack([t1, t2])

# check shape of output
In [68]: stacked.shape
Out[68]: torch.Size([48, 1, 600, 600])

我们得到48 (32 + 16) 作为结果中第一个维度的大小,因为我们沿该维度堆叠张量。


注意:

您还可以通过显式计算形状来初始化结果张量,例如stacked,并将此张量作为参数传递给torch.vstack()out= kwarg,如果您想将结果写入特定张量,例如实例更新现有张量(相同形状)的值。但是,这是可选的。

# calculate new shape of stacking
In [80]: newshape = (t1.shape[0] + t2.shape[0], *t1.shape[1:])

# allocate an empty tensor, filled with garbage values
In [81]: stacked = torch.empty(newshape)

# stack it along axis 0 and write the result to `stacked`
In [83]: torch.vstack([t1, t2], out=stacked)

# check shape/size
In [84]: stacked.shape
Out[84]: torch.Size([48, 1, 600, 600])

【讨论】:

  • 我想知道为什么会出现错误:“模块'torch'没有属性'vstack'”
  • @Aras 感谢您指出这一点。我更新了答案,提到 API 仅在 PyTorch 1.7.0 中添加。访问这些类型的 API 是使用最新版本的好处之一,但我同意这并不总是可能的 :)
【解决方案2】:

如果我理解正确,您正在尝试做的是将输出的小批量堆叠在一起成为一个批次。我敢打赌,你的最后一批是部分填充的(只有 16 个元素,而不是 32)。

我不会使用torch.stack(创建一个新轴),而是在批处理轴(axis=0)上简单地与torch.cat 连接。假设matricestorch.Tensors 的列表

torch.cat(matrices).cpu().detach().numpy()

默认情况下,torch.cataxis=0 连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2017-11-06
    • 2017-04-06
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多