How to Convert a Numpy Array to a PyTorch Tensor in Python



Python


In this article, we show how to convert a numpy array to a PyTorch tensor in Python.

So, in numpy, we can create arrays and PyTorch has a built-in function, torch.from_numpy(), which allows to convert numpy arrays into PyTorch tensors.

The converted array will have the exact same values and be of the same data type.

This function comes in handy if working with numpy arrays, which you then need to convert into PyTorch tensors, which can be a stronger module when working with things such as artificial intelligence.

The torch.from_numpy() function takes in a single parameter, which is the numpy array that is desired to be converted.

Below, we have the full code of converting a numpy array into a PyTorch tensor.



So the first thing we must do is import torch and numpy modules.

We then create a numpy array, array1, which has 4 elements of values, 1, 2, 3, and 4.

We use the type() function to see specifically that this is a numpy array.

We then get the array's dtype attribute to see that the elements of the array are of type int32.

We then create a variable, torch1, and use the torch.from_numpy() function to convert the numpy array to a PyTorch tensor.

We view the torch1 variable and see that it is now a tensor of the same int32 type.

We then use the type() function again and see that is a tensor of the Torch module.

The torch.from_numpy() function will always copy the same data type as was used in numpy.

So if you were to specifically create a numpy array and specify a data type, the same data type will be used in the converted PyTorch tensor.

Below we create a numpy array and specify the data type to be of same int16.



So you can see we specified now the numpy array to be of type int16.

We then use the torch.from_numpy() function to convert the numpy array to a PyTorch tensor and the data type of the tensor is of type int16.

And this is how to convert a numpy array to a PyTorch tensor in Python.


Related Resources



HTML Comment Box is loading comments...