Certainly! Here's an example Python code that uses a BiLSTM encoder and BiGRU decoder RNN to translate English text to Arabic text using training, validation, and test data from text files. It also includes tokenization of sentences, conversion to numerical representations, padding or truncating sentences to a fixed length, and evaluation of the model using the test data.
import numpy as np
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Bidirectional, GRU, RepeatVector, concatenate
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.preprocessing.text import Tokenizer
def preprocess_data(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
data = file.read()
sentences = data.split('\n')
sentences = [sentence.lower() for sentence in sentences]
return sentences
# Preprocess the training, validation, and test data
train_data = preprocess_data('train_data.txt')
validate_data = preprocess_data('validate_data.txt')
test_data = preprocess_data('test_data.txt')
# Tokenize sentences and convert them into numerical representations
tokenizer_train = Tokenizer()
tokenizer_train.fit_on_texts(train_data)
train_sequences = tokenizer_train.texts_to_sequences(train_data)
vocab_size_train = len(tokenizer_train.word_index) + 1
tokenizer_validate = Tokenizer()
tokenizer_validate.fit_on_texts(validate_data)
validate_sequences = tokenizer_validate.texts_to_sequences(validate_data)
vocab_size_validate = len(tokenizer_validate.word_index) + 1
tokenizer_test = Tokenizer()
tokenizer_test.fit_on_texts(test_data)
test_sequences = tokenizer_test.texts_to_sequences(test_data)
# Pad or truncate sentences to a fixed length
max_sequence_length = 100
train_data_padded = pad_sequences(train_sequences, maxlen=max_sequence_length, padding='post', truncating='post')
validate_data_padded = pad_sequences(validate_sequences, maxlen=max_sequence_length, padding='post', truncating='post')
test_data_padded = pad_sequences(test_sequences, maxlen=max_sequence_length, padding='post', truncating='post')
# Define the model architecture
encoder_inputs = Input(shape=(max_sequence_length,))
encoder = Bidirectional(LSTM(64, return_sequences=False))(encoder_inputs)
decoder_inputs = Input(shape=(max_sequence_length,))
decoder = Bidirectional(GRU(64, return_sequences=True))(decoder_inputs)
decoder_outputs = GRU(vocab_size_validate, return_sequences=True)(decoder)
output = concatenate([encoder, decoder_outputs])
output = LSTM(64, return_sequences=True)(output)
output = LSTM(vocab_size_validate, return_sequences=True)(output)
model = Model([encoder_inputs, decoder_inputs], output)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
# Training the model
early_stopping = EarlyStopping(monitor='val_loss', patience=10)
model.fit([train_data_padded, train_data_padded], np.expand_dims(validate_data_padded, -1),
epochs=100, batch_size=32, validation_split=0.2, callbacks=[early_stopping])
# Evaluation on test data
test_data_padded_encoded = tokenizer_train.texts_to_sequences(test_data_padded)
test_data_padded_encoded = pad_sequences(test_data_padded_encoded, maxlen=max_sequence_length, padding='post')
predictions = np.argmax(model.predict([test_data_padded_encoded, test_data_padded_encoded]), axis=-1)
# Convert numerical representations back to sentences
predicted_sentences = tokenizer_validate.sequences_to_texts(predictions)
for i in range(len(test_data)):
print('English:', test_data[i])
print('Arabic:', predicted_sentences[i])
print()
# Evaluate the model on test data
accuracy = model.evaluate([test_data_padded_encoded, test_data_padded_encoded], np.expand_dims(test_data_padded, -1))
print('Accuracy:', accuracy)
Make sure to replace 'train_data.txt', 'validate_data.txt', and 'test_data.txt' with the actual file paths containing your corresponding data.
Additionally, please ensure you have installed the required libraries such as TensorFlow and Keras.