When training a neural network with pytorch, we often need to convert array variable type and tensor type pytorch in numpy today to introduce a method for mutual conversion between them.
A, numpy to tensor
First, we want to introduce the necessary packages:
import numpy as np import torch
Then create a numpy array of type:
x = np.ones(5) print(type(x))
Here creates an array of one-dimensional, five are 1, we print about this type of x is shown below:
<class 'numpy.ndarray'>
This will now be described numpy x is an array type, and then we use the following code to convert x tensor Type:
x = torch.tensor(x) print(type(x))
The printed result is:
<class 'torch.Tensor'>
That we successfully converted!
Two, tensor to numpy
Directly on the code:
x = x.detach().numpy() print(type(x))
Where x is just that we converted into x, print the results tensor are as follows:
<class 'numpy.ndarray'>
We have thus succeeded in converting him back ~