pytorch与tensorflow的numpy与tensor互转

一、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]])

参考链接

https://www.jianshu.com/p/939c71e0245a

https://blog.csdn.net/a1786742005/article/details/84994700

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值