【问题标题】:Printing a TensorFlow object without using session在不使用会话的情况下打印 TensorFlow 对象
【发布时间】:2021-11-19 02:03:27
【问题描述】:

我在尝试打印 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.printtf.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'。它没有帮助我。

【问题讨论】:

  • 不要在 Tensorflow 模型/训练脚本中使用 NumPy 函数
  • 感谢您的评论。有没有什么具体的原因?

标签: python numpy tensorflow tensorflow2.0


【解决方案1】:

下面的代码给了我一个输出 -

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()了吗?

【讨论】:

  • 谢谢!是的,它已打开,但我重新启动了内核,现在甚至 tf.print 工作正常。
  • 但是,我打算做的仍然没有工作。当我打电话给 tf.compat.v1.print(model.optimizer.learning_rate) 时,它会打印出keras.optimizer_v2.learning_rate_schedule.ExponentialDecay object at 0x0000021BDCC520D0>
  • 对不起,我错过了那部分,你能提供你是如何创建模型的吗?可能是完整的代码块,直到你遇到错误。
  • 别担心!这是我找到的解决方案:lr = model.optimizer._decayed_lr(tf.float32), print(lr)
猜你喜欢
  • 2011-04-05
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多