python - 如何阻止变量被更新?

标签 python tensorflow machine-learning neural-network

在 Tensorflow 中训练神经网络后,如何阻止它更新权重和偏差以测试其当前值?据我所知,您可以使用 inspect_checkpoint.print_tensors_in_checkpoint_file 检查它们,但它为您提供的输出是无需计算的。我已经尝试过了:

  • tf.train.Saver.restore - 这只会在保存变量后使反向传播恢复正常(与我想要实现的完全相反!)
  • tf.variable_scope.reuse_variables - 不起作用
  • tf.stop_gradient - 令人惊讶的是,一组值在打印变量的范围内 (0,10) 的循环中出现两次。然而,在所有其他迭代中,变量采用其他值。

最佳答案

仅当您运行相应的操作时,才会完成更新操作(例如,调用optimize)。如果您想访问变量的值而不更新它,请不要运行更新操作(例如 train_optf.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/

相关文章:

Python:使用多维 multiprocessing.manager.list()

python - 导入错误 : No module named '_pywrap_tensorflow_internal'

machine-learning - 带约束的梯度下降(拉格朗日乘子)

python - 经过一些迭代后,损失突然变成了 Nan

python - 在 MAMP 上使用 Python

python - 在方法内的 %time 语句中定义的变量在该语句之后不可访问

tensorflow - 组合条件和控制依赖关系

python - 分布式 Tensorflow 模型并不比独立模型快

python - 使用 dill 库保存和加载 neupy 算法可以在同一时间段返回不同的预测吗?

python - 如何获取切换标志值以及标志切换之间的行总和