python - 在不使用会话的情况下打印 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.print
ortf.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
打印所有东西,但是,我更新了包TensorFlow
和numpy
包,现在面临着很多不兼容的问题。最糟糕的是,我不记得我使用的是哪个版本。
我遵循这篇文章 AttributeError: 'Tensor' object has no attribute 'numpy'中解释的每一步。它没有帮助我。
解决方案
以下代码给了我一个输出 -
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()
吗?
推荐阅读
- python - 生成从前端烧瓶发送的视频缩略图
- jenkins - sfdx force:source:deploy 未找到结果
- java - 如何调试 Maven 项目中的冲突依赖项
- java - 如何从剪贴板中获取复制的内容 - Selenium 无头模式
- javascript - Javascript Student - 通过索引返回数组# - 参数问题
- azure-sqldw - Azure Synapse Analytics 中的 STRING_SPLIT
- python - 在OpenCV python中测量点到掩码的距离
- python - ezdxf 和 Matplotlib 如何增加线条粗细
- bash - 将数组参数传递给 zsh 中的 bash 脚本
- mongodb - MongoDB updateOne 子数组 - $elemMatch 在 arrayFilter 中不起作用