PyTorch .tensor()
Anonymous contributor
Published Aug 23, 2024
Contribute to Docs
The .tensor() function in PyTorch creates a tensor from a given data input.
Syntax
torch.tensor(data, dtype=None, device=None, requires_grad=False)
data: This required parameter represents the input data for the tensor. The data must be array-like (e.g., list, tuple) or scalar.dtype: This optional parameter specifies the desired type for the returned tensor. If not provided, the data type is inferred from thedata.device: This optional parameter specifies the desired device of the returned tensor. Common values are'cpu'or'cuda'. If not specified, the tensor is created on the default device.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 .tensor() function:
import torcht1 = torch.tensor(3)print(t1, '\n')t2 = torch.tensor([[1.0, 3.0, 5.0], [2.0, 6.0, 0.0]])print(t2)
The code above generates the following output:
tensor(3)tensor([[1., 3., 5.],[2., 6., 0.]])
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
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
- Intermediate.3 hours