Keras自定义层

例子为单输入单输出层
匿名函数定义

Lambda(lambda x: (x - 100)/255, input_shape=(784,))
#Lambda若作为第一层,需要指定input_shape

自定义函数

class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel', 
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):
        x = (x - 100)/255
        return K.dot(x, self.kernel)
#call()中定义对输入的处理,当你定义了build()后call()中必须包含数据转化,即对输入进行操作后,必须进行映射操作,这里为点乘

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

猜你喜欢

转载自blog.csdn.net/weixin_43414981/article/details/90759336