ValueError:操作'cond_25 / Shape'已被标记为不可提取

时间:2019-03-21 09:29:53

标签: python tensorflow

当我尝试执行以下操作时,会发生上述错误:

se = tf.Session()
cont = tf.constant([[1., 2., 4., 5.], [5., 2., 7., 8.]])
def f1():
    print(se.run(tf.shape(cont)))
    return True
def f2():
    return False
r = tf.cond(tf.greater(tf.constant(10), tf.constant(9)), f1, f2)

完整的错误日志如下:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-44-ca1189c6f7a2>", line 7, in <module>
    r = tf.cond(tf.greater(tf.constant(10), tf.constant(9)), f1, f2)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2086, in cond
orig_res_t, res_t = context_t.BuildCondBranch(true_fn)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 1930, in BuildCondBranch
original_result = fn()
  File "<ipython-input-44-ca1189c6f7a2>", line 3, in f1
    print(se.run(tf.shape(cont)))
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 929, in run
    run_metadata_ptr)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1137, in _run
    self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 484, in __init__
    self._assert_fetchable(graph, fetch.op)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 497, in _assert_fetchable
    'Operation %r has been marked as not fetchable.' % op.name)

并不是cont无法访问变量f1(),因为以下命令可以正确执行:

cont = tf.constant([[1., 2., 4., 5.], [5., 2., 7., 8.]])
def f1():
    print(se.run((cont)))
    return True
def f2():
    return False
r = tf.cond(tf.greater(tf.constant(10), tf.constant(9)), f1, f2)

输出:
[[1. 2. 4. 5.] [5. 2. 7. 8.]]

有人可以建议为什么发生这种情况,并且如何纠正它?

1 个答案:

答案 0 :(得分:0)

您看到的错误已说明here

请在说明中注意这一行。

  

请记住,传递给tf.cond()或tf.while_loop()的所有函数必须是纯函数,因此它们不得修改其环境。

import tensorflow as tf


se = tf.Session()
cont = tf.constant([[1., 2., 4., 5.], [5., 2., 7., 8.]])
def f1():
    print('Shape is ',tf.shape(cont))
    return True
def f2():
    return False
r = tf.cond(tf.greater(tf.constant(10), tf.constant(9)), f1, f2)

此代码执行没有错误。

如果您对静态和动态形状感到困惑,this会很好地解释它。