PyTorch torch.ones function
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:
*size(int): The shape of the tensor, for example3,(3, 4),(2, 3, 4), etc.dtype(torch.dtype, optional): Specifies the tensor's data type, defaulting totorch.float32.device(torch.device, optional): Specifies the device on which the tensor is stored.requires_grad(bool, optional): Whether gradients need to be computed.pin_memory(bool, optional): Whether to use pinned memory.
Return Value:
torch.Tensor: Returns a tensor of all ones.
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
)
(
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
)
(
x
)
(
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
)
(
x.
shape
)
The output is:
torch.Size([2, 3, 4])