PyTorch torch.ones Function
Pytorch torch Reference Manual
torch.onesis a function in PyTorch used to create an all-ones tensor. It creates a tensor of the specified shape with all elements initialized to 1.
This is often used in deep learning to initialize certain parameters, create masks, or serve as baseline values 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, e.g.,3、(3, 4)、(2, 3, 4)etc.dtype(torch.dtype, optional): Specifies the data type of the tensor, defaults totorch.float32。device(torch.device, optional): Specifies the device where the tensor is stored.requires_grad(bool, optional): Whether to compute gradients.pin_memory(bool, optional): Whether to use pinned memory.
Return Value:
torch.Tensor: Returns an all-ones tensor.
Usage Examples
Example 1: Create a 1D Ones Tensor
Example
import torch
# Create an all-ones tensor containing 5 elements
x = torch.ones(5)
print(x)
# Create an all-ones tensor containing 5 elements
x = torch.ones(5)
print(x)
The output result is:
tensor([1., 1., 1., 1., 1.])
Example 2: Create a 2D Ones Tensor
Example
import torch
# Create a 3x4 all-ones tensor (matrix)
x = torch.ones(3, 4)
print(x)
print(x.shape)
# Create a 3x4 all-ones tensor (matrix)
x = torch.ones(3, 4)
print(x)
print(x.shape)
The output result is:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
torch.Size([3, 4])
Example 3: Create a 3D Ones Tensor
Example
import torch
# Create a 2x3x4 all-ones tensor
x = torch.ones(2, 3, 4)
print(x.shape)
# Create a 2x3x4 all-ones tensor
x = torch.ones(2, 3, 4)
print(x.shape)
The output result is:
torch.Size([2, 3, 4])
Other Extensions