写我自己的keras层

时间:2016-11-30 02:09:49

标签: python-2.7 deep-learning keras keras-layer

我想编写自己的keras图层,将带有形状的张量(nb_batch,input_dim)作为输入,并生成带形状的张量(nb_batch,context_size,output_dim)。我在下面写了一个演示:

class MyLayer(Layer):
def __init__(self, output_dim, context_size, init="uniform", **kwargs):
    self.output_dim = output_dim
    self.context_size = context_size
    self.init = initializations.get(init)
    super(MyLayer, self).__init__(**kwargs)

def build(self, input_shape):
    input_dim = input_shape[1]
    self.W_vec = self.init(
        (self.context_size, input_dim, self.output_dim),
        name="W_vec")

    self.trainable_weights = [self.W_vec]
    super(MyLayer, self).build()  # be sure you call this somewhere!

def call(self, x, mask=None):
    return K.dot(x, self.W_vec)
    # return K.dot(x, self.W)

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

当我运行它时,出现错误" TypeError:build()只需要2个参数(给定1个)" enter code here

1 个答案:

答案 0 :(得分:0)

看起来构建需要输入形状参数

super(MyLayer, self).build(input_shape) # be sure you call this somewhere!