一、tensorflow的numpy与tensor互转
1.数组(numpy)转tensor
利用tf.convert_to_tensor(numpy),将numpy转成tensor
>>> a = np.ones((3,3))
>>> a
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> t = tf.convert_to_tensor(a)
>>> t
<tf.Tensor 'Const_1:0' shape=(3, 3) dtype=float64>
2.tensor转数组(numpy)
利用tensor.eval(), 将tensor转为numpy
sess = tf.session()
>>> a_t = t.eval(session=sess)
>>> a_t
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
二、pytorch的numpy与tensor互转
1.numpy转tensor
直接利用torch.from_numpy(a)即可。
>>> b = np.arange(6).reshape((3,2))
>>> b
array([[0, 1],
[2, 3],
[4, 5]])
>>> t = torch.from_numpy(b)
>>> t
tensor([[0, 1],
[2, 3],
[4, 5]])
2.tensor转numpy
直接利用a.numpy()即可
>>> t
tensor([[0, 1],
[2, 3],
[4, 5]])
>>> b_t = t.numpy()
>>> b_t
array([[0, 1],
[2, 3],
[4, 5]])