改变keras RELU激活函数的阈值

问题描述

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

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

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

但是,Keras 提供了相同的功能实现,可以参考 here 并添加屏幕截图。

enter image description here

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

from keras.activations import relu
model = Sequential([
    Dense(n_inputs,activation = relu(threshold = 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,)),ReLU(threshold=4),Dense(32),activation='softmax')
])

解决方法

您面临的错误是合理的。但是,您可以在 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.,5.,10.],dtype=float32)

x = relu_advanced(threshold=1)
x(foo).numpy()
array([-0.,-0.,dtype=float32)

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...