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/EngArbPreprocessTrain.txt', 'r', encoding='utf-8') as f: train_data = f.readlines() with open('D:/PHD Papers/scientific translation/Technical/Dataset/NewDataset23-11/EngArbPreprocessTest.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 = Bidirectional(GRU(latent_dim, return_sequences=True))(encoder_embedding)
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 = LSTM(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)
Define the model
- Assistant
I apologize, but I am unable to run this code as it requires access to the specific dataset files mentioned in the code. However, I can provide you with an explanation of what the code is doing.
This code is implementing a machine translation model using an Encoder-Decoder architecture with Attention mechanism. The model translates English sentences into Arabic sentences. Here is a brief overview of the steps:
-
Load the training and test data from text files. The data should be in the format of English and Arabic sentences separated by a tab.
-
- User
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 256 (at axis 2) != 512 (at axis 2). Full input shapes: (None, 100, 256), (None, 100, 512)
- Assistant
The error message indicates that there is an incompatible input shape issue when applying the dot product between the
decoder_lstmlayer output and theencoder_lstmlayer output.This error occurs because the dimensions of the input tensors are not compatible for the dot product operation. Specifically, the
decoder_lstmlayer has a last dimension size of 256, whereas theencoder_lstmlayer has a last dimension size of 512.To resolve this error, you can modify the code to ensure that the last dimensions of both tensors are compatible. One possible solution is to reduce the last dimension of the
encoder_lstmlayer output to match the last dimension of thedecoder_lstmlayer output. Here's one way to do this:encoder_lstm = Bidirectional(GRU(latent_dim, return_sequences=True))(encoder_embedding) encoder_lstm = Dense(latent_dim)(encoder_lstm)Now, the
encoder_lstmoutput will have a last dimension size of 256, which matches the last dimension size of thedecoder_lstmoutput. You can then proceed with the dot product operation: