Let's call the function I'm looking for "magic_combine
", which can combine the continuous dimensions of tensor I give to it. For more specific, I want it to do the following thing:
a = torch.zeros(1, 2, 3, 4, 5, 6)
b = a.magic_combine(2, 5) # combine dimension 2, 3, 4
print(b.size()) # should be (1, 2, 60, 6)
I know that torch.view()
can do the similar thing. But I'm just wondering if there is any more elegant way to achieve the goal?
stack() method joins (concatenates) a sequence of tensors (two or more tensors) along a new dimension. It inserts new dimension and concatenates the tensors along that dimension. This method joins the tensors with the same dimensions and shape.
a = torch.zeros(1, 2, 3, 4, 5, 6)
b = a.view(*a.shape[:2], -1, *a.shape[5:])
Seems to me a bit simpler than the current accepted answer and doesn't go through a list
constructor (3 times).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With