一、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]])
本文介绍了如何在TensorFlow和PyTorch中实现numpy数组与tensor之间的相互转换。对于TensorFlow,使用tf.convert_to_tensor将numpy数组转为tensor,通过tensor.eval()转回numpy数组;对于PyTorch,则直接利用torch.from_numpy和tensor.numpy()进行转换。
9412

被折叠的 条评论
为什么被折叠?



