需要实现三个方法:
- build(input_shape):定义你自己权重的地方,需要设置self.built=True.你可以通过调用super([Layer],self).build()来实现
- call(x):定义层逻辑的地方。除非你需要支持mask,否则你只需要关系传递给call的第一个参数
- compute_output_shape(input_shape):防止你更改你输入的shape,你需要定义shape改变的逻辑
from keras import backend as K
from keras.layers import Layer
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):
return K.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)