【问题标题】:Custom activation function Keras: Applying different activation to different layers自定义激活函数 Keras:对不同层应用不同的激活
【发布时间】:2018-06-29 13:29:16
【问题描述】:

我的自定义激活函数的 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]。

有人能告诉我这是否是正确的做法吗?

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    Keras Activations 旨在处理几乎任何可以想象的前馈层(例如 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?,它建议按照您在问题中写的内容进行操作。

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 1970-01-01
      • 2019-05-09
      • 2021-05-15
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      相关资源
      最近更新 更多