【问题标题】:How to define a modified leaky ReLU - TensorFlow如何定义修改后的泄漏 ReLU - TensorFlow
【发布时间】:2021-11-18 00:08:02
【问题描述】:

我想使用具有最小化而不是最大化的leaky-ReLu 函数作为我对密集层的激活。换句话说,我希望我的激活是f(x) = min{x, \alpha x }。我先定义一个方法,如下图。

def new_leaky_relu(x, alpha):
    part_1 = tf.cast(tf.math.greater_equal(0.0, x), dtype='float32')   
    part_2 = tf.cast(tf.math.greater_equal(x, 0.0), dtype='float32') 
    return (part_1*x) + (x*part_2*k) 

当我在一个简单的模型上测试它时,我确实收到了一个错误。

model = tf.keras.Sequential([ 
tf.keras.layers.Flatten(input_shape=(124,))])  
model.add(tf.keras.layers.Dense(256,activation=new_leaky_relu(alpha=0.1)))
new_leaky_relu() missing 1 required positional argument: 'x'

如何确保它是一个激活函数并且在编译模型时不必传递输入?另外,我构建激活函数的方式是有效的,还是有更好的方式?

我还使用了其他帖子中分享的建议。见How do you create a custom activation function with Keras?

from keras.utils.generic_utils import get_custom_objects
from keras.layers import Activation
get_custom_objects().update({'custom_activation': Activation(new_leaky_relu)})

model = tf.keras.Sequential([ 
tf.keras.layers.Flatten(input_shape=(124,))])  
model.add((tf.keras.layers.Dense(256,Activation(new_leaky_relu(alpha=0.1))))

【问题讨论】:

    标签: python tensorflow keras activation-function


    【解决方案1】:

    你可以尝试如下:

    import tensorflow as tf 
    
    def custom_leaky_relu(alpha=0.0):        
        def new_leaky_relu(x):
            part_1 = tf.cast(tf.math.greater_equal(0.0, x), dtype='float32')   
            part_2 = tf.cast(tf.math.greater_equal(x, 0.0), dtype='float32') 
            return (part_1*x) + (x*part_2) 
        return new_leaky_relu
    
    model = tf.keras.Sequential([ 
    tf.keras.layers.Flatten(input_shape=(124,))])  
    model.add(tf.keras.layers.Dense(256, activation=custom_leaky_relu(alpha=0.1)))
    

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      相关资源
      最近更新 更多