PyTorch torch.ones() Method

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

  1. size (int…): It is a sequence of integers defining the shape of the output tensor.
  2. out: Output tensor.
  3. dtype: The desired data type of the tensor. The default is torch.float32.
  4. layout: Memory layout of the tensor. The default is a torch.strided.
  5. device: The desired device for the tensor. Default is the current default device.
  6. 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

Creating a 2x3x4 Tensor Filled with Ones of Int Type on CPU

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

torch.zeros_like()

torch.zeros()

Leave a Comment