如何从关注类中获取注意力量

时间:2017-04-26 03:58:09

标签: python keras attention-model

class AttLayer(Layer):
    def __init__(self, **kwargs):
        self.init = initializations.get('normal')
        #self.input_spec = [InputSpec(ndim=3)]
        super(AttLayer, self).__init__(** kwargs)

    def build(self, input_shape):
        assert len(input_shape)==3
        #self.W = self.init((input_shape[-1],1))
        self.W = self.init((input_shape[-1],))
        #self.input_spec = [InputSpec(shape=input_shape)]
        self.trainable_weights = [self.W]
        super(AttLayer, self).build(input_shape)  # be sure you call this somewhere!

    def call(self, x, mask=None):
        eij = K.tanh(K.dot(x, self.W))

        ai = K.exp(eij)
        weights = ai/K.sum(ai, axis=1).dimshuffle(0,'x')

        weighted_input = x*weights.dimshuffle(0,1,'x')
        return weighted_input.sum(axis=1)

    def get_output_shape_for(self, input_shape):
        return (input_shape[0], input_shape[-1])

我有兴趣从班级获得注意力量而不是自我.W(层的权重)。有人可以告诉我我该怎么做?

这是我做的: MAX_SENT_LENGTH=40

the image has the code i wrote

当我尝试将模型创建为: sentEncoder =Model(sentence_input,weighted_inp)

它会抛出以下错误:

  

输出张量到模型必须是Keras张量。找到:Sum {axis = 1,   acc_dtype = float64} 0.0

0 个答案:

没有答案