Reputation: 1598
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.
Upvotes: 23
Views: 16745
Reputation: 23
The voted answers are right. And I want to add this: I think from the pytorch documentation, we can't actually find the new method explanation. And I guess the reason if that this method is implemented by C, not by python.
Upvotes: 0
Reputation: 1612
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])
Upvotes: 11
Reputation: 5148
Here is a simple use-case and example using new()
, since without this the utility of this function is not very clear.
Suppose you want to add Gaussian noise to a tensor (or Variable) without knowing a priori what it's datatype is.
This will create a tensor of Gaussian noise, the same shape and data type as a Variable X
:
noise_like_grad = X.data.new(X.size()).normal_(0,0.01)
This example also illustrates the usage of new(size)
, so that we get a tensor of same type and same size as X
.
Upvotes: 6
Reputation: 37691
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.
Upvotes: 23
Reputation: 1598
I've found an answer. It is used to create a new tensor with the same type.
Upvotes: 2