TensorFlow 2.6.0环境下如何查看Tensor张量的实际数值
TensorFlow 2.6 查看张量实际值的解决方案
你之前尝试的tf.Print、tf.Session相关调用均为TensorFlow 1.x的静态图专属API,TensorFlow 2.x版本默认开启Eager Execution执行模式,上述API已废弃不可用。你打印输出仅显示张量结构,说明当前代码运行在静态图上下文(如被@tf.function装饰、处于tf.keras编译后的执行流程中),未触发实际计算。
以下是不同场景下的稳定解决方案:
场景1:代码未进入静态图上下文(常规Eager执行模式)
直接调用张量的.numpy()方法即可获取其实际存储的数值:
predicted_ids=tf.random.categorical(predicted_logits, num_samples=1) predicted_ids=tf.squeeze(predicted_ids, axis=-1) print(predicted_ids.numpy())
场景2:代码运行在静态图上下文(被@tf.function装饰、自定义损失/层的执行过程中)
两种可选方案:
- 方案1:临时开启静态图函数的Eager执行模式,在调用目标函数前添加配置:
# 全局开启函数的Eager执行,调试完成后删除该行即可恢复静态图运行效率 tf.config.run_functions_eagerly(True)
配置后即可在静态图代码中直接使用.numpy()方法打印张量值。
- 方案2:使用TensorFlow 2.x专属的
tf.print()方法直接输出,无需修改执行模式:
@tf.function def your_infer_func(): predicted_ids=tf.random.categorical(predicted_logits, num_samples=1) predicted_ids=tf.squeeze(predicted_ids, axis=-1) # 直接输出张量实际值 tf.print(predicted_ids)
该方法也可直接用于tf.keras的自定义损失、自定义层、回调函数等静态图执行场景。
内容的提问来源于stack exchange,提问作者kiriloff
相关产品推荐
相关产品推荐

