PyTorch torch.from_numpy() method is “used to create a Tensor from a numpy.ndarray.” The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa. The returned tensor is not resizable.
Syntax
torch.from_numpy(ndarray)
Parameters
ndarray: It is an Input Numpy array (numpy.ndarray).
The torch.from_numpy() method accepts ndarray with dtypes of numpy.float64, numpy.float32, numpy.float16, numpy.complex64, numpy.complex128, numpy.int64, numpy.int32, numpy.int16, numpy.int8, numpy.uint8, and numpy.bool.
Example
import numpy as np
import torch
# Creating a numpy array
numpy_array = np.array([1, 2, 3, 4, 5])
# Converting it to a PyTorch tensor
tensor_from_numpy = torch.from_numpy(numpy_array)
print(tensor_from_numpy)
Output
tensor([1, 2, 3, 4, 5])
The memory is shared between the tensor and the NumPy array. This is memory efficient but can sometimes lead to unintended consequences if you modify one and expect the other to remain unchanged.
Related posts
torch.Tensor.untyped_storage()

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.