【问题标题】:Tensorflow python. ValueError: Non-scalar tensor cannot be converted to boolean张量流蟒蛇。 ValueError:非标量张量不能转换为布尔值
【发布时间】:2019-03-04 07:44:01
【问题描述】:

我一直在尝试将这些与 tensorflow 1.12.2 相关的代码与 Visual Studio 15.9.6 一起安装。 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.

【问题讨论】:

  • .eval() 函数也可以提供帮助。这将评估表达式并返回一个值

标签: python-3.x tensorflow tensorflow-datasets


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2022-09-29
    • 2020-10-22
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多