【问题标题】:Number of layers in the NN model keeps increasing every time I call a new instance of the model每次调用模型的新实例时,NN 模型中的层数都会不断增加
【发布时间】:2019-06-10 08:00:13
【问题描述】:

我现在使用 tensorflow 和 jupyter 工作了一段时间,但这是我第一次遇到这个问题。我有一个 6 层的 NN 模型,我通过调用函数“分类器”获得了这个模型的一个实例

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 层,依此类推。我总是在调用分类器()方法之前再次初始化,但它只是一次又一次地发生。我不知道这是否是 jupyter 的问题。我知道解决这个问题的唯一方法是完全重启内核,这会导致变量丢失。

【问题讨论】:

  • 您应该制作一个可重现的示例来显示问题并将其包含在您的问题中。

标签: tensorflow machine-learning jupyter-notebook


【解决方案1】:

在创建模型之前,不要忘记重置默认图形 tf.reset_default_graph()。问题是笔记本在单线程中运行,每当您一遍又一遍地构建图表时,Tensorflow 都会在图表上堆叠新节点。这就是为什么在 Jupyter notebook 中进行原型设计时,总是在开始构建新图时重置默认图。

【讨论】:

  • 谢谢,戈尔扬。它解决了这个问题,尽管我想提一下,必须小心放置 tf.reset_default_graph() 的位置。必须放在模型初始化之前。
【解决方案2】:

每次调用函数classifier 时,您都会创建额外的层,当您创建model 并编译它时,仅使用model 对象到model.fitmodel.predict

【讨论】:

  • 但是在训练时,它不会训练原始模型,而是训练堆叠模型。不管怎样,正如@gorjan 所描述的,问题已经解决了!
猜你喜欢
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 2021-08-28
相关资源
最近更新 更多