TensorFlow关闭eager模式下如何提取tensor内部存储的整数值
关闭Eager模式下TensorFlow提取Tensor内部数值的方法
报错原因
触发
AttributeError: 'Tensor' object has no attribute 'numpy'的核心原因是调用tf.compat.v1.disable_eager_execution()后,TensorFlow进入静态图执行模式:此时定义的Tensor仅为计算图中的运算节点,不会实时计算并存储实际数值,因此不支持eager模式下的.numpy()直接取值方法。
解决方案(无需修改eager模式配置)
静态图模式下需要通过会话(Session)触发运算,才能拿到Tensor对应的实际数值,修改后代码如下:
import tensorflow as tf tf.compat.v1.disable_eager_execution() if __name__ == '__main__': test = tf.constant([1,4,5]) # 创建会话运行计算图获取对应数值 with tf.compat.v1.Session() as sess: np_array = sess.run(test) # 提取整数数值 integer_value = np_array[0] # 如需转Python原生int类型,可调用int()转换 print(integer_value) # 输出 1 print(type(integer_value)) # 输出 <class 'numpy.int32'>
补充说明
- 如需同时提取多个Tensor的数值,可直接将Tensor列表传入
sess.run():res1, res2 = sess.run([tensor1, tensor2]) - 拿到的numpy数组元素可直接参与数值运算,如需Python原生整数类型,调用
int()方法转换即可。
内容的提问来源于stack exchange,提问作者Fanto
相关产品推荐
相关产品推荐

