Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyTorch: new_ones vs ones

Tags:

In PyTorch what is the difference between new_ones() vs ones(). For example,

x2.new_ones(3,2, dtype=torch.double) 

vs

torch.ones(3,2, dtype=torch.double) 
like image 408
Anuj Gupta Avatar asked Oct 18 '18 02:10

Anuj Gupta


People also ask

What is Torch Ones_like?

ones_like(input, out=output) is equivalent to torch. ones(input. size(), out=output) . input (Tensor) – the size of input will determine size of the output tensor. dtype ( torch.

How do you compare two tensors in PyTorch?

To compare two tensors element-wise in PyTorch, we use the torch. eq() method. It compares the corresponding elements and returns "True" if the two elements are same, else it returns "False".


1 Answers

For the sake of this answer, I am assuming that your x2 is a previously defined torch.Tensor. If we then head over to the PyTorch documentation, we can read the following on new_ones():

Returns a Tensor of size size filled with 1. By default, the returned Tensor has the same torch.dtype and torch.device as this tensor.

Whereas ones()

Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument sizes.

So, essentially, new_ones allows you to quickly create a new torch.Tensor on the same device and data type as a previously existing tensor (with ones), whereas ones() serves the purpose of creating a torch.Tensor from scratch (filled with ones).

like image 141
dennlinger Avatar answered Sep 22 '22 12:09

dennlinger