我已经使用TensorFlow和Jupyter有一段时间了,但这是我第一次遇到这个问题。我有一个包含6层的NN模型,通过调用“classifier”函数来获取模型的实例
def classifier(input_repr,prob,reuse=None): e_l1=tf.layers.dense(inputs=input_repr,units=512,activation=tf.nn.leaky_relu) e_l1=tf.nn.dropout(e_l1,prob) e_l2=tf.layers.dense(inputs=e_l1,units=256,activation=tf.nn.leaky_relu) e_l2=tf.nn.dropout(e_l2,prob) e_l3=tf.layers.dense(inputs=e_l2,units=128,activation=tf.nn.leaky_relu) e_l3=tf.nn.dropout(e_l3,prob) e_l4=tf.layers.dense(inputs=e_l3,units=64,activation=tf.nn.leaky_relu) e_l4=tf.nn.dropout(e_l4,prob) e_l5=tf.layers.dense(inputs=e_l4,units=32,activation=tf.nn.leaky_relu) e_l5=tf.nn.dropout(e_l5,prob) d_l3=tf.layers.dense(inputs=e_l5,units=1,activation=tf.nn.leaky_relu) return d_l3
我还有一个函数来可视化模型摘要,如下所示
def model_summary(): model_vars = tf.trainable_variables() slim.model_analyzer.analyze_vars(model_vars, print_info=True)print(model_summary())
我通过以下方式获取模型实例,
model_output=classifier(input_repr,prob)
问题是,每次我调用这个函数,然后调用model_summary(),层数就会叠加到之前的模型上。例如,如果我第一次调用“classifier()”,model_Summary()显示5层,但当我再次调用时,它显示10层,依此类推。我总是在调用classifier()方法之前重新初始化,但问题一次又一次地发生。我不知道这是否是Jupyter的问题。我知道解决这个问题的唯一方法是完全重启内核,这会导致变量丢失。
回答:
不要忘记在创建模型之前重置默认图tf.reset_default_graph()
。问题在于笔记本是在单线程中运行的,每次你反复构建图时,TensorFlow都会在图上堆叠新节点。这就是为什么在Jupyter笔记本中原型设计时,构建新图时总是要重置默认图。