Python 自定义激活功能Keras:对不同层应用不同的激活
自定义激活函数的i/p是19*19*5张量,比如x。该函数需要将sigmoid应用于第一层,即x[:,:,0:1],并将relu应用于其余层,即x[:,:,1:5]。我使用以下代码定义了一个自定义激活函数:Python 自定义激活功能Keras:对不同层应用不同的激活,python,tensorflow,keras,Python,Tensorflow,Keras,自定义激活函数的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({'cust
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
激活
s设计用于几乎任何可想象的前馈层的任意大小的层(例如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)
但是,如果您打算在网络中的许多不同层之后使用此转换,从而真正想要自定义定义的激活
,请参阅,这建议您按照问题中的内容进行操作