Certainly! Here's an example code that uses a BiLSTM encoder and BiGRU decoder with an attention layer to translate English text to Arabic text. It includes the steps for tokenizing the sentences, converting them into numerical representations, padding or truncating the sentences to a fixed length, and using test data to evaluate and make an example prediction translation.
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Bidirectional, GRU, Dense, Concatenate, Attention, Embedding
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('train_data.txt', 'r', encoding='utf-8') as f:
train_data = f.read().splitlines()
with open('validate_data.txt', 'r', encoding='utf-8') as f:
validate_data = f.read().splitlines()
with open('test_data.txt', 'r', encoding='utf-8') as f:
test_data = f.read().splitlines()
# Tokenize sentences and convert them into numerical representations
tokenizer_en = Tokenizer()
tokenizer_en.fit_on_texts(train_data)
train_data_en = tokenizer_en.texts_to_sequences(train_data)
train_data_en = pad_sequences(train_data_en, maxlen=max_sequence_length)
tokenizer_ar = Tokenizer()
tokenizer_ar.fit_on_texts(train_data)
train_data_ar = tokenizer_ar.texts_to_sequences(train_data)
train_data_ar = pad_sequences(train_data_ar, maxlen=max_sequence_length)
# Define encoder inputs and BiLSTM layer
encoder_inputs = Input(shape=(max_sequence_length,))
encoder_embedding = Embedding(len(tokenizer_en.word_index) + 1, embedding_dim)(encoder_inputs)
encoder_lstm = Bidirectional(LSTM(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_ar.word_index) + 1, embedding_dim)(decoder_inputs)
decoder_gru = Bidirectional(GRU(latent_dim, return_sequences=True))(decoder_embedding)
# Apply Attention mechanism
attention = Dot(axes=[2, 2])([decoder_gru, encoder_lstm])
attention = Dense(max_sequence_length, activation='softmax')(attention)
context = Dot(axes=[2, 1])([attention, encoder_lstm])
decoder_combined_context = Concatenate(axis=-1)([context, decoder_gru])
# Define decoder output layer
decoder_dense = Dense(len(tokenizer_ar.word_index) + 1, activation='softmax')
decoder_outputs = decoder_dense(decoder_combined_context)
# Define the model
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
# Train the model
model.fit([train_data_en, train_data_ar], train_data_ar, batch_size=64, epochs=10, validation_split=0.2)
# Use test data to evaluate the model
test_data_en = tokenizer_en.texts_to_sequences(test_data)
test_data_en = pad_sequences(test_data_en, maxlen=max_sequence_length)
predicted_arabic = model.predict(test_data_en)
decoded_arabic = tokenizer_ar.sequences_to_texts(np.argmax(predicted_arabic, axis=-1))
# Print example prediction translation from test data
print("English sentence: ", test_data[0])
print("Predicted Arabic sentence: ", decoded_arabic[0])
Make sure to have the 'train_data.txt', 'validate_data.txt', and 'test_data.txt' files in the same directory as the Python script. Also, ensure you have the required dependencies installed, such as TensorFlow and numpy.