首页 > 解决方案 > FailedPreconditionError(参见上面的回溯):尝试使用未初始化的值 rnn/gru_cell/gates/kernel

问题描述

我使用 tensorflow 运行下面的代码,并得到错误:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value rnn/gru_cell/gates/kernel
 [[Node: rnn/gru_cell/gates/kernel/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](rnn/gru_cell/gates/kernel)]]

我在网站上搜索了类似的错误,但不适用于我的代码。

火车.py:

if __name__ == '__main__':
q = np.array([[1,2,3,1,4],[2,3,4,1,0],[3,4,1,2,1]])

f = np.ones((3,2,5))
y = np.array([[1,0,0,0],[0,0,0,1],[0,0,1,0]])
#init = tf.initialize_all_variables()
with tf.Session() as sess:
    m = model.Readers_Model(3,0.01,5,5,2,5,5)
    sess.run(m.init_op)
    loss,_ = sess.run([m.input_()],
    {m.question_placeholder:q,m.fact_placeholder:f,
    m.label_placeholder:y,m.dropout_placeholder:0.1})

    print ('loss is %f'%loss)

模型.py:

class Readers_Model(object):

def __init__(self,batch_size,lr,max_q_len,max_f_len,num_doc,hidden_size,vocub_size):
    self.init_op = tf.global_variables_initializer()

    self.embedding_size =   hidden_size   #word embedding
    self.word_embeddings = tf.get_variable('embedding',[self.vocabulary_size, self.embedding_size],
                                           initializer=tf.random_normal_initializer(mean=0, stddev=1))
    self.label_placeholder = tf.placeholder(tf.int32, shape=(self.batch_size,self.num_class))
    self.fact_placeholder = tf.placeholder(tf.int32, shape=(self.batch_size, self.num_doc, self.max_f_len))
    self.dropout_placeholder = tf.placeholder(tf.float32)
    self.question_placeholder = tf.placeholder(tf.int32, shape=(self.batch_size, self.max_q_len),name='question')

def quesiton_encoding_layer(self):
    input = tf.nn.embedding_lookup(self.word_embeddings, self.question_placeholder)

    gru_cell = tf.contrib.rnn.GRUCell(self.hidden_size)
    output, last_state = tf.nn.dynamic_rnn(gru_cell,
                                 input,
                                 dtype=np.float32,

                                 )

    #shape:[batch_size, GRU_hidden_size]
    '''
    last_state = tf.nn.dropout(last_state, self.dropout_placeholder)
    '''
    last_hidden_unit = last_state[1]

    return output,last_state

看看上面的代码,我在会话开始时运行了 tf.initialize_all_variables() 并初始化了名为 embbedding 的 tf.variables。那么错误的原因是什么?

标签: pythontensorflow

解决方案


tf.global_variables_initializer()一旦创建了所有变量,就应该实例化该操作。例如,下面的代码片段产生一个FailedPreconditionError: Attempting to use uninitialized value

import tensorflow as tf

init = tf.global_variables_initializer()
a = tf.Variable(1)

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(a))

请注意,Readers_Model.__init__您正在实例化self.init_op之前self.word_embeddings,并且可能也在之前gru_cell


推荐阅读