Reputation: 1295
The above error occurs when I try to do the following:
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)
The complete error log is as follows:
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)
It is not that the variable cont
is in-accessible by f1()
, as the following exectues correctly:
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)
Output:
[[1. 2. 4. 5.]
[5. 2. 7. 8.]]
Can someone suggest why is this happening and how to correct it?
Upvotes: 1
Views: 1813
Reputation: 3197
The error you see is explained here
Please note this line in the explanation.
Recall that all functions passed to tf.cond() or tf.while_loop() must be pure functions, and so they must not modify their environment.
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 code executes without error.
If you are confused with static and dynamic shapes this explains it well.
Upvotes: 1