Deep learning keras和tensorflow中具有点和一般评分功能的梁式注意机制

Deep learning keras和tensorflow中具有点和一般评分功能的梁式注意机制,deep-learning,nlp,attention-model,Deep Learning,Nlp,Attention Model,我试图在keras中实现点积和从编码器和解码器输出以及隐藏状态分别计算相似性分数的一般实现 我有一个想法,用tf.keras.layers.dot(编码器输出,解码器状态)的乘积来计算产品分数,但是这两个值的乘积有错误 class Attention(tf.keras.Model): def __init__(self,units): super().__init__() self.units = units def call(self, decoder_state,

我试图在keras中实现点积和从编码器和解码器输出以及隐藏状态分别计算相似性分数的一般实现

我有一个想法,用
tf.keras.layers.dot(编码器输出,解码器状态)
的乘积来计算产品分数,但是这两个值的乘积有错误

class Attention(tf.keras.Model):
  def __init__(self,units):
    super().__init__()
    self.units = units

  def call(self, decoder_state, encoder_output):
      score = tf.keras.layers.dot([encoder_output,decoder_state], axes=[2, 1])
      
      attention_weights = tf.nn.softmax(score, axis=1)
      context_vector = attention_weights * encoder_output
      context_vector = tf.reduce_sum(context_vector, axis=1)
      
      return context_vector, attention_weights

batch_size = 16
units = 32
input_length = 20
decoder_state = tf.random.uniform(shape=[batch_size, units])
encoder_output = tf.random.uniform(shape=[batch_size, input_length, units])
attention = Attention(units)
context_vector, attention_weights = attention(decoder_state, encoder_output)
我得到以下错误:

/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: Incompatible shapes: [16,20] vs. [16,20,32] [Op:Mul]
这是一个非常简单的修复方法,但由于我是新手,因此无法获得需要在此处调用的确切方法。 我尝试过重新调整编码器输出的值,但仍然不起作用。
请求帮助我解决这个问题。

我只是把@Ayush Srivastava的评论作为回应,以便帖子得到答案

基本上,发生错误是因为您试图将两个张量(即
注意\u权重
编码器\u输出
)与不同的形状相乘,因此需要重塑
解码器\u状态

以下是完整的答案:

class Attention(tf.keras.Model):
    def __init__(self,units):
        super().__init__()
        self.units = units

    def call(self, decoder_state, encoder_output):
        decoder_state = tf.keras.layers.Reshape((decoder_state.shape[1], 1))(decoder_state) 
        score = tf.keras.layers.dot([encoder_output, decoder_state],[2, 1]) 

        attention_weights = tf.nn.softmax(score, axis=1)

        context_vector = attention_weights * encoder_output
        context_vector = tf.reduce_sum(context_vector, axis=1)
        
        return context_vector, attention_weights
形状:

decoder_state before reshape: (16, 32)
decoder_state after reshape:  (16, 32, 1)
enc_output:                   (16, 20, 32)
score:                        (16, 20, 1)
attention_weights:            (16, 20, 1)
context_vector before sum:    (16, 20, 32)

我现在找到了解决方案。我丢失了对解码器状态的重塑。我添加了以下层解码器隐藏状态=tf.keras.layers.revorme((隐藏大小,1))(解码器隐藏状态)score=tf.keras.layers.dot([编码器输出,解码器隐藏状态],[2,1])