python - 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。那么错误的原因是什么?
解决方案
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
。
推荐阅读
- drop-down-menu - 如何在 Swift 4 和 iOS 11 中实现一个小的下拉菜单到 UIButton,例如选择一种货币?
- javascript - 使用动态输入删除操作符在 Javascript 中的项目
- typescript - 如何从 TypeScript 中的字符串数组创建类型?
- typescript - Animated.View 的样式道具的打字稿定义
- botframework - 如何在 Microsoft BOT 框架中检测和读取 facebook Emojis
- powershell - 通过 ssis 包运行时导入的 powershell 模块不可见
- r - 在 For 循环中的 R 中创建子集数据框
- amp-html - amp-next-page 是一种在用户缓存中预加载其他页面的方法吗?
- kubernetes - 如何使用一个代理在 Mesosphere DC/OS 上成功运行 Kubernetes?
- javascript - Javascript:日期 A 在日期 B 的 x 天内