我在恢复一些变量时遇到了问题。当我在更高的层次上保存整个模型时,我已经恢复了变量,但这次我决定只恢复几个变量。在第一个会话之前,我初始化权重:
weights = {
'1': tf.Variable(tf.random_normal([n_input, n_hidden_1], mean=0, stddev=tf.sqrt(2*1.67/(n_input+n_hidden_1))), name='w1')
}
weights_saver = tf.train.Saver(var_list=weights)然后,在会话中,当我训练NN时:
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
[...]
weights_saver.save(sess, './savedModels/Weights/weights')然后:
with tf.Session() as sess:
new_saver = tf.train.import_meta_graph(pathsToVariables + 'Weights/weights.meta')
new_saver.restore(sess, pathsToVariables + 'Weights/weights')
weights =
{
'1': tf.Variable(sess.graph.get_tensor_by_name("w1:0"), name='w1', trainable=False)
}
sess.run(tf.global_variables_initializer())
print(sess.run(weights['1']))但在这一点上,恢复的权重似乎是随机的。事实上,如果我再次执行sess.run(tf.global_variables_initializer()),权重将会不同。就好像,我恢复了权重初始化的正常功能,但没有恢复训练权重。
我做错了什么?
我的问题清楚了吗?
发布于 2018-05-03 03:10:20
weights =
{
'1': tf.Variable(sess.run(sess.graph.get_tensor_by_name("w1:0")), name='w1', trainable=False)
}我找到了答案。我需要运行张量来获得值。现在这一点似乎很明显。
编辑2:
这种方式不是从其他值初始化张量的好方法,因为当我们恢复并创建张量时,它将创建2个具有相同名称的张量。或者,如果名称不同,它将恢复过去模型中的变量,并可能稍后尝试对其进行优化。最好恢复前一个会话中的变量,存储这些值,然后关闭会话,打开一个新会话以创建其他所有内容。
with tf.session() as sess:
weight1 = sess.run(sess.graph.get_tensor_by_name("w1:0"))
tf.reset_default_graph() #this will eliminate the variables we restored
with tf.session() as sess:
weights =
{
'1': tf.Variable(weight1 , name='w1-bis', trainable=False)
}
...我们现在可以确定恢复的变量不是图的一部分。
https://stackoverflow.com/questions/50017707
复制相似问题