升级了tensorflow到1.15,发现一个用tf.kerasTensorBoard的时候就会报错的问题.

问题描述

错误信息如下:

TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors
leak out of the function building context by including a
tf.init_scope in your function building code.
For example, the following function will fail:
@tf.function
def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
added = my_constant * 2
The graph tensor has name: create_file_writer/SummaryWriter:0

问题解决

这个问题主要还是因为tensorflow要兼容两个版本的问题,也有我用vscode开发的原因.

现在使用的tensorflow.keras的时候最好还是用如下的方式:

TensorBoard = tf.keras.callbacks.TensorBoard

我用的是如下:

from tensorflow.python.keras.callbacks import TensorBoard

问题就在这里了,现在tensorflow 1.15默认的TensorBoard是使用tf 2.0的写法的,如果用第一个方式调用是没问题的.但因为tf.keras.callbacks.TensorBoard是从from tensorflow.python.keras.callbacks_v1导入的,所以我的写法调用的是对应tf 2.0的代码,导致错误.

所以我的写法要改成:

from tensorflow.python.keras.callbacks_v1 import TensorBoard