.from_numpy()
Published Feb 16, 2025
Contribute to Docs
The .from_numpy()
function in PyTorch creates a tensor from a NumPy array, sharing the underlying memory. Changes to the NumPy array will affect the tensor. However, only in-place operations on the tensor will affect the NumPy array, while operations that create new tensors will not.
Syntax
torch.from_numpy(ndarray)
ndarray
: A NumPy array to be converted into a PyTorch tensor. It must be a NumPy array with a supported dtype (e.g.,float32
,int64
).
Example
The following example uses the .from_numpy()
function to convert a NumPy array into a PyTorch tensor:
import numpy as npimport torch# Create a NumPy arraynp_array = np.array([1, 2, 3, 4])# Convert NumPy array to a PyTorch tensor (shared memory)tensor = torch.from_numpy(np_array)print(tensor)
The output is:
tensor([1, 2, 3, 4])
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
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 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