.ones()
Anonymous contributor
Published Aug 13, 2024
Contribute to Docs
The .ones()
function in PyTorch creates a tensor of a specified shape, where each element is initialized to the scalar value 1. It is used in machine learning and deep learning for tasks such as preparing data, creating masks, or starting with default values for neural network weights. Knowing how to use .ones()
is valuable for building models and handling data efficiently.
Syntax
torch.ones(size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
size
: This required parameter specifies the tensor shape.out
: This optional parameter is the output tensor. The default value isNone
.dtype
: This optional parameter denotes the desired type for the returned tensor. The default value isNone
.layout
: This optional parameter designates the layout desired for the returned tensor. The default value istorch.strided
.device
: This optional parameter specifies the desired device of the returned tensor (e.g.,torch.device('cpu')
ortorch.device('cuda')
). The default value isNone
.requires_grad
: This optional parameter determines if autograd should record the operations on the returned tensor. The default value isFalse
.
Example
The following example shows how to use the .ones()
function:
import torchtensor_simple = torch.ones(3)print(tensor_simple)tensor_sizes = torch.ones((2,5))print(tensor_sizes)
The code above generates the following output:
tensor([1., 1., 1.])tensor([[1., 1., 1., 1., 1.],[1., 1., 1., 1., 1.]])
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Free course
Intro to PyTorch and Neural Networks
Learn how to use PyTorch to build, train, and test artificial neural networks in this course.Intermediate3 hours - Course
PyTorch for Classification
Build AI classification models with PyTorch using binary and multi-label techniques.With CertificateBeginner Friendly3 hours