首页 > 解决方案 > 在不使用会话的情况下打印 TensorFlow 对象

问题描述

尝试打印 TensorFlow 对象时收到不同的错误。

import numpy as np
import tensorflow as tf

TensorFlow 和 numpy 的版本分别是 2.6 和 1.19.5。

print("np version:", np.__version__)
print("tf version:" ,tf.version.VERSION)
print("eager is on? ", tf.executing_eagerly())

#np version: 1.19.5
#tf version: 2.6.0
#eager is on?  True

现在,让我创建一个小数组并将其变成一个tf对象。

arr= [0,1.2,-0.8]
arr = tf.constant(arr, dtype = tf.float32)

当我使用tf.printortf.compat.v1.print(arr)时,什么也没有发生。当我打电话时numpy,我确实收到了一个错误。

tf.compat.v1.print(arr.numpy())

AttributeError: 'Tensor' object has no attribute 'numpy'

到目前为止唯一有效的是;

with tf.compat.v1.Session() as sess:  print(arr.eval()) 

#[ 0.   1.2 -0.8]

但是,我想使用,numpy因为我的目标是在训练阶段打印网络的某些功能。例如,如果我想打印学习率,我调用 with tf.compat.v1.Session() as sess: print(model.optimizer.learning_rate.eval()) . 然而,它返回了另一个错误。

 'ExponentialDecay' object has no attribute 'eval'

我以前可以用来numpy打印所有东西,但是,我更新了包TensorFlownumpy包,现在面临着很多不兼容的问题。最糟糕的是,我不记得我使用的是哪个版本。

我遵循这篇文章 AttributeError: 'Tensor' object has no attribute 'numpy'中解释的每一步。它没有帮助我。

标签: pythonnumpytensorflowtensorflow2.0

解决方案


以下代码给了我一个输出 -

import numpy as np
import tensorflow as tf

print("np version:", np.__version__)
print("tf version:" ,tf.version.VERSION)
print("eager is on? ", tf.executing_eagerly())
tf.enable_eager_execution()

arr= [0,1.2,-0.8]
arr = tf.constant(arr, dtype = tf.float32)

tf.compat.v1.print(arr.numpy())

输出:array([ 0. , 1.2, -0.8], dtype=float32)

你加了tf.enable_eager_execution()吗?


推荐阅读