tensorflow张量和numpy数组相互转换

知识补充:

官方文档(GItHub):TensorFlow 2.0: Functions, not Sessions.

tensorflow2.x的转换模块@tf.function

关于图执行(Graph )和立即执行(Eager)

numpy数组转换成张量:(tf.convert_to_tensor)

import numpy as np 
import tensorflow as tf

a = np.ones((1,2))
print(a, type(a))
a = tf.convert_to_tensor(a, dtype='float32')
print(a, type(a))

输出为:
[[1. 1.]] <class 'numpy.ndarray'>
tf.Tensor([[1. 1.]], shape=(1, 2), dtype=float32)  <class'tensorflow.python.framework.ops.EagerTensor'>

张量转换为数组: (Session.run 或者 eval)

import numpy as np 
import tensorflow as tf

tf.compat.v1.disable_eager_execution()

b = tf.constant([1,2,3])
b = tf.compat.v1.Session().run(b)
print(b, type(b))

b = tf.constant([1,2,3])
with tf.compat.v1.Session().as_default():
        b = b.eval()
print(b, type(b))

输出:
[1 2 3] <class 'numpy.ndarray'>
[1 2 3] <class 'numpy.ndarray'>

(tensorflow2.0以上版本需要tf.compat.v1作为接口)

eager_execution 是tensorflow的立即执行模式(不同于图执行模式),在2.x的tensorflow中默认打开,需要调用disable_eager_execution()去关闭(在1.x的版本中则是默认关闭)

如果不关闭该模式,则需要.numpy()来转换成数组,继续用eval()则会报错:

eval is not supported when eager execution is enabled

import numpy as np 
import tensorflow as tf

b = tf.constant([1,2,3])
with tf.compat.v1.Session().as_default():
        # b = b.eval()
        b= b.numpy()
print(b, type(b))

补充:实测可以直接调用numpy的asarray来转换

补充:

关于图执行(Graph )和立即执行(Eager)

tensorflow2.x的转换模块@tf.function

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值