import torch
x = torch.tensor(
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
]
)
x
x.shape
Tensor.resize_¶
Notice that Tensor.resize_
is in-place
and the non in-place version Tensor.resize
is deprecated.
xc = x.clone()
xc
xc is x
xc.resize_((1, 2, 5))
xc.shape
You can resize a Tensor to have more elements. The Tensor is padded on the right.
- A float Tensor is padded with the value 0.
- It seems that an int Tensor is padded with random integers.
Resize an int Tensor.
t = torch.tensor([1, 2, 3])
t
t.resize_(5)
Resize a float Tensor.
t = torch.tensor([1.0, 2.0, 3.0])
t
t.resize_(5)
Tensor.squeeze¶
x.squeeze(0)
x.squeeze(0).shape
y = x.unsqueeze(0)
y
y.shape
y.squeeze(0)
y.squeeze(0).shape
Tensor.unsqueeze¶
x.unsqueeze(0)
x.unsqueeze(0).shape
Tensor.view¶
x.view((1, 2, 5))
x.view((1, 2, 5)).shape
Tensor.view_as¶
View this tensor as the same size as other
.
self.view_as(other)
is equivalent to self.view(other.size()).
Tensor.expand¶
Returns a new view of the self tensor with singleton dimensions expanded to a larger size.
Tensor.expand
is used to replicate data in a tensor.
If x
is the tensor to be expanded.
The new shape must be (k, *x.shape)
,
where k
is a non-negative integer.
x
x.expand((3, 2, 5))
x.expand((1, 2, 5))
x.expand((1, 2, 5)).shape
x = torch.tensor([1, 2, 3])
x
x.repeat(2)
x.repeat(2, 4, 3)
Add a Dummy Dimension¶
If you need to add a dummy dimension at the beginning or the end,
it is the easiest to use the method Tensor.unsqueeze
since you only need to specify the position to add the dummy dimension
instead of specifying the full new dimension.
Otherwise,
I'd suggest you to use the method Tensor.view
as it can be used for both adding/removing a dummy dimension
(at the slight inconvenience of specifying the full new dimension).
x.expand((1, 2, 5))
x.view((1, 2, 5))
x.unsqueeze(0)
x.clone().resize_((1, 2, 5))
You can also use numpy-style slicing to add a dummy dimenson!!!
x[None, :, :]
Remove a Dummy Dimension¶
If you need to remove a dummy dimension from the beginning or the end,
it is the easiest to use the method Tensor.squeeze
since you only need to specify the position to remove the dummy dimension
instead of specifying the full new dimension.
Otherwise,
I'd suggest you to use the method Tensor.view
as it can be used for both adding/removing a dummy dimension
(at the slight inconvenience of specifying the full new dimension).
y = x.unsqueeze(0)
y
y.shape
y.view((2, 5))
y.squeeze(0)
y.clone().resize_((2, 5))