keras + tensorflow 中的高级自定义激活函数

Advanced Custom activation function in keras + tensorflow

def newactivation(x):
    if x>0:
        return K.relu(x, alpha=0, max_value=None)
    else :
        return x * K.sigmoid(0.7* x)

get_custom_objects().update({'newactivation': Activation(newactivation)})

我正尝试在我的 keras 模型中使用这个激活函数,但我很难找到要替换的东西

if x>0:

错误我得到:

File "/usr/local/lib/python3.4/dist-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.

有人能帮我说清楚吗?

if x > 0 没有意义,因为 x > 0 是张量,而不是布尔值。

要在 Keras 中执行条件语句,请使用 keras.backend.switch

例如你的

if x > 0:
   return t1
else:
   return t2

会变成

keras.backend.switch(x > 0, t1, t2)

试试这样的:

def newactivation(x):
    return tf.cond(x>0, x, x * tf.sigmoid(0.7* x))

x 不是 python 变量,它是一个张量,当模型为 运行 时,它会保持一个值。 x 的值只有在评估该 op 时才知道,因此需要通过 TensorFlow(或 Keras)评估条件。

您可以评估张量,然后检查条件

from keras.backend.tensorflow_backend import get_session


sess=get_session()
if sess.run(x)>0:
    return t1
else:
    return t2

get_session 不适用于 TensorFlow 2.0。您可以找到 here

的解决方案

受 ed 2018 年 3 月 21 日在 17:28 的先前回答的启发 汤姆霍斯金。这对我有用。 tf.cond

def custom_activation(x):
    return tf.cond(tf.greater(x, 0), lambda: ..., lambda: ....)