无法在Jupyter Notebook中多次运行Tensorflow代码

Blo*_*ost 2 ipython autoencoder tensorflow jupyter-notebook

我在Jupyter Notebook中多次运行Tensorflow(v1.1)代码.

例如,我执行这个简单的代码片段,为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
)
Run Code Online (Sandbox Code Playgroud)

第一次完全没问题,我的编码器已经创建了.

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

这非常烦人,因为它每次我想要更改图层时都会强制我重新启动内核.

有人可以解释为什么会发生这种情况以及如何解决这个问题?

谢谢!

pfm*_*pfm 6

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

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

为以防万一,我也建议使用所描述的交互式会话这里开始TensorFlow InteractiveSession部分:

import tensorflow as tf
sess = tf.InteractiveSession()
Run Code Online (Sandbox Code Playgroud)