Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.ones function

PyTorch torch.ones function


PyTorch torch reference manual PyTorch torch reference manual

torch.ones is a function in PyTorch used to create a tensor of all ones. It creates a tensor of a specified shape with all elements initialized to 1.

In deep learning, this is commonly used to initialize certain parameters, create masks, or serve as a baseline value for mathematical operations.

Function definition

torch.ones(*size, dtype=None, device=None, requires_grad=False, pin_memory=False)

Parameters:

Return Value:


Usage examples

Example 1: Create a 1D tensor of ones

Example

import

torch

Create a tensor of ones with 5 elements

x

=

torch.

ones

(

5

)

print

(

x

)

The output is:

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

Example 2: Create a 2D tensor of ones

Example

import

torch

Create a 3x4 tensor of ones (matrix)

x

=

torch.

ones

(

3

,

4

)

print

(

x

)

print

(

x.

shape

)

The output is:

tensor([[1., 1., 1., 1.],

        [1., 1., 1., 1.],

        [1., 1., 1., 1.]])

torch.Size([3, 4])

Example 3: Create a 3D tensor of ones

Example

import

torch

Create a 2x3x4 tensor of ones

x

=

torch.

ones

(

2

,

3

,

4

)

print

(

x.

shape

)

The output is:

torch.Size([2, 3, 4])


PyTorch torch reference manual PyTorch torch reference manual