如何解决改变keras RELU激活函数的阈值
我正在尝试在构建我的神经网络时更改激活函数 Relu
的阈值。
所以,最初的代码是下面写的,其中 relu 阈值的默认值为 0。
model = Sequential([
Dense(n_inputs,input_shape=(n_inputs,),activation = 'relu'),Dense(32,Dense(2,activation='softmax')
])
但是,Keras 提供了相同的功能实现,可以参考 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
函数上使用以下技巧来完成您的工作。通过这种方式,您定义了一个接受必要参数的函数,例如 alpha
、threshold
等,并且在函数体中,您定义了另一个计算 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')
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。