seq2seq(tf2.0版本)

import tensorflow as tf
'''
LSTM中,每一个细胞单元的state = (c_state,hidden_state),output就是最后一个词语细胞的state中的hidden_state

'''
embedding_units = 256
units = 1024
input_vocab_size = len(input_tokenizer.word_index) +1
output_vocab_size = len(output_tokenizer.word_index) +1

# encode
class Encoder(tf.keras.Model):
    def __init__(self,vocab_size,embedding_units,encoding_units,batch_size):
        super(Encoder,self).__init__()
        self.batch_size = batch_size
        self.encoding_units = encoding_units
        self.embedding = tf.keras.layers.Embedding(vocab_size,embedding_units)
        self.gru = tf.keras.layers.GRU(self.encoding_units,return_sequences=True,
                                       return_state=True,recurrent_initializer='glorot_uniform')

    def call(self,x,hidden):
        # 输入,获取embedding
        x = self.embedding(x)
        # gru
        output,state = self.gru(x,initial_state=hidden)
        return output,state
    def initialize_hidden_state(self):
        return tf.zeros([self.batch_size,self.encoding_units])


# attention机制
class BahdanauAttention(tf.keras.Model):
    def __init__(self,units):
        super(BahdanauAttention,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,decoder_hidden,encoder_outputs):
        # decoder_hidden.shape:[batch_size,units]
        # encoder_outputs.shape:[batch_size,length,units]
        decoder_hidden_with_time_axis = tf.expand_dims(decoder_hidden,1)
        # before V:(batch_size,length,units)
        # after V:(batch_size,length,1)
        score = self.V(tf.nn.tanh(self.W1(encoder_outputs) + self.W2(decoder_hidden_with_time_axis)))
        # shape:(batch_size,length,1)
        attention_weights = tf.nn.softmax(score,axis=1)
        # shape:(batch_size,length,units)
        context_vector = attention_weights * encoder_outputs
        # shape:(batch_size,units)
        context_vector = tf.reduce_sum(context_vector,axis=1)
        return context_vector,attention_weights

attention_model = BahdanauAttention(units=10)
attention_result,attention_weights = attention_model(sample_hidden,sample_output)
TensorFlow 2.x 中,tf.contrib.seq2seq.AttentionWrapper 已被弃用。相反,可以使用 tf.keras.layers.Attention 类来实现注意力机制。 下面是一个使用 tf.keras.layers.Attention 的示例: ```python import tensorflow as tf # 定义一个 Attention 层 attention = tf.keras.layers.Attention() # 输入序列的形状为 (batch_size, seq_len, embedding_dim) encoder_inputs = tf.keras.Input(shape=(None, embedding_dim)) decoder_inputs = tf.keras.Input(shape=(None, embedding_dim)) # 编码器 LSTM 层 encoder_lstm = tf.keras.layers.LSTM(units=hidden_size, return_sequences=True, return_state=True) encoder_outputs, state_h, state_c = encoder_lstm(encoder_inputs) # 解码器 LSTM 层 decoder_lstm = tf.keras.layers.LSTM(units=hidden_size, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=[state_h, state_c]) # 注意力机制 context_vector, attention_weights = attention([decoder_outputs, encoder_outputs]) # 输出层 output = tf.keras.layers.Dense(vocab_size, activation='softmax')(context_vector) # 定义模型 model = tf.keras.Model(inputs=[encoder_inputs, decoder_inputs], outputs=output) ``` 在上面的代码中,我们首先定义了一个 tf.keras.layers.Attention 层。然后,我们定义了编码器和解码器 LSTM 层,并使用它们分别对编码器输入和解码器输入进行编码。 接下来,我们使用注意力层对解码器输出和编码器输出进行注意力计算,得到上下文向量和注意力权重。 最后,我们使用一个全连接层对上下文向量进行预测,得到输出结果。 希望这个例子可以帮助你理解如何在 TensorFlow 2.x 中使用注意力机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值