Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何利用keras建立注意力模型?_Python_Tensorflow_Keras_Deep Learning_Attention Model - Fatal编程技术网

Python 如何利用keras建立注意力模型?

Python 如何利用keras建立注意力模型?,python,tensorflow,keras,deep-learning,attention-model,Python,Tensorflow,Keras,Deep Learning,Attention Model,我试图理解注意力模型,并且自己建立一个。经过多次搜索,我发现了一个用keras编码的Attention模型,而且看起来很简单。但当我试图在我的机器上构建相同的模型时,它给出了多参数错误。该错误是由于传入类注意的参数不匹配造成的。在网站的注意力课程中,它要求一个论点,但它用两个论点启动注意力对象 import tensorflow as tf max_len = 200 rnn_cell_size = 128 vocab_size=250 class Attention(tf.keras.Mo

我试图理解注意力模型,并且自己建立一个。经过多次搜索,我发现了一个用keras编码的Attention模型,而且看起来很简单。但当我试图在我的机器上构建相同的模型时,它给出了多参数错误。该错误是由于传入类
注意
的参数不匹配造成的。在网站的注意力课程中,它要求一个论点,但它用两个论点启动注意力对象

import tensorflow as tf

max_len = 200
rnn_cell_size = 128
vocab_size=250

class Attention(tf.keras.Model):
    def __init__(self, units):
        super(Attention, self).__init__()
        self.W1 = tf.keras.layers.Dense(units)
        self.W2 = tf.keras.layers.Dense(units)
        self.V = tf.keras.layers.Dense(1)
    def call(self, features, hidden):
        hidden_with_time_axis = tf.expand_dims(hidden, 1)
        score = tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis))
        attention_weights = tf.nn.softmax(self.V(score), axis=1)
        context_vector = attention_weights * features
        context_vector = tf.reduce_sum(context_vector, axis=1)
        return context_vector, attention_weights

sequence_input = tf.keras.layers.Input(shape=(max_len,), dtype='int32')

embedded_sequences = tf.keras.layers.Embedding(vocab_size, 128, input_length=max_len)(sequence_input)

lstm = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM
                                     (rnn_cell_size,
                                      dropout=0.3,
                                      return_sequences=True,
                                      return_state=True,
                                      recurrent_activation='relu',
                                      recurrent_initializer='glorot_uniform'), name="bi_lstm_0")(embedded_sequences)

lstm, forward_h, forward_c, backward_h, backward_c = tf.keras.layers.Bidirectional \
    (tf.keras.layers.LSTM
     (rnn_cell_size,
      dropout=0.2,
      return_sequences=True,
      return_state=True,
      recurrent_activation='relu',
      recurrent_initializer='glorot_uniform'))(lstm)

state_h = tf.keras.layers.Concatenate()([forward_h, backward_h])
state_c = tf.keras.layers.Concatenate()([forward_c, backward_c])

#  PROBLEM IN THIS LINE
context_vector, attention_weights = Attention(lstm, state_h)

output = keras.layers.Dense(1, activation='sigmoid')(context_vector)

model = keras.Model(inputs=sequence_input, outputs=output)

# summarize layers
print(model.summary())

如何使此模型工作?

初始化注意力层和传递参数的方式有问题。您应该在此处指定
注意层
单元的数量,并修改传入参数的方式:

context_vector, attention_weights = Attention(32)(lstm, state_h)
结果是:

__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_1 (InputLayer)            (None, 200)          0                                            
__________________________________________________________________________________________________
embedding (Embedding)           (None, 200, 128)     32000       input_1[0][0]                    
__________________________________________________________________________________________________
bi_lstm_0 (Bidirectional)       [(None, 200, 256), ( 263168      embedding[0][0]                  
__________________________________________________________________________________________________
bidirectional (Bidirectional)   [(None, 200, 256), ( 394240      bi_lstm_0[0][0]                  
                                                                 bi_lstm_0[0][1]                  
                                                                 bi_lstm_0[0][2]                  
                                                                 bi_lstm_0[0][3]                  
                                                                 bi_lstm_0[0][4]                  
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 256)          0           bidirectional[0][1]              
                                                                 bidirectional[0][3]              
__________________________________________________________________________________________________
attention (Attention)           [(None, 256), (None, 16481       bidirectional[0][0]              
                                                                 concatenate[0][0]                
__________________________________________________________________________________________________
dense_3 (Dense)                 (None, 1)            257         attention[0][0]                  
==================================================================================================
Total params: 706,146
Trainable params: 706,146
Non-trainable params: 0
__________________________________________________________________________________________________
None

注意层现在是Tensorflow(2.1)的Keras API的一部分。但它输出的张量与“查询”张量大小相同

以下是如何使用梁式注意事项:

query_attention = tf.keras.layers.Attention()([query, value])
和Bahdanau风格的注意:

query_attention = tf.keras.layers.AdditiveAttention()([query, value])
经改编的版本:

attention\u weights=tf.keras.layers.attention()([lstm,state\u h])

有关更多信息,请访问原始网站:

回答Arman的特定查询-这些库使用2018年后查询、值和键的语义。若要将语义映射回Bahdanau或Luong的论文,可以考虑“查询”是最后一个解码器隐藏状态。“值”将是编码器输出的集合-编码器的所有隐藏状态。“查询”涉及所有“值”

无论您使用的是哪种版本的代码或库,请务必注意,“查询”将在时间轴上展开,以便为后续添加做好准备。此值(正在扩展)将始终是RNN的最后一个隐藏状态。另一个值将始终是需要关注的值-编码器端的所有隐藏状态。这个简单的代码检查可以确定“查询”和“值”映射到什么,而不考虑您正在使用的库或代码


您可以参考以不到6行代码编写您自己的自定义注意层

您能否根据此特定OP的问题澄清“查询”和“值”?OP希望将“lstm”和“state_h”传递给注意层。那么
query
value
应该是什么?有什么例子吗?@Yahya它们需要是时间序列数据格式[批次、时间、特征]中的TensorFlow张量。我希望这就是你想要的。这里有一个简单的方法来增加注意力: