import numpy as np import keras from nltk.translate.bleu_score import corpus_bleu # Configuration batch_size = 64 epochs = 350 latent_dim = 256 num_samples = 50000 data_path = "fra.txt" # Preparing data input_texts = [] target_texts = [] input_characters = set() target_characters = set() with open(data_path, "r", encoding="utf-8") as f: lines = f.read().split("\n") for line in lines[: min(num_samples, len(lines) - 1)]: input_text, target_text, _ = line.split("\t") target_text = "\t" + target_text + "\n" input_texts.append(input_text) target_texts.append(target_text) for char in input_text: if char not in input_characters: input_characters.add(char) for char in target_text: if char not in target_characters: target_characters.add(char) input_characters = sorted(list(input_characters)) target_characters = sorted(list(target_characters)) num_encoder_tokens = len(input_characters) num_decoder_tokens = len(target_characters) max_encoder_seq_length = max([len(txt) for txt in input_texts]) max_decoder_seq_length = max([len(txt) for txt in target_texts]) print("Number of samples:", len(input_texts)) print("Number of unique input tokens:", num_encoder_tokens) print("Number of unique output tokens:", num_decoder_tokens) print("Max sequence length for inputs:", max_encoder_seq_length) print("Max sequence length for outputs:", max_decoder_seq_length) input_token_index = dict([(char, i) for i, char in enumerate(input_characters)]) target_token_index = dict([(char, i) for i, char in enumerate(target_characters)]) encoder_input_data = np.zeros( (len(input_texts), max_encoder_seq_length, num_encoder_tokens), dtype="float32", ) decoder_input_data = np.zeros( (len(input_texts), max_decoder_seq_length, num_decoder_tokens), dtype="float32", ) decoder_target_data = np.zeros( (len(input_texts), max_decoder_seq_length, num_decoder_tokens), dtype="float32", ) for i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)): for t, char in enumerate(input_text): encoder_input_data[i, t, input_token_index[char]] = 1.0 encoder_input_data[i, t + 1 :, input_token_index[" "]] = 1.0 for t, char in enumerate(target_text): decoder_input_data[i, t, target_token_index[char]] = 1.0 if t > 0: decoder_target_data[i, t - 1, target_token_index[char]] = 1.0 decoder_input_data[i, t + 1 :, target_token_index[" "]] = 1.0 decoder_target_data[i, t:, target_token_index[" "]] = 1.0 # Creating model encoder_inputs = keras.Input(shape=(None, num_encoder_tokens)) encoder = keras.layers.LSTM(latent_dim, return_state=True) encoder_outputs, state_h, state_c = encoder(encoder_inputs) encoder_states = [state_h, state_c] decoder_inputs = keras.Input(shape=(None, num_decoder_tokens)) decoder_lstm = keras.layers.LSTM(latent_dim, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states) decoder_dense = keras.layers.Dense(num_decoder_tokens, activation="softmax") decoder_outputs = decoder_dense(decoder_outputs) model = keras.Model([encoder_inputs, decoder_inputs], decoder_outputs) # Creating the training model model.compile( optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"] ) model.fit( [encoder_input_data, decoder_input_data], decoder_target_data, batch_size=batch_size, epochs=epochs, validation_split=0.2, ) model.save("s2s_model.keras") # Sampling model = keras.models.load_model("s2s_model.keras") encoder_inputs = model.input[0] encoder_outputs, state_h_enc, state_c_enc = model.layers[2].output encoder_states = [state_h_enc, state_c_enc] encoder_model = keras.Model(encoder_inputs, encoder_states) decoder_inputs = model.input[1] decoder_state_input_h = keras.Input(shape=(latent_dim,)) decoder_state_input_c = keras.Input(shape=(latent_dim,)) decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c] decoder_lstm = model.layers[3] decoder_outputs, state_h_dec, state_c_dec = decoder_lstm( decoder_inputs, initial_state=decoder_states_inputs ) decoder_states = [state_h_dec, state_c_dec] decoder_dense = model.layers[4] decoder_outputs = decoder_dense(decoder_outputs) decoder_model = keras.Model( [decoder_inputs] + decoder_states_inputs, [decoder_outputs] + decoder_states ) reverse_input_char_index = dict((i, char) for char, i in input_token_index.items()) reverse_target_char_index = dict((i, char) for char, i in target_token_index.items()) def decode_sequences(input_seqs): states_values = encoder_model.predict(input_seqs, verbose=0) target_seqs = np.zeros((len(input_seqs), 1, num_decoder_tokens)) target_seqs[:, 0, target_token_index["\t"]] = 1.0 decoded_sentences = [""] * len(input_seqs) stop_conditions = np.zeros(len(input_seqs), dtype=bool) while not np.all(stop_conditions): output_tokens, h, c = decoder_model.predict( [target_seqs] + states_values, verbose=0 ) sampled_token_indices = np.argmax(output_tokens[:, -1, :], axis=1) sampled_chars = [ reverse_target_char_index[idx] for idx in sampled_token_indices ] for i, char in enumerate(sampled_chars): decoded_sentences[i] += char if char == "\n" or len(decoded_sentences[i]) > max_decoder_seq_length: stop_conditions[i] = True target_seqs = np.zeros((len(input_seqs), 1, num_decoder_tokens)) for i, token_index in enumerate(sampled_token_indices): target_seqs[i, 0, token_index] = 1.0 states_values = [h, c] return decoded_sentences # BLEU score evaluation def calculate_bleu_score(input_texts, target_texts, num_samples=500): input_seqs = np.zeros( (num_samples, max_encoder_seq_length, num_encoder_tokens), dtype="float32" ) for i, input_text in enumerate(input_texts[:num_samples]): for t, char in enumerate(input_text): input_seqs[i, t, input_token_index[char]] = 1.0 input_seqs[i, t + 1 :, input_token_index[" "]] = 1.0 decoded_sentences = decode_sequences(input_seqs) references = [[list(text.strip())] for text in target_texts[:num_samples]] hypotheses = [list(text.strip()) for text in decoded_sentences] bleu = corpus_bleu(references, hypotheses) print("BLEU Score:", bleu) print("\nExample Translations:") for i in range(10): print("Input:", input_texts[i]) print("Target:", target_texts[i]) print("Translation:", decoded_sentences[i]) print() calculate_bleu_score(input_texts, target_texts)