PyTorch torch.ones() method “returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.”
Syntax
torch.ones(*size, *, out=None, dtype=None, layout=torch.strided,
device=None, requires_grad=False)
Parameters
- 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)
Output
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)
Output
Example 3: Creating a Tensor with Gradient Tracking Enabled
import torch
tensor3 = torch.ones(2, 2, requires_grad=True)
print(tensor3)
Output
tensor([[1., 1.],
[1., 1.]], requires_grad=True)
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.