【问题标题】:Implementing the Square Non-linearity (SQNL) activation function in Keras在 Keras 中实现平方非线性 (SQNL) 激活函数
【发布时间】:2019-07-13 22:47:26
【问题描述】:

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

我尝试使用 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 中使用它吗?非常感谢。

【问题讨论】:

  • 我觉得你需要用tf.greater(x, 2.0)等函数替换比较语句。
  • 我已经尝试过了,它仍然给出了同样的错误。还有其他想法吗?

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


【解决方案1】:

我一周前刚刚开始研究 tensorflow,并且正在积极尝试不同的激活函数。我想我知道你的两个问题是什么。在您的第二个和第三个作业中,您需要将复合条件放在tf.logical_and 下。您遇到的另一个问题是返回行上的最后一个tf.where 返回一个-1,它不是tensorflow 所期望的向量。我还没有尝试过 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 的数组.也许一位经验丰富的 tensorflow 实践者可以提出正确的方法来做到这一点。

希望这会有所帮助。

顺便说一句,tf.greater 等同于tf.__gt__,这意味着orig &gt; 2.0 在python 中扩展为tf.greater(orig, 2.0)

只是一个跟进。我在 Keras 中使用 MNIST 演示进行了尝试,并且激活函数按上面的代码工作。

更新:

“矢量化”-1 的较简单的方法是使用 tf.ones_like 函数

所以将最后一行替换为

   return tf.where(orig < -2.0, -tf.ones_like(x), x)

为了更清洁的解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-23
    • 2019-05-20
    • 1970-01-01
    • 2017-08-10
    • 2019-09-10
    • 2020-12-05
    • 2019-01-09
    • 2023-03-13
    相关资源
    最近更新 更多