.as_tensor()
In PyTorch, the .as_tensor()
function converts various data types, including NumPy arrays, into PyTorch tensors. When possible, it avoids copying data by sharing memory with the original array. This means that if a NumPy array is modified, the corresponding PyTorch tensor will also reflect those changes. However, if the NumPy array is not in a compatible format, PyTorch may create a copy instead.
Syntax
The syntax for the .as_tensor()
function is as follows:
torch.as_tensor(data, dtype=None, device=None)
data
: The input data to be converted into a PyTorch tensor. It can be a NumPy array, PyTorch tensor, CuPy array, or Python list.dtype
: The data type of the output tensor. IfNone
, the data type is inferred from the input data.device
: The device on which the output tensor will be stored (e.g.,'cpu'
or'cuda'
). IfNone
:- If
data
is a CuPy array, the tensor remains on the same GPU. - Otherwise, the tensor is placed on the CPU by default.
- If
Example
In the following example, a NumPy array is converted into a PyTorch tensor using .as_tensor()
, allowing both to share memory when possible:
import torchimport numpy as np# Create a NumPy arrayarr = np.array([1, 2, 3])# Convert the NumPy array into a PyTorch tensortensor = torch.as_tensor(arr)print(tensor)
It produces an output as follows:
tensor([1, 2, 3])
In this example, a NumPy array arr
with values [1, 2, 3]
is first created and then converted into a PyTorch tensor using the .as_tensor()
function. The resulting tensor tensor
shares memory with the original NumPy array when possible.
Additional Notes
- The
.as_tensor()
function helps avoid unnecessary data copies when converting a NumPy array into a PyTorch tensor, which can save memory and improve performance, especially with large datasets. - The resulting PyTorch tensor shares memory with the original NumPy array when possible, meaning that modifying one affects the other.
- To create a separate copy of the data,
.tensor()
can be used, which always creates a new tensor with independent memory.
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
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - 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