【问题标题】:Change the threshold value of the keras RELU activation function改变keras RELU激活函数的阈值
【发布时间】:2021-07-30 16:26:06
【问题描述】:

我正在尝试在构建我的神经网络时更改激活函数Relu 的阈值。

所以,初始代码是下面写的,其中 relu 阈值的默认值为 0。

model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, ), activation = 'relu'),
    Dense(32, activation = 'relu'),
    Dense(2, activation='softmax')
])

不过,Keras 提供了相同的功能实现,可以参考here 并添加截图。

因此,我将代码更改为以下以传递自定义函数,结果却出现以下错误。

from keras.activations import relu
model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, ), activation = relu(threshold = 2)), 
    Dense(32, activation = relu(threshold = 2)),
    Dense(2, activation='softmax')
])

错误: TypeError: relu() missing 1 required positional argument: 'x'

我知道错误是我没有在 relu 函数中使用 x,但我无法传递类似的东西。语法要求我写model.add(layers.Activation(activations.relu)),但我将无法更改阈值。这就是我需要解决方法或解决方案的地方。

然后我使用了Layer implementation of the ReLU function,它对我有用,如下所示,但我想知道是否有一种方法可以使激活函数实现工作,因为添加层并不总是很方便,我想制作Dense 函数内部的更多修改。

对我有用的代码:-

from keras.layers import ReLU
model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, )),
    ReLU(threshold=4), 
    Dense(32),
    ReLU(threshold=4),
    Dense(2, activation='softmax')
])

【问题讨论】:

    标签: python tensorflow keras neural-network relu


    【解决方案1】:

    您面临的错误是合理的。但是,您可以在 relu 函数上使用以下技巧来完成您的工作。这样,您定义了一个带有必要参数的函数,例如alphathreshold 等,并在函数体中定义另一个函数,该函数使用这些参数计算 relu 激活,并且结束返回上层函数。

    # help(tf.keras.backend.relu)
    from tensorflow.keras import backend as K
    def relu_advanced(alpha=0.0, max_value=None, threshold=0):        
        def relu_plus(x):
            return K.relu(x, 
                          alpha = tf.cast(alpha, tf.float32), 
                          max_value = max_value,
                          threshold= tf.cast(threshold, tf.float32))
        return relu_plus
    

    样品:

    foo = tf.constant([-10, -5, 0.0, 5, 10], dtype = tf.float32)
    tf.keras.activations.relu(foo).numpy()
    array([ 0.,  0.,  0.,  5., 10.], dtype=float32)
    
    x = relu_advanced(threshold=1)
    x(foo).numpy()
    array([-0., -0.,  0.,  5., 10.], dtype=float32)
    

    对于您的情况,只需使用如下:

    model = Sequential([
        Dense(64, input_shape=(32, ), activation = relu_advanced(threshold=2)), 
        Dense(32, activation = relu_advanced(threshold=2)),
        Dense(2, activation='softmax')
    ])
    

    【讨论】:

    猜你喜欢
    • 2017-05-06
    • 2021-08-31
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多