FailedPreconditionError(请参阅上面的回溯):尝试使用未初始化的值rnn / gru_cell / gates / kernel

时间:2018-07-11 04:24:19

标签: python tensorflow

我使用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)]]

我在网站上搜索了类似的错误,但是我的代码无法很好地工作。

train.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)

model.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.initalize_all_variables()并初始化名为embbedding的tf.variables。那么出错的原因是什么?

1 个答案:

答案 0 :(得分:0)

一旦创建了所有变量,就应实例化操作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之前实例化。