我正在尝试用一个分段线性函数替换Keras的Sigmoid函数,该函数定义如下:
def custom_activation_4(x):if x < -6: return 0elif x >= -6 and x < -4: return (0.0078*x + 0.049)elif x >= -4 and x < 0: return (0.1205*x + 0.5)elif x >= 0 and x < 4: return (0.1205*x + 0.5)elif x >= 4 and x < 6: return (0.0078*x + 0.951)else: return 1;
当我尝试这样运行时:
classifier_4.add(Dense(output_dim = 18, init = 'uniform', activation = custom_activation_4, input_dim = 9))
编译器抛出错误说:
Using a `tf.Tensor` as a Python `bool` is not allowed.
我研究了这个问题并了解到,我将变量x视为一个简单的Python变量,而它实际上是一个张量。这就是它不能像简单的布尔变量那样被处理的原因。我还尝试使用了tensorflow cond方法。如何在这里将x视为并使用张量?非常感谢您提前提供的所有帮助。
回答:
您的自定义激活函数是作为单个浮点数的函数编写的,但您想将其应用于整个张量。最好的方法是使用tf.where
。像这样
def custom_activation_4(x): orig = x x = tf.where(orig < -6, tf.zeros_like(x), x) x = tf.where(orig >= -6 and orig < -4, (0.0078*x + 0.049), x) x = tf.where(orig >= -4 and orig < 0, (0.1205*x + 0.5), x) x = tf.where(orig >= 0 and orig < 4, (0.1205*x + 0.5), x) x = tf.where(orig >= 4 and orig < 6, (0.0078*x + 0.951), x) return tf.where(orig >= 6, 1, x)