【问题标题】:Tensorflow error: Using a `tf.Tensor` as a Python `bool` is not allowedTensorflow 错误:不允许使用 `tf.Tensor` 作为 Python `bool`
【发布时间】:2018-07-12 07:06:05
【问题描述】:

我正在努力在 Python 中的 中实现激活函数。

代码如下:

def myfunc(x):
    if (x > 0):
        return 1
    return 0

但我总是收到错误:

不允许将 tf.Tensor 用作 Python bool。使用if t is not None:

【问题讨论】:

    标签: tensorflow tensorflow machine-learning deep-learning keras activation-function


    【解决方案1】:

    使用tf.cond:

    tf.cond(tf.greater(x, 0), lambda: 1, lambda: 0)
    

    另一种解决方案,另外还支持多维张量:

    tf.sign(tf.maximum(x, 0))
    

    但是请注意,这个激活的梯度在任何地方都是零,所以神经网络不会用它学习任何东西。

    【讨论】:

    • 不幸的是,我现在有此错误,形状必须为 0 级,但对于具有输入形状的 'actfc1_36/activation_15/cond/Switch'(操作:'Switch')为 2 级
    【解决方案2】:

    在TF2中,你可以只用@tf.function装饰函数myfunc():

    @tf.function
    def myfunc(x):
        if (x > 0):
            return 1
        return 0
    

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2021-04-18
      • 1970-01-01
      • 2020-05-04
      • 2020-07-31
      相关资源
      最近更新 更多