Skip to main content
 首页 » 编程设计

python之自定义激活函数 Keras : Applying different activation to different layers

2024年12月31日28dudu

我的自定义激活函数的 i/p 将是一个 19 * 19 * 5 张量,比如 x。该函数需要将 sigmoid 应用于第一层,即 x[:,:,0:1],并将 relu 应用于其余层,即 x[:,:,1:5]。我已经使用以下代码定义了一个自定义激活函数:

def custom_activation(x): 
    return tf.concat([tf.sigmoid(x[:,:,:,0:1]) , tf.nn.relu(x[:,:,:,1:5])],axis = 3) 
 
get_custom_objects().update({'custom_activation': Activation(custom_activation)}) 

第四个维度出现在图片中,因为在我得到的函数 custom_activation 的输入中,批量大小作为另一个维度。所以输入张量的形状是[bathc_size,19,19,5]。

谁能告诉我这样做是否正确?

请您参考如下方法:

Keras Activation 旨在处理几乎任何可以想象的前馈层(例如 Tanh、Relu、Softmax 等)的任意大小的层。您描述的转换听起来特定于您正在使用的体系结构中的特定层。因此,我建议使用 Lambda 层来完成任务:

from keras.layers import Lambda 
 
def custom_activation_shape(input_shape): 
     # Ensure there is rank 4 tensor 
     assert len(input_shape) == 4 
     # Ensure the last input component has 5 dimensions 
     assert input_shape[3] == 5 
 
     return input_shape  # Shape is unchanged 

然后可以将其添加到您的模型中

Lambda(custom_activation, output_shape=custom_activation_shape) 

但是,如果您打算在网络中的许多不同层之后使用此转换,并且因此真正喜欢自定义定义的 Activation,请参阅 How do you create a custom activation function with Keras? ,这表明按照您在问题中所写的进行操作。