【问题标题】:Cannot run Tensorflow code multiple times in Jupyter Notebook无法在 Jupyter Notebook 中多次运行 TensorFlow 代码
【发布时间】:2023-05-23 13:36:01
【问题描述】:

我在 Jupyter Notebook 中多次运行 Tensorflow (v1.1) 代码时遇到了困难。

例如,我执行这个简单的代码 sn-p 为 seq2seq 模型创建一个编码层:

# Construct encoder layer (LSTM)
encoder_cell = tf.contrib.rnn.LSTMCell(encoder_hidden_units)
encoder_outputs, encoder_final_state = tf.nn.dynamic_rnn(
    encoder_cell, encoder_inputs_embedded, 
    dtype=tf.float32, time_major=False
)

第一次完全没问题,我的编码器就创建好了。

但是,如果我重新运行它(无论我应用了哪些更改),我都会收到以下错误: Attempt to have a second RNNCell use the weights of a variable scope that already has weights

这很烦人,因为每次我想更改层时它都会强制我重新启动内核。

谁能解释一下为什么会发生这种情况以及如何解决这个问题?

谢谢!

【问题讨论】:

  • 另外,如果你们中的一些人有关于如何在 Tensorflow 1.1 中实现基本 seq2seq 模型的精彩教程,请不要犹豫分享!不幸的是,seq2seq tutorial 已过时且已弃用,取而代之的是 new seq2seq API
  • 在@Nicolas 回答之后,Python shell 中也会发生同样的情况。当我们尝试从图中重建现有节点时,Tensorflow 会引发错误。

标签: tensorflow ipython jupyter-notebook autoencoder


【解决方案1】:

您尝试构建完全相同的图表两次,因此 TensorFlow 会抱怨,因为默认图表中已经存在变量。

您可以做的是在第二次尝试调用该方法之前调用tf.reset_default_graph(),以确保您在需要时创建新图表。

以防万一,我还建议使用 启动 TensorFlow InteractiveSession 部分中描述的交互式会话:

import tensorflow as tf
sess = tf.InteractiveSession()

【讨论】:

  • 只比@pfm 稍微明确一点,我发现以下工作: import tensorflow as tf; tf.reset_default_graph();
最近更新 更多