【问题标题】:Piecewise activation function in tensorflow and broadcasting math operation张量流和广播数学运算中的分段激活函数
【发布时间】:2019-01-15 17:54:39
【问题描述】:

我正在尝试实现和测试我在一篇论文中读到的激活函数。

我正在使用带有 tensorflow 后端的 Keras,我想将激活函数提供给我的模型的 fit 方法。这是函数的数学形式:

Piecewise Formula

我尝试通过两种方式实现这一点:

def function_1(x):

    cond1 = tf.greater(x , 2.0)
    cond2 = tf.logical_and(tf.less_equal(x, 2.0), tf.greater_equal(x, 0.0))
    cond3 = tf.logical_and(tf.less(x, 0.0), tf.greater_equal(x, -2.0))
    cond4 = tf.less(x, -2.0)

    y = tf.where(cond1, tf.constant(1.0) , tf.where(cond2,
    x - 0.25*tf.square(x), tf.where(cond3, x + 0.25*tf.square(x), 
    tf.where(cond4, tf.constant(-1.0), tf.constant(-1.0)))))

    return y

def function_2(x):

    cond1 = tf.greater(x , 2.0)
    cond2 = tf.logical_and(tf.less_equal(x, 2.0), tf.greater_equal(x, 0.0))
    cond3 = tf.logical_and(tf.less(x, 0.0), tf.greater_equal(x, -2.0))
    cond4 = tf.less(x, -2.0)

    y = tf.case({cond1: lambda x: tf.constant(1.0), cond2: lambda x: x - 
    0.25*tf.square(x), cond3: lambda x: x + 0.25*tf.square(x),
    cond4: lambda x: tf.constant(-1.0)}, exclusive = True)

    return y

在这两种情况下,我都会遇到同样的错误:

InvalidArgumentError: Shapes must be equal rank, but are 0 and 2 for 'dense_22/Select' (op: 'Select') with input shapes: [?,5], [], [].

正确的方法是什么?我的代码有什么问题?

【问题讨论】:

    标签: python tensorflow keras neural-network activation-function


    【解决方案1】:

    问题是,您将形状为 [None, 5](等级 2)的张量与缩放器(等级 0)进行比较,这在 tf.greatertf.less 中是不可能的。相反,您可以使用支持广播的tf.math...

    这是实现此功能的一种可能的解决方案:

    import tensorflow as tf
    
    x = tf.placeholder(dtype=tf.float32, shape=[1, 5])
    
    cond1 = tf.cast(tf.math.greater(x, 2.0), tf.float32)
    cond2 = tf.cast(tf.math.logical_and(tf.math.less_equal(x, 2.0), tf.math.greater_equal(x, 0.0)), tf.float32)
    cond3 = tf.cast(tf.math.logical_and(tf.math.less(x, 0.0), tf.math.greater_equal(x, -2.0)), tf.float32)
    cond4 = tf.cast(tf.math.less(x, -2.0), tf.float32)
    
    a = tf.math.multiply(cond1, 1.0)
    b = tf.math.multiply(cond2, (x - tf.square(x) / 4))
    c = tf.math.multiply(cond3, (x + tf.square(x) / 4))
    d = tf.math.multiply(cond4, -1.0)
    
    f = a + b + c + d
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print(sess.run(f, feed_dict={x: [[-1.0, -5, 1.5, -1.5, 5]]})) 
    

    【讨论】:

    • 谢谢。问题已解决!没注意tf.math函数中的广播
    【解决方案2】:

    您可以尝试lambda层,它非常方便在网络中添加我们的自定义层或功能。这是一个例子:

    dense1 = Dense(dims)(input)   
    act1 = Lambda(customFunc, output_shape)(dense1)
    
    def customFunc(x):
        """-----operations----""""
        # final output y of shape defined as above in layer
        y = conditioned-output
        return y
    

    这里是更多info的链接这是另一个有用的link,用例子来解释。

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 2018-03-04
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      相关资源
      最近更新 更多