5
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])

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

这是我所做的: MAX_SENT_LENGTH=40

图片有我写的代码

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

它抛出以下错误:

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

4

0 回答 0