torch.Tensor.expand#
- Tensor.expand(*sizes)→Tensor#
Returns a new view of the
selftensor with singleton dimensions expandedto a larger size.Passing -1 as the size for a dimension means not changing the size ofthat dimension.
Tensor can be also expanded to a larger number of dimensions, and thenew ones will be appended at the front. For the new dimensions, thesize cannot be set to -1.
Expanding a tensor does not allocate new memory, but only creates anew view on the existing tensor where a dimension of size one isexpanded to a larger size by setting the
strideto 0. Any dimensionof size 1 can be expanded to an arbitrary value without allocating newmemory.- Parameters
*sizes (torch.Size orint...) – the desired expanded size
Warning
More than one element of an expanded tensor may refer to a singlememory location. As a result, in-place operations (especially ones thatare vectorized) may result in incorrect behavior. If you need to writeto the tensors, please clone them first.
Example:
>>>x=torch.tensor([[1],[2],[3]])>>>x.size()torch.Size([3, 1])>>>x.expand(3,4)tensor([[ 1, 1, 1, 1], [ 2, 2, 2, 2], [ 3, 3, 3, 3]])>>>x.expand(-1,4)# -1 means not changing the size of that dimensiontensor([[ 1, 1, 1, 1], [ 2, 2, 2, 2], [ 3, 3, 3, 3]])