我一直在尝试与Visual Studio 15.9.6一起安装的与tensorflow 1.12.2相关的这些代码。 python版本是3.6.6。
问题出在log_huber函数中的条件语句。任何有关如何解决此问题的建议将不胜感激。该代码附在下面:
import tensorflow as tf
import numpy as np
def log_huber(x, m):
if tf.abs(x) <= tf.abs(m):
return x**2
else:
return m**2 * (1 - 2 * tf.log(m) + tf.log(x**2))
x = np.arange(10,dtype=np.float32)
m = np.arange(10,20,dtype=np.float32)
_x = tf.data.Dataset.from_tensor_slices(x).shuffle(10).repeat().batch(1)
iter_x = _x.make_one_shot_iterator()
_x_init_ops = iter_x.make_initializer(_x)
next_x = iter_x.get_next()
_m = tf.data.Dataset.from_tensor_slices(m).shuffle(10).repeat().batch(1)
iter_m = _m.make_one_shot_iterator()
_m_init_ops = iter_m.make_initializer(_x)
next_m = iter_m.get_next()
y = tf.contrib.eager.py_func(func=log_huber, inp=[next_x,next_m], Tout=tf.float32)
with tf.Session() as sess:
sess.run([_x_init_ops,_m_init_ops])
terminate = 1
while terminate!="0":
print(sess.run(y))
terminate = input("0 for end, 1 to continue")
错误消息如下:
...\testTensorboard\testTensorboard\dataset.py", line 5, in log_huber
if tf.abs(x) <= tf.abs(m):
...\conda\conda\envs\rdkit-env\lib\site-packages\tensorflow\python\framework\ops.py", line 914, in __bool__
"Non-scalar tensor %s cannot be converted to boolean." % repr(self))
ValueError: Non-scalar tensor <tf.Tensor: id=58, shape=(1,), dtype=bool, numpy=array([False])> cannot be converted to boolean.
答案 0 :(得分:1)
如果您这样使用tf.squeeze,则会删除尺寸。
def log_huber(x, m):
print (tf.abs(x))
if tf.squeeze(tf.abs(x)) <= tf.squeeze(tf.abs(m)):
return x**2
else:
return m**2 * (1 - 2 * tf.log(m) + tf.log(x**2))
从该张量的形状中删除大小为1的尺寸
tf.Tensor([2。],shape =(1,),dtype = float32)