Certainly! In this example, we'll use an LSTM encoder and BiLSTM decoder to translate English text to Arabic text using Python and Keras. We'll follow the steps of splitting the data from a file into train, validation, and test sets, tokenizing the sentences, converting them into numerical representations, padding or truncating the sentences to a fixed length, evaluating the translation using test data, and translating some examples from the test set.
import numpy as np
from keras.models import Model
from keras.layers import Input, Embedding, LSTM, Bidirectional, Dense
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
# Read data from file
with open('english_arabic.txt', 'r', encoding='utf-8') as file:
lines = file.read().split('\n')
# Split data into train, validation, and test sets
train_data = lines[:8000]
val_data = lines[8000:9000]
test_data = lines[9000:]
# Tokenize the sentences
tokenizer_en = Tokenizer()
tokenizer_ar = Tokenizer()
tokenizer_en.fit_on_texts(train_data)
tokenizer_ar.fit_on_texts(train_data)
vocab_size_en = len(tokenizer_en.word_index) + 1
vocab_size_ar = len(tokenizer_ar.word_index) + 1
train_data_en = tokenizer_en.texts_to_sequences(train_data)
train_data_ar = tokenizer_ar.texts_to_sequences(train_data)
val_data_en = tokenizer_en.texts_to_sequences(val_data)
val_data_ar = tokenizer_ar.texts_to_sequences(val_data)
test_data_en = tokenizer_en.texts_to_sequences(test_data)
test_data_ar = tokenizer_ar.texts_to_sequences(test_data)
# Pad or truncate the sentences to a fixed length
max_sentence_length = 20
train_data_en = pad_sequences(train_data_en, maxlen=max_sentence_length, padding='post')
train_data_ar = pad_sequences(train_data_ar, maxlen=max_sentence_length, padding='post')
val_data_en = pad_sequences(val_data_en, maxlen=max_sentence_length, padding='post')
val_data_ar = pad_sequences(val_data_ar, maxlen=max_sentence_length, padding='post')
test_data_en = pad_sequences(test_data_en, maxlen=max_sentence_length, padding='post')
test_data_ar = pad_sequences(test_data_ar, maxlen=max_sentence_length, padding='post')
# Define the model architecture
en_input = Input(shape=(max_sentence_length,))
embedding_en = Embedding(vocab_size_en, 100)(en_input)
encoder_lstm = LSTM(128)(embedding_en)
ar_input = Input(shape=(max_sentence_length,))
embedding_ar = Embedding(vocab_size_ar, 100)(ar_input)
decoder_bilstm = Bidirectional(LSTM(128, return_sequences=True))(embedding_ar)
attention = keras.layers.Attention()([decoder_bilstm, encoder_lstm])
context = tf.keras.layers.Concatenate()([attention, decoder_bilstm])
output = Dense(vocab_size_ar, activation='softmax')(context)
model = Model(inputs=[en_input, ar_input], outputs=output)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit([train_data_en, train_data_ar[:, :-1]], train_data_ar[:, 1:], epochs=10, batch_size=32, validation_data=([val_data_en, val_data_ar[:, :-1]], val_data_ar[:, 1:]))
# Evaluate the model on test data
test_loss, test_accuracy = model.evaluate([test_data_en, test_data_ar[:, :-1]], test_data_ar[:, 1:], verbose=0)
print(f"Test Loss: {test_loss}")
print(f"Test Accuracy: {test_accuracy}")
# Perform translation using test data examples
predicted_ar = model.predict([test_data_en, test_data_ar[:, :-1]])
for i in range(len(test_data_en)):
en_sentence = ' '.join([tokenizer_en.index_word[idx] for idx in test_data_en[i] if idx != 0])
ar_sentence = ' '.join([tokenizer_ar.index_word[idx] for idx in np.argmax(predicted_ar[i], axis=1) if idx != 0])
print(f"English sentence: {en_sentence}")
print(f"Translated Arabic sentence (predicted): {ar_sentence}")
print("---")
Make sure to replace 'english_arabic.txt' with the path to your dataset file containing English and Arabic sentences. Feel free to adjust the model architecture and hyperparameters according to your needs.