I want to convert a NumPy array to a tensor. Which function should I use for it?

+2 votes

A Numpy array can be converted into a tensor using one of the following methods of the torch.

- tensor()
- from_numpy()
- as_tensor()

Here is an example:

>>> import numpy as np

>>> import torch

>>> a=np.array([1,2,3,4])

>>> a

array([1, 2, 3, 4])>>> f=torch.tensor(a)

>>> f

tensor([1, 2, 3, 4])>>> f=torch.from_numpy(a)

>>> f

tensor([1, 2, 3, 4])>>> f=torch.as_tensor(a)

>>> f

tensor([1, 2, 3, 4])