PyTorch torch.ones_like() Method

PyTorch torch.ones_like() method is “used to create a tensor filled with ones that have the same properties (size, dtype, layout, device, etc.) as the given input tensor.” It’s similar to the torch.zeros_like() function, but the resulting tensor is filled with 1 instead of 0.

Syntax

torch.ones_like(input, *, dtype=None, layout=None, device=None, 
                requires_grad=False, memory_format=torch.preserve_format)

Parameters

  1. input: The input tensor whose properties (size, dtype, etc.) will be used to create the output tensor.
  2. dtype: Overrides the data type of the result tensor. The default is None.
  3. layout: Overrides the layout of the result tensor. The default is None.
  4. device: Overrides the device of the result tensor. The default is None.
  5. requires_grad: If set to True, the tensor will be created with gradient tracking enabled. The default is False.
  6. memory_format: The desired memory format of the returned Tensor. Default: torch.preserve_format.

Example 1: Creating a Tensor of Ones with the Same Properties as Another Tensor

import torch

x = torch.tensor([[1, 2, 3], [4, 5, 6]])

tensor1 = torch.ones_like(x)

print(tensor1)

Output

tensor([[1, 1, 1],
        [1, 1, 1]])

Example 2: Creating a Tensor of Ones with the Same Shape but Different Dtype

import torch

x = torch.tensor([1.0, 2.0, 3.0])

tensor2 = torch.ones_like(x, dtype=torch.int32)

print(tensor2)

Output

tensor([1, 1, 1], dtype=torch.int32)

Example 3: Creating a Tensor of Ones with Gradient Tracking Enabled

import torch

x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)

tensor3 = torch.ones_like(x, requires_grad=True)

print(tensor3)

Output

tensor([1., 1., 1.], requires_grad=True)

That’s it!

Related posts

torch.ones()

torch.zeros()

torch.zeros_like()

Leave a Comment