当我们使用pytorch
时候,我们常常需要将Variable
转换为numpy
或Tensor
转换为numpy
;比如我们使用torch.Tensor
和torch.FloatTensor
的时候,我们
一、Tensor
与numpy
之间的相互转化
1、Tensor
张量转化为numpy
a = torch.FloatTensor(2,3)
print a.numpy();
2、将numpy
转换为Tensor
张量
a = np.ones(5)
torch.from_numpy(a)
二、Variable
与numpy
之间的相互转化
1、Variable
张量转化为numpy
其实这里的转换和Tensor
与numpy
之间的相互转化差不多,只是我们的需要先提取出来我们Variable
中的数据即可,我们可以使用variable.data
来将Variable
转为Tensor
import torch
from torch.autograd import Variable
a = Variable(torch.FloatTensor(2,3))
print a.data.numpy()
2、将numpy
转换为Variable
其实这个不需要过多的介绍,这个只是把numpy
转化为torch
并且再将torch
转化为Variable
import torch
import numpy as np
from torch.autograd import Variable
a = np.ones(5)
print Variable(torch.from_numpy(a))
实例
# input numpy array
In [91]: arr = np.arange(10, dtype=float32).reshape(5, 2)
# input tensors in two different ways
In [92]: t1, t2 = torch.Tensor(arr), torch.from_numpy(arr)
# their types
In [93]: type(arr), type(t1), type(t2)
Out[93]: (numpy.ndarray, torch.FloatTensor, torch.FloatTensor)
# ndarray
In [94]: arr
Out[94]:
array([[ 0., 1.],
[ 2., 3.],
[ 4., 5.],
[ 6., 7.],
[ 8., 9.]], dtype=float32)
我知道PyTorch
张量器共享 NumPy ndarrays
的内存缓冲区。因此,改变一个将反映在另一个。所以,在这里我正在切片并更新Tensor
中的一些值t2
In [98]: t2[:, 1] = 23.0
正如预期的那样,它已经更新t2,arr
因为它们共享相同的内存缓冲区。
In [99]: t2
Out[99]:
0 23
2 23
4 23
6 23
8 23
[torch.FloatTensor of size 5x2]
In [101]: arr
Out[101]:
array([[ 0., 23.],
[ 2., 23.],
[ 4., 23.],
[ 6., 23.],
[ 8., 23.]], dtype=float32)
但是,t1
也在更新。请记住,t1
使用torch.Tensor()while t2
构建使用torch.from_numpy()
In [100]: t1
Out[100]:
0 23
2 23
4 23
6 23
8 23
[torch.FloatTensor of size 5x2]