everyone, I have a small question.
What is the purpose of the method tensor.new(..)
in Pytorch, I didn't find anything in the documentation. It looks like it creates a new Tensor (like the name suggests), but why we don't just use torch.Tensor
constructors instead of using this new method that requires an existing tensor.
Thank you in advance.
As the documentation of tensor.new() says:
Constructs a new tensor of the same data type as self tensor.
Also note:
For CUDA tensors, this method will create new tensor on the same device as this tensor.
It seems that in the newer versions of PyTorch there are many of various new_*
methods that are intended to replace this "legacy" new
method.
So if you have some tensor t = torch.randn((3, 4))
then you can construct a new one with the same type and device using one of these methods, depending on your goals:
t = torch.randn((3, 4))
a = t.new_tensor([1, 2, 3]) # same type, device, new data
b = t.new_empty((3, 4)) # same type, device, non-initialized
c = t.new_zeros((2, 3)) # same type, device, filled with zeros
...
for x in (t, a, b, c):
print(x.type(), x.device, x.size())
# torch.FloatTensor cpu torch.Size([3, 4])
# torch.FloatTensor cpu torch.Size([3])
# torch.FloatTensor cpu torch.Size([3, 4])
# torch.FloatTensor cpu torch.Size([2, 3])
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