TensorFlow: TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed

若如初见. 提交于 2019-12-23 12:08:38

问题


I'm trying to define a triplet loss using descriptor from a CNN's output, but this error showed up when I try to train the network.

My definition of loss function:

def compute_loss(descriptor, margin):
    diff_pos = descriptor[0:1800:3] - descriptor[1:1800:3]
    diff_neg = descriptor[0:1800:3] - descriptor[2:1800:3]
    Ltriplet = np.maximum(0, 1 - tf.square(diff_neg)/(tf.square(diff_pos) + margin))
    Lpair = tf.square(diff_pos)

    Loss = Ltriplet + Lpair

    return Loss

here descriptor is the outcome of CNN, the income of CNN is a set of triplets containing anchor, puller and pusher exactly in this order. As input I packed 600 triplet together and feed them into the CNN.

Then I got this error when training the network:

2018-03-08 16:40:49.529263: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
Traceback (most recent call last):
  File "/Users/gaoyingqiang/Documents/GitHub/Master-TUM/TDCV/exercise_3/ex3/task2_new.py", line 78, in <module>
    loss = compute_loss(h_fc2, margin)
  File "/Users/gaoyingqiang/Documents/GitHub/Master-TUM/TDCV/exercise_3/ex3/task2_new.py", line 37, in compute_loss
    Ltriplet = np.maximum(0, 1 - tf.square(diff_neg)/(tf.square(diff_pos) + margin))
  File "/Users/gaoyingqiang/.virtualenvs/ex3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 614, in __bool__
    raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

Process finished with exit code 1

Where goes wrong?


回答1:


You are mixing numpy and tensorflow operations. Tensorflow accepts numpy arrays normally (their value is known statically, hence can be converted to a constant), but not vice versa (tensor value is known only when the session is run, except eager evaluation).

The solution: change np.maximum to tf.maximum.



来源:https://stackoverflow.com/questions/49177169/tensorflow-typeerror-using-a-tf-tensor-as-a-python-bool-is-not-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!