+4 votes
in Programming Languages by (60.2k points)
I want to convert a NumPy array to a tensor. Which function should I use for it?

1 Answer

+2 votes
by (355k points)
selected by
 
Best answer

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])


...