【发布时间】:2018-03-13 22:24:26
【问题描述】:
我正在构建一个神经网络。我在火车部分使用tf.variable_scope(),对测试部分使用相同的范围(reset=True)。我想知道如果我使用tf.train.Saver() 将变量保存在火车部分并使用tf.train.restore() 恢复测试部分的变量,是否会得到不同的结果?
基本上,我想确保将训练后的变量复制到测试部分。
例如,在下面的示例中,变量 v1 和 v_1 具有相同的值,那么,在这种情况下,我是否需要使用 tf.train.Saver() 才能获得正确的结果?
将张量流导入为 tf
tf.reset_default_graph()
# Create some variables.
with tf.variable_scope("first_model"):
v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)
inc_v1 = v1.assign(v1+2)
dec_v2 = v2.assign(v2-1)
with tf.variable_scope("first_model", reuse=True):
# Create some variables.
v_1 = tf.get_variable("v1", shape=[3])
v_2 = tf.get_variable("v2", shape=[5])
inc_v_1 = v1.assign(v1+2)
dec_v_2 = v2.assign(v2-1)
# Add an op to initialize the variables.
init_op = tf.global_variables_initializer()
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Later, launch the model, initialize the variables, do some work, and save the
# variables to disk.
with tf.Session() as sess:
sess.run(init_op)
# Do some work with the model.
inc_v1.op.run()
dec_v2.op.run()
inc_v_1.op.run()
dec_v_2.op.run()
# Save the variables to disk.
save_path = saver.save(sess, "/tmp/model_2.ckpt")
print("Model saved in path: %s" % save_path)
print("v1 : %s" % v1.eval())
print("v2 : %s" % v2.eval())
print("v_1 : %s" % v_1.eval())
print("v_2 : %s" % v_2.eval())
【问题讨论】:
标签: python tensorflow neural-network