In this tutorial, we will introduce you how to convert a pytorch tensor to numpy. It is very easy to understand.
Convert a numpy to tensor
It is easy to create a tensor from a numpy ndarray.
For example:
import torch import numpy as np d = np.array([[ 0.0050, 0.8963, -0.7895, 0.1878, 0.9381], [ 2.3930, 1.4334, 1.0084, -0.3042, -1.0104], [ 0.7383, 1.0310, -0.4101, -0.4086, 0.2880], [ 0.0728, -0.6073, -0.0805, 0.3811, -0.0614], [-2.4547, 0.7017, -1.1140, -0.3677, 0.8146]]) x = torch.from_numpy(d)
Run this code, we will see:
tensor([[ 0.0050, 0.8963, -0.7895, 0.1878, 0.9381], [ 2.3930, 1.4334, 1.0084, -0.3042, -1.0104], [ 0.7383, 1.0310, -0.4101, -0.4086, 0.2880], [ 0.0728, -0.6073, -0.0805, 0.3811, -0.0614], [-2.4547, 0.7017, -1.1140, -0.3677, 0.8146]], dtype=torch.float64)
Here we will use torch.from_numpy() to convert a numpy to tensor.
Convert a tensor to numpy
Here are some methods to convert a pytorch tensor to numpy, for example:
import torch import numpy as np x = torch.randn([5,5], requires_grad= True) print(x) y = x.data.cpu().numpy() print(y) y = x.detach().numpy() print(y)
Here we can use x.data.cpu().numpy() or x.detach().numpy() to convert tensor x to numpy.
Run this code, we will see:
tensor([[-0.3366, -1.5594, 0.4729, -1.1344, -1.6247], [-1.5472, -0.2384, 0.6280, 1.7125, -1.1771], [-0.8164, -0.7187, -2.0486, -1.4570, 0.2325], [-1.2239, -1.1844, -0.5962, 0.2595, -0.3080], [ 0.6933, -0.2938, -0.6494, -0.5251, -0.1348]], requires_grad=True) [[-0.33663884 -1.5593643 0.47293866 -1.1344287 -1.6246802 ] [-1.5471828 -0.23844147 0.6279917 1.712499 -1.177059 ] [-0.8164169 -0.7187119 -2.0485656 -1.4570057 0.23254262] [-1.223918 -1.184376 -0.5962117 0.2594809 -0.3079657 ] [ 0.69329727 -0.2938432 -0.64942586 -0.5251326 -0.13480751]] [[-0.33663884 -1.5593643 0.47293866 -1.1344287 -1.6246802 ] [-1.5471828 -0.23844147 0.6279917 1.712499 -1.177059 ] [-0.8164169 -0.7187119 -2.0485656 -1.4570057 0.23254262] [-1.223918 -1.184376 -0.5962117 0.2594809 -0.3079657 ] [ 0.69329727 -0.2938432 -0.64942586 -0.5251326 -0.13480751]]