我正在尝试使用来自 CNN 输出的描述符来定义三元组损失,但是当我尝试训练网络时出现了这个错误。
我对损失函数的定义:
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
这里的descriptor是CNN的outcome,CNN的income是一组三元组,依次是anchor、puller、pusher。作为输入,我将 600 个三元组打包在一起并将它们送入 CNN。
然后我在训练网络的时候出现了这个错误:
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
哪里出了问题?
最佳答案
您正在混合使用 numpy 和 tensorflow 操作。 Tensorflow 通常接受 numpy 数组(它们的值是静态已知的,因此可以转换为常量),但反之亦然(张量值仅在 session 运行时已知,eager evaluation 除外)。
解决方案:将np.maximum
改为tf.maximum
。
关于python - TensorFlow:TypeError:不允许将 `tf.Tensor` 用作 Python `bool`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49177169/