import numpy as np import tensorflow as tf from tensorflow.keras.models import Model…
- User
import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Bidirectional, GRU, Concatenate, Dot, Attention, Dense,Embedding,Activation from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences
Define hyperparameters
max_sequence_length = 100 embedding_dim = 100 latent_dim = 256
Load train, validate, and test data from text files
with open('D:/PHD Papers/scientific translation/Technical/Dataset/NewDataset23-11/Train.txt', 'r', encoding='utf-8') as f: train_data = f.readlines() with open('D:/PHD Papers/scientific translation/Technical/Dataset/NewDataset23-11/Test.txt', 'r', encoding='utf-8') as f: test_data = f.readlines()
Extract English and Arabic sentences from data
english_sentences_train = [] arabic_sentences_train = []
english_test = [] arabic_test = []
for line in train_data: english, arabic = line.strip().split('\t') english_sentences_train.append(english) arabic_sentences_train.append(arabic)
for line in test_data: english, arabic = line.strip().split('\t') english_test.append(english) arabic_test.append(arabic)
Tokenize sentences and convert them into numerical representations
tokenizer_en = Tokenizer() tokenizer_en.fit_on_texts(english_sentences_train) train_data_en = tokenizer_en.texts_to_sequences(english_sentences_train) train_data_en = pad_sequences(train_data_en, maxlen=max_sequence_length, padding='post', truncating='post') tokenizer_ar = Tokenizer() tokenizer_ar.fit_on_texts(arabic_sentences_train) train_data_ar = tokenizer_ar.texts_to_sequences(arabic_sentences_train) train_data_ar = pad_sequences(train_data_ar, maxlen=max_sequence_length, padding='post', truncating='post')
Define encoder inputs and BiLSTM layer
encoder_inputs = Input(shape=(max_sequence_length,)) encoder_embedding = Embedding(len(tokenizer_ar.word_index) + 1, embedding_dim)(encoder_inputs) encoder_lstm = GRU(latent_dim, return_sequences=True)(encoder_embedding) encoder_lstm = Dense(latent_dim)(encoder_lstm)
Define decoder inputs and BiGRU layer
decoder_inputs = Input(shape=(max_sequence_length,)) decoder_embedding = Embedding(len(tokenizer_en.word_index) + 1, embedding_dim)(decoder_inputs) decoder_lstm = GRU(latent_dim, return_sequences=True)(decoder_embedding)
Apply Attention mechanism
attention = Dot(axes=[2, 2])([decoder_lstm, encoder_lstm]) attention = Activation('softmax')(attention) context = Dot(axes=[2, 1])([attention, encoder_lstm]) decoder_combined_context = Concatenate(axis=-1)([context, decoder_lstm])
Define decoder output layer
decoder_dense = Dense(len(tokenizer_en.word_index) + 1, activation='softmax') decoder_outputs = decoder_dense(decoder_combined_context)
- Assistant
The code provided is an implementation of a Neural Machine Translation (NMT) model using an Attention mechanism. The model is trained to translate English sentences to Arabic sentences.
Here are the main steps of the code:
- Load the train and test data from text files.
- Preprocess the data by tokenizing the sentences and converting them into numerical representations using the Tokenizer and pad_sequences functions from the Keras library.
- Define the encoder and decoder network architecture using the Keras functional API. The encoder network consists of an input layer, an embedding layer, and a BiLSTM layer. The decoder network consists of an input layer and a BiGRU layer.
- Apply the Attention mechanism to compute attention weights between the encoder and decoder hidden states.
- Concatenate the computed context vector with the decoder hidden states and pass it through a dense layer to obtain the decoder outputs.
- Compile the model with the Adam optimizer and sparse categorical cross-entropy loss.
- User
make decoder Bi-GRU
- Assistant
To modify the decoder to use a Bidirectional GRU (Bi-GRU) layer instead of a regular GRU layer, you can replace the line
decoder_lstm = GRU(latent_dim, return_sequences=True)(decoder_embedding)with the following code:pythondecoder_bigrus = Bidirectional(GRU(latent_dim, return_sequences=True))(decoder_embedding) decoder_lstm = Concatenate(axis=-1)(decoder_bigrus)This code adds a Bidirectional layer around the GRU layer in the decoder, and then concatenates the outputs of both directions. This allows the decoder to consider the information from both past and future timesteps when generating the output sequence.
After making this change, you can compile and train the model as before.
- User
Traceback (most recent call last): File "D:\PHD Papers\scientific translation\GPT\BiLSTM witth Attention\GRU attention Bi.py", line 56, in decoder_lstm = Concatenate(axis=-1)(decoder_bigrus) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\layers\merging\concatenate.py", line 99, in build "A
Concatenatelayer should be called on a list of " ValueError: AConcatenatelayer should be called on a list of at least 1 input. Received: input_shape=(None, 100, 512) - Assistant
I apologize for the error. It seems that the input shape of the decoder Bi-GRU layer is not compatible with the Concatenate layer. To resolve this issue, we need to reshape the output of the Bi-GRU layer before passing it to the Concatenate layer.
Here's the modified code for the decoder section:
python# Apply Bidirectional GRU to the decoder embedding decoder_bigrus = Bidirectional(GRU(latent_dim, return_sequences=True))(decoder_embedding) # Reshape the output of the Bi-GRU layer for concatenation decoder_bigrus_reshaped = tf.reshape(decoder_bigrus, (-1, max_sequence_length, 2*latent_dim)) # Concatenate the outputs of both directions decoder_lstm = Concatenate(axis=-1)([decoder_bigrus_reshaped, decoder_embedding])After making these changes, you can compile and train the model as before. Let me know if you encounter any further issues.
- User
Traceback (most recent call last): File "D:\PHD Papers\scientific translation\GPT\BiLSTM witth Attention\GRU attention Bi.py", line 61, in attention = Dot(axes=[2, 2])([decoder_lstm, encoder_lstm]) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\layers\merging\dot.py", line 137, in build "Incompatible input shapes: " ValueError: Incompatible input shapes: axis values 612 (at axis 2) != 256 (at axis 2). Full input shapes: (None, 100, 612), (None, 100, 256)
- Assistant
Apologies for the confusion. The dimension mismatch error occurs because the dimensions of the encoder LSTM and decoder Bi-GRU layers do not match. To resolve this, we need to adjust the dimensions to allow for proper dot-product for attention mechanism.
Here's the modified code for the attention section:
python# Adjust the dimensions of encoder LSTM and decoder Bi-GRU layers hidden_units_encoder = 2 * latent_dim hidden_units_decoder = 2 * latent_dim # Apply Attention mechanism attention = Dot(axes=[2, 2])([decoder_lstm, encoder_lstm]) attention = Activation('softmax')(attention) context = Dot(axes=[2, 1])([attention, encoder_lstm]) context = tf.reshape(context, (-1, max_sequence_length, hidden_units_encoder)) # Concatenate the computed context vector with the decoder Bi-GRU outputs decoder_combined_context = Concatenate(axis=-1)([context, decoder_lstm])