tensor转换 pytorch tensorflow
生活随笔
收集整理的這篇文章主要介紹了
tensor转换 pytorch tensorflow
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、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]])
總結
以上是生活随笔為你收集整理的tensor转换 pytorch tensorflow的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一维卷积网络多分类
- 下一篇: API pytorch tensor