[英]keras activation function layer: model.add Activation('relu') gives invalid syntax
[英]Change the threshold value of the keras RELU activation function
我正在尝试在构建我的神经网络时更改激活 function Relu
的阈值。
因此,初始代码是下面写的,其中 relu 阈值的默认值为 0。
model = Sequential([
Dense(n_inputs, input_shape=(n_inputs, ), activation = 'relu'),
Dense(32, activation = 'relu'),
Dense(2, activation='softmax')
])
但是,Keras 提供了相同的 function 实现,可以参考这里并添加屏幕截图。
因此,我将代码更改为以下代码以传递自定义 function 仅得到以下错误。
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 function 中使用 x 但我无法通过类似的东西。 语法要求我写model.add(layers.Activation(activations.relu))
但我将无法更改阈值。 这是我需要解决方法或解决方案的地方。
然后我使用了 ReLU function 的层实现,它对我有用,如下所示,但我想知道是否有一种方法可以使激活 function 实现工作,因为该层并不总是方便添加,我想制作Dense function 内部的更多修改。
对我有用的代码:-
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')
])
您面临的错误是合理的。 但是,您可以在relu
function 上使用以下技巧来完成您的工作。 In this way, you define a function that takes necessary arguments eg alpha
, threshold
etc, and in the function body, you define another function that calculates relu
activations with these parameters, and the end returns to the upper function.
# 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')
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.