Tensorflow error: Variable gru_def/rnn/gru_cell/gates/kernel does not exist, or was not created with tf.get_variable()

Tensorflow error: Variable gru_def/rnn/gru_cell/gates/kernel does not exist, or was not created with tf.get_variable()

这是我第一次使用 python 和 tensorflow 进行编程。我想使用动态 RNN 来构建句子嵌入。 这是我用 jupyter 编写的代码的一部分。

graph = tf.Graph()
x_data = tf.placeholder(tf.int32, [None,None])
sequence_lengths = tf.placeholder(tf.int32, shape=[None])
embedding_mat = tf.Variable(tf.random_uniform([vocab_size,embedding_size],  0.0, 1.0),dtype=tf.float32)
embedding_output = tf.nn.embedding_lookup(embedding_mat,x_data)

with tf.variable_scope('cell_def'):
    cell =tf.contrib.rnn.GRUCell(num_units = rnn_size)
    hidden_state_in =cell.zero_state(batch_size,tf.float32) 
with tf.variable_scope('gru_def'):
    output, state = tf.nn.dynamic_rnn(cell,embedding_output,initial_state=hidden_state_in,dtype=tf.float32,sequence_length=sequence_lengths)

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer())
    feed_dict = {x_data:embedding_output}
    sess.run(output,feed_dict=feed_dict)
    #tf.get_variable_scope().reuse_variables()    
sess.close()    

当我 运行 我的代码时,我得到这个错误:

Variable gru_def/rnn/gru_cell/gates/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:

我尝试通过调用 tf.get_variable_scope().reuse_variables() 将重用标志设置为 True 来解决此问题,但错误仍然存​​在。

然后,我向 GRUCell 添加了一个 reuse 参数,但是我有这个错误:

ValueError: Variable gru_def/rnn/gru_cell/gates/kernel does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=tf.AUTO_REUSE in VarScope?

cell = tf.contrib.rnn.GRUCell(num_units = rnn_size,reuse=True)

你能帮帮我吗

在张量流 1.3+ 中:

cell = tf.contrib.rnn.GRUCell(num_units=rnn_size, reuse=tf.AUTO_REUSE)