Differences between .ones_like() and .new_ones()

Hi! I was wondering what’s the differences between two tensor operations, namely x.ones_like() and x.new_ones()? Looks like they are all intended for creating tensors filled with ones and inheriting from the properties of the calling tensor x?

Thank you!

.ones_like() takes tensor as an input argument

input = torch.empty(2, 3)

new_ones is a member function of the tensor object

>>> tensor = torch.tensor((), dtype=torch.int32)
>>> tensor.new_ones((2, 3))
tensor([[ 1,  1,  1],
        [ 1,  1,  1]], dtype=torch.int32)
1 Like

The obvious difference is that you pass a shape into t.new_ones but not into torch.ones_like.

If I remember correctly, the torch.ones_like is an equivalent of the numpy API and t.new_ones is a “torch-legacy-idiomatic” replacement of a long-deprecated t.new method (which incidentally still seems to exist e.g. here pytorch/torch/nn/init.py at b199e3c8427a9648b9a76830ed9898ab4603288c · pytorch/pytorch · GitHub ) which is of similar nature as the deprecated Tensor(...) and FloatTensor(...) constructors.

Of course, part of the attraction of t.new_ones is that in contrast to C++ with t.options(), you have the “tensor properties” spread over several keyword arguments in Python (dtype, device, memory layout, …), but I tend to prefer torch.ones and torch.ones_like over the t.new_ones.

Best regards


1 Like