Tensorflow错误:不允许将`tf.Tensor`用作Python `bool`

12
我正在努力在Python的中实现一个激活函数。
代码如下:
def myfunc(x):
    if (x > 0):
        return 1
    return 0

但我总是得到以下错误:

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

2个回答

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

另一个解决方案,此外还支持多维张量

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

需要注意的是,这种激活函数在每个位置的梯度都为零,因此神经网络无法从中学习到任何信息。


很不幸,我现在遇到了这个错误:“actfc1_36/activation_15/cond/Switch”(op: 'Switch')的形状必须为等级0,但实际却是等级2。 - Lilo

3
TF2 中,您可以使用 @tf.function 装饰函数 myfunc():
@tf.function
def myfunc(x):
    if (x > 0):
        return 1
    return 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接