Reputation: 41
I have a tensor with the shape torch.Size([39, 1, 20, 256, 256])
how do I duplicate the channel to make the shape torch.Size([39, 3, 20, 256, 256])
.
Upvotes: 4
Views: 4732
Reputation: 11450
I am fairly certain that this is already a duplicate question, but I could not find a fitting answer myself, which is why I am going ahead and answer this by referring to both the PyTorch documentation and PyTorch forum
Essentially, torch.Tensor.expand()
is the function that you are looking for, and can be used as follows:
x = torch.rand([39, 1, 20, 256, 256])
y = x.expand(39, 3, 20, 256, 256)
Note that this works only on singleton dimensions, which is the case in your example, but may not work for arbitrary dimensions prior to expansion. Also, this is basically just providing a different memory view, which means that, according to the documentation, you have to keep the following in mind:
More than one element of an expanded tensor may refer to a single memory location. As a result, in-place operations (especially ones that are vectorized) may result in incorrect behavior. If you need to write to the tensors, please clone them first.
For a newly allocated memory version, see torch.Tensor.repeat
, which is outlined in this (slightly related) answer. The syntax works otherwise exactly the same as expand()
.
Upvotes: 8