在 Tensorflow 中训练神经网络后,如何阻止它更新权重和偏差以测试其当前值?据我所知,您可以使用 inspect_checkpoint.print_tensors_in_checkpoint_file
检查它们,但它为您提供的输出是无需计算的。我已经尝试过了:
tf.train.Saver.restore
- 这只会在保存变量后使反向传播恢复正常(与我想要实现的完全相反!)tf.variable_scope.reuse_variables
- 不起作用tf.stop_gradient
- 令人惊讶的是,一组值在打印变量的范围内 (0,10) 的循环中出现两次。然而,在所有其他迭代中,变量采用其他值。
最佳答案
仅当您运行相应的操作时,才会完成更新操作(例如,调用optimize
)。如果您想访问变量的值而不更新它,请不要运行更新操作(例如 train_op
或 tf.assign
),并且仅评估变量:
import tensorflow as tf
weight = tf.Variable(0.0)
op = tf.assign_add(weight, 1) # update weight by adding 1 to it
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(weight)) # Get the value of the weight
print(sess.run(op)) # Update the weight
print(sess.run(weight)) # Get the value of the weight but don't update it
print(sess.run(weight)) # Get the value of the weight
将打印:
0.0
1.0
1.0
1.0
关于python - 如何阻止变量被更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49385147/