此代码可以正常工作:
import tensorflow as tf
x = tf.Variable(initial_value=0)
with tf.Session() as session:
print session.run(x.assign(1))
但是这段代码失败了:
import tensorflow as tf
x = tf.Variable(initial_value=0)
supervisor = tf.train.Supervisor(logdir="/tmp")
with tf.Session() as session:
print session.run(x.assign(1))
唯一的区别是tf.train.Supervisor
的实例化。请注意,我们甚至不使用主管来创建托管会话。
错误是:
python tf_supervisor_freeze.py
Traceback (most recent call last):
File "tf_supervisor_freeze.py", line 6, in <module>
print session.run(x.assign(1))
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/ops/variables.py", line 522, in assign
return state_ops.assign(self._variable, value, use_locking=use_locking)
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/ops/gen_state_ops.py", line 47, in assign
use_locking=use_locking, name=name)
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 491, in apply_op
preferred_dtype=default_dtype)
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 702, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 110, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 103, in constant
attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0]
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2286, in create_op
self._check_not_finalized()
File "<virtual_env_path>/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2009, in _check_not_finalized
raise RuntimeError("Graph is finalized and cannot be modified.")
RuntimeError: Graph is finalized and cannot be modified.
Process finished with exit code 1
如果tf.train.Supervisor(logdir="/tmp", summary_op=None, saver=None)
用于禁用部分主管服务,则会出现错误。
Github上的其他人提出了这个问题,但没有提供答案;请求是在StackOverflow上提出问题。唯一相关的StackOverflow question似乎无法解决此特定情况。
答案 0 :(得分:4)
正如错误所述,您无法在图表最终确定时修改图表。
RuntimeError(&#34;图表已完成,无法修改。&#34;)
执行此代码tf.train.Supervisor()
时,图表将最终确定。您可以使用版本1.0的张量流中的路径/tensorflow/python/training/supervisor.py来检查它的代码。
你会发现这个:
# The graph is not allowed to change anymore.
graph.finalize()
因此,您无法在Supervisor()
之后修改图表。
答案 1 :(得分:3)
我无法解释为什么,但我找到了解决办法。这有效:
import tensorflow as tf
x = tf.Variable(initial_value=0)
a = x.assign(1)
supervisor = tf.train.Supervisor(logdir="/tmp")
with tf.Session() as session:
print session.run(a)
所做的一切都是在创建主管之前将创建赋值操作(即a = x.assign(1)
)。看来主管确实冻结了图表,以防止在主管创建之后创建或更准确地使用新操作。
答案 2 :(得分:0)
分配操作是图形中的新操作。 如果该操作是在图完成之前定义的(即使稍后执行),也可以。
有效地执行操作会为变量分配一个值。可以在图形完成后安全地完成此操作,因为它不会更改图形。
底线是: -在图形完成之前声明操作 -赶紧跑吧。