[英]RuntimeError: Sizes of arrays must match except in dimension 1
I have a list of different shapes array that I wish to stack.我有一个我希望堆叠的不同形状数组的列表。 Of course, np.stack doesn't work here because of the different shapes so is there a way to handle this using np.stack on dim=1?
当然,由于形状不同,np.stack 在这里不起作用,所以有没有办法在 dim=1 上使用 np.stack 来处理这个问题?
is it possible to stack these tensors with different shapes along the second dimension so I would have the result array with shape [ -, 2, 5]?是否可以沿第二维堆叠这些具有不同形状的张量,以便我得到形状为 [-, 2, 5] 的结果数组? I want the result to be 3d.
我希望结果为 3d。
data = [np.random.randn([2, 5]), np.random.randn([3, 5])]
stacked = np.stack(data, dim=1)
I tried another solution我尝试了另一种解决方案
f, s = data[0].shape, data[1].shape
stacked = np.concatenate((f.unsqueeze(dim=1), s.unsqueeze(dim=1)), dim=1)
where I unsqueeze the dimension but I also get this error: RuntimeError: Sizes of arrays must match except in dimension 1. Expected size 2 but got size 3 for array number 1 in the list.
在我取消压缩维度的地方,但我也收到此错误:
RuntimeError: Sizes of arrays must match except in dimension 1. Expected size 2 but got size 3 for array number 1 in the list.
another solution that didn't work:另一个无效的解决方案:
l = torch.cat(f[:, None, :], s[:, None, :])
the expected output should have shape [:, 2, 4]
预期的 output 应具有形状
[:, 2, 4]
Stacking 2d arrays as in your example, to become 3d, would require you to impute some missing data.在您的示例中堆叠 2d arrays 成为 3d,需要您估算一些缺失的数据。 There is not enough info to create the 3d array if the dimensions of your input data don't match.
如果输入数据的维度不匹配,则没有足够的信息来创建 3d 数组。
I see two options:我看到两个选项:
axis = 1
to get shape
(5, 5)
axis = 1
连接以获得shape
(5, 5)
a = data[0]
b = data[1]
combined = np.concatenate((a, b)) # shape (5, 5)
data[0]
to be able to create a 3d resultdata[0]
以能够创建 3d 结果a = data[0]
b = data[1]
a = np.concatenate((a, np.zeros((b.shape[0] - a.shape[0], a.shape[1]))))
combined = np.stack((a, b)) # shape (2, 3, 5)
Another option could be to delete rows from data[1]
to do something similar as option 2), but deleting data is in general not recommended.另一种选择是从
data[1]
中删除行以执行与选项 2) 类似的操作,但通常不建议删除数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.