PyTorch torch.ones() method “returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.”
torch.ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
- size (int…): It is a sequence of integers defining the shape of the output tensor.
- out: Output tensor.
- dtype: The desired data type of the tensor. The default is torch.float32.
- layout: Memory layout of the tensor. The default is a torch.strided.
- device: The desired device for the tensor. Default is the current default device.
- requires_grad: If set to True, the tensor will be created with gradient tracking enabled. The default is False.
Example 1: Creating a 2×3 Tensor Filled with Ones
import torch tensor1 = torch.ones(2, 3) print(tensor1)
tensor([[1., 1., 1.], [1., 1., 1.]])
Example 2: Creating a 2x3x4 Tensor Filled with Ones of Int Type on CPU
import torch tensor2 = torch.ones(2, 3, 4, dtype=torch.int32, device='cpu') print(tensor2)
Example 3: Creating a Tensor with Gradient Tracking Enabled
import torch tensor3 = torch.ones(2, 2, requires_grad=True) print(tensor3)
tensor([[1., 1.], [1., 1.]], requires_grad=True)