PyTorch NumPy to tensor: Convert A NumPy Array To A PyTorch Tensor
PyTorch NumPy to tensor - Convert a NumPy Array into a PyTorch Tensor so that it retains the specific data type
< > Code:
You must be a Member to view code
Access all courses and lessons, gain confidence and expertise, and learn how things work and how to use them.
or Log In
We import NumPy as np.
import numpy as np
And we import PyTorch
Then we print the PyTorch version that we are using.
We are using 0.2.0_4.
Next, I paste in a NumPy array.
numpy_ex_array = np.array([[[1,2,3,4], [2,3,4,5], [3,4,5,6]], [[4,5,6,7], [5,6,7,8], [6,7,8,9]]], dtype=np.float32)
What we’re going to do is we’re going to define a variable numpy_ex_array and set it equal to a NumPy or np.array and we're going to give it the NumPy data type of 32 float.
So here, we can see the dtype=np.float32.
We can look at the shape which is a 2x3x4 multi-dimensional array.
We can print this multidimensional array and see that it is two arrays with three rows and four columns each.
What we want to do is use PyTorch from NumPy functionality to import this multi-dimensional array and make it a PyTorch tensor.
To do that, we're going to define a variable torch_ex_float_tensor and use the PyTorch from NumPy functionality and pass in our variable numpy_ex_array.
torch_ex_float_tensor = torch.from_numpy(numpy_ex_array)
Then we can print our converted tensor and see that it is a PyTorch FloatTensor of size 2x3x4 which matches the NumPy multi-dimensional array shape, and we see that we have the exact same numbers.
The first row of the first array in NumPy was 1, 2, 3, 4.
Here, the first row of this PyTorch tensor, we see that it is 1, 2, 3, 4.
Again, it is a FloatTensor which was the exact NumPy data type that we passed in float 32.
PyTorch by default uses a float 32 for the FloatTensor.