Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch beginner : tensor.new method

Tags:

pytorch

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.

like image 645
abcdaire Avatar asked Mar 13 '18 18:03

abcdaire


2 Answers

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.

like image 83
Wasi Ahmad Avatar answered Sep 22 '22 02:09

Wasi Ahmad


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])
like image 36
devforfu Avatar answered Sep 22 '22 02:09

devforfu