PyTorch torch.from_numpy() Method

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.asarray()

torch.is_complex()

torch.Tensor.untyped_storage()

Leave a Comment