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)
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 with1
. By default, the returned Tensor has the sametorch.dtype
andtorch.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).
new_ones()
can be used on an existing tensor, like x = torch.tensor(); x.new_ones([2,3])
. This allows you to move your tensor x
freely across devices or compute the dimensions, before actually initializing it. ones()
, on the other hand, directly creates a new tensor: x = torch.ones([2,3])
.
Jan 30, 2021 at 12:17
new_ones()
# defining the tensor along with device to run on. (Assuming CUDA hardware is available)
x = torch.rand(5, 3, device="cuda")
new_ones()
works with existing tensor. y
will inherit the datatype
from x
and it will run on same device
as defined in x
y = x.new_ones(2, 2)
print(y)
Output:
tensor([[1., 1.],
[1., 1.]], device='cuda:0')
ones()
# defining tensor. By default it will run on CPU.
x = torch.ones(5, 3)
print(x)
Output:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
ones()
is used to define tensor with 1.
(as shown in example) of given size
and is not dependent on the existing tensor, whereas new_ones()
works with existing tensor which inherits properties like datatype
and device
from existing tensor and define the tensor
with given size
.
x2
in this instance?