在Keras中实现平方非线性(SQNL)激活函数

时间:2019-07-13 22:47:26

标签: tensorflow keras backend keras-layer activation-function

我一直在尝试将平方非线性激活函数功能实现为keras模型的自定义激活函数。这是列表https://en.wikipedia.org/wiki/Activation_function上的第10个函数。

我尝试使用keras后端,但是我不需要多个if else语句,因此我也尝试使用以下内容:

import tensorflow as tf
def square_nonlin(x):
    orig = x
    x = tf.where(orig >2.0, (tf.ones_like(x)) , x)
    x = tf.where(0.0 <= orig <=2.0, (x - tf.math.square(x)/4), x)
    x = tf.where(-2.0 <= orig < 0, (x + tf.math.square(x)/4), x)
    return tf.where(orig < -2.0, -1, x)

如您所见,我需要评估4个不同的条款。但是当我尝试编译Keras模型时,仍然出现错误:

Using a `tf.Tensor` as a Python `bool` is not allowed

有人可以帮我在Keras上使用它吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

我一周前才刚刚开始研究tensorflow,并积极地尝试各种激活功能。我想我知道您的两个问题是什么。在第二次和第三次分配中,您需要将复合条件放在tf.logical_and下。您遇到的另一个问题是返回线上的最后一个tf.where返回一个-1,它不是张量流所期望的向量。我没有用Keras尝试过该功能,但是在我的“激活功能”测试器中,此代码有效。

def square_nonlin(x):
    orig = x
    x = tf.where(orig >2.0, (tf.ones_like(x)) , x)
    x = tf.where(tf.logical_and(0.0 <= orig, orig <=2.0), (x - tf.math.square(x)/4.), x)
    x = tf.where(tf.logical_and(-2.0 <= orig, orig < 0), (x + tf.math.square(x)/4.), x)
    return tf.where(orig < -2.0, 0*x-1.0, x)

正如我所说的,我是新手,所以可以将-1向量化x,然后将0向量乘以-1,然后减去-1,从而得到一个填充的数组tf.greater的形状正确。也许是经验丰富的张量流实践者之一可以建议这样做的正确方法。

希望这会有所帮助。

顺便说一句,tf.__gt__orig > 2.0等价,这意味着tf.greater(orig, 2.0)在python的幕后扩展为-1

只需跟进。我在Keras的MNIST演示中进行了尝试,并且激活功能按上面的代码工作。

更新:

“矢量化” tf.ones_like的一种比较轻松的方法是使用 return tf.where(orig < -2.0, -tf.ones_like(x), x) 函数

因此将最后一行替换为

using (MemoryStream memoryStream = new MemoryStream())
        using (StreamWriter streamWriter = new StreamWriter(memoryStream, Encoding.Unicode))
        {
            writeToStream(rows, streamWriter);

            bytes = compress(memoryStream);
        }

寻求更清洁的解决方案