Home > Net >  RuntimeError: Sizes of arrays must match except in dimension 1
RuntimeError: Sizes of arrays must match except in dimension 1

Time:01-10

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?

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]? I want the result to be 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.

another solution that didn't work:

l = torch.cat(f[:, None, :], s[:, None, :])

the expected output should have shape [:, 2, 4]

CodePudding user response:

Stacking 2d arrays as in your example, to become 3d, would require you to impute some missing data. There is not enough info to create the 3d array if the dimensions of your input data don't match.

I see two options:

  1. concatenate along axis = 1 to get shape (5, 5)
a = data[0]
b = data[1]
combined = np.concatenate((a, b))  # shape (5, 5)
  1. add dummy rows to data[0] to be able to create a 3d result
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.

  • Related