Spaces:
Runtime error
Runtime error
Create train_eng_fra.py
Browse files- train_eng_fra.py +125 -0
train_eng_fra.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tensorflow as tf
|
| 2 |
+
import io
|
| 3 |
+
import os
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# 1. Download dataset (eng–fra)
|
| 7 |
+
path_to_zip = tf.keras.utils.get_file(
|
| 8 |
+
fname="fra-eng.zip",
|
| 9 |
+
origin="http://storage.googleapis.com/download.tensorflow.org/data/fra-eng.zip",
|
| 10 |
+
extract=True,
|
| 11 |
+
)
|
| 12 |
+
path_to_file = os.path.join(os.path.dirname(path_to_zip), "fra.txt")
|
| 13 |
+
|
| 14 |
+
# 2. Load sentence pairs
|
| 15 |
+
with io.open(path_to_file, encoding="UTF-8") as f:
|
| 16 |
+
lines = f.read().strip().split("\n")
|
| 17 |
+
|
| 18 |
+
pairs = [l.split("\t")[:2] for l in lines] # [eng, fra]
|
| 19 |
+
eng_texts = [p[0] for p in pairs]
|
| 20 |
+
fra_texts = [p[1] for p in pairs]
|
| 21 |
+
|
| 22 |
+
# Add special tokens to target (French)
|
| 23 |
+
start_token = "<sos>"
|
| 24 |
+
end_token = "<eos>"
|
| 25 |
+
fra_texts_in = [start_token + " " + t for t in fra_texts]
|
| 26 |
+
fra_texts_out = [t + " " + end_token for t in fra_texts]
|
| 27 |
+
|
| 28 |
+
# 3. Build tokenizers
|
| 29 |
+
num_words_src = 10000
|
| 30 |
+
num_words_tgt = 10000
|
| 31 |
+
|
| 32 |
+
src_tokenizer = tf.keras.preprocessing.text.Tokenizer(
|
| 33 |
+
num_words=num_words_src, filters="", lower=True, oov_token="<unk>"
|
| 34 |
+
)
|
| 35 |
+
tgt_tokenizer = tf.keras.preprocessing.text.Tokenizer(
|
| 36 |
+
num_words=num_words_tgt, filters="", lower=True, oov_token="<unk>"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
src_tokenizer.fit_on_texts(eng_texts)
|
| 40 |
+
tgt_tokenizer.fit_on_texts(fra_texts_in + fra_texts_out)
|
| 41 |
+
|
| 42 |
+
src_sequences = src_tokenizer.texts_to_sequences(eng_texts)
|
| 43 |
+
tgt_sequences_in = tgt_tokenizer.texts_to_sequences(fra_texts_in)
|
| 44 |
+
tgt_sequences_out = tgt_tokenizer.texts_to_sequences(fra_texts_out)
|
| 45 |
+
|
| 46 |
+
# 4. Pad sequences
|
| 47 |
+
max_len_src = max(len(s) for s in src_sequences)
|
| 48 |
+
max_len_tgt = max(len(s) for s in tgt_sequences_in)
|
| 49 |
+
|
| 50 |
+
src_input = tf.keras.preprocessing.sequence.pad_sequences(
|
| 51 |
+
src_sequences, maxlen=max_len_src, padding="post"
|
| 52 |
+
)
|
| 53 |
+
tgt_input = tf.keras.preprocessing.sequence.pad_sequences(
|
| 54 |
+
tgt_sequences_in, maxlen=max_len_tgt, padding="post"
|
| 55 |
+
)
|
| 56 |
+
tgt_output = tf.keras.preprocessing.sequence.pad_sequences(
|
| 57 |
+
tgt_sequences_out, maxlen=max_len_tgt, padding="post"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# 5. Define encoder–decoder model (from scratch)
|
| 61 |
+
embed_dim = 256
|
| 62 |
+
enc_units = 256
|
| 63 |
+
dec_units = 256
|
| 64 |
+
src_vocab_size = min(num_words_src, len(src_tokenizer.word_index) + 1)
|
| 65 |
+
tgt_vocab_size = min(num_words_tgt, len(tgt_tokenizer.word_index) + 1)
|
| 66 |
+
|
| 67 |
+
# Encoder
|
| 68 |
+
encoder_inputs = tf.keras.Input(shape=(None,), name="encoder_inputs")
|
| 69 |
+
enc_emb = tf.keras.layers.Embedding(src_vocab_size, embed_dim)(encoder_inputs)
|
| 70 |
+
encoder_lstm = tf.keras.layers.LSTM(
|
| 71 |
+
enc_units, return_state=True, return_sequences=False
|
| 72 |
+
)
|
| 73 |
+
_, state_h, state_c = encoder_lstm(enc_emb)
|
| 74 |
+
encoder_states = [state_h, state_c]
|
| 75 |
+
|
| 76 |
+
# Decoder
|
| 77 |
+
decoder_inputs = tf.keras.Input(shape=(None,), name="decoder_inputs")
|
| 78 |
+
dec_emb_layer = tf.keras.layers.Embedding(tgt_vocab_size, embed_dim)
|
| 79 |
+
dec_emb = dec_emb_layer(decoder_inputs)
|
| 80 |
+
decoder_lstm = tf.keras.layers.LSTM(
|
| 81 |
+
dec_units, return_sequences=True, return_state=True
|
| 82 |
+
)
|
| 83 |
+
decoder_outputs, _, _ = decoder_lstm(dec_emb, initial_state=encoder_states)
|
| 84 |
+
decoder_dense = tf.keras.layers.Dense(tgt_vocab_size, activation="softmax")
|
| 85 |
+
decoder_outputs = decoder_dense(decoder_outputs)
|
| 86 |
+
|
| 87 |
+
model = tf.keras.Model([encoder_inputs, decoder_inputs], decoder_outputs)
|
| 88 |
+
model.compile(
|
| 89 |
+
optimizer="adam",
|
| 90 |
+
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
|
| 91 |
+
metrics=["accuracy"],
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# 6. Train model
|
| 95 |
+
batch_size = 64
|
| 96 |
+
epochs = 10
|
| 97 |
+
|
| 98 |
+
model.fit(
|
| 99 |
+
[src_input, tgt_input],
|
| 100 |
+
np.expand_dims(tgt_output, -1),
|
| 101 |
+
batch_size=batch_size,
|
| 102 |
+
epochs=epochs,
|
| 103 |
+
validation_split=0.1,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# 7. Save everything
|
| 107 |
+
os.makedirs("artifacts", exist_ok=True)
|
| 108 |
+
model.save("artifacts/eng_fra_seq2seq.h5")
|
| 109 |
+
|
| 110 |
+
# Save tokenizers and metadata
|
| 111 |
+
import pickle
|
| 112 |
+
|
| 113 |
+
with open("artifacts/src_tokenizer.pkl", "wb") as f:
|
| 114 |
+
pickle.dump(src_tokenizer, f)
|
| 115 |
+
with open("artifacts/tgt_tokenizer.pkl", "wb") as f:
|
| 116 |
+
pickle.dump(tgt_tokenizer, f)
|
| 117 |
+
|
| 118 |
+
meta = {
|
| 119 |
+
"max_len_src": max_len_src,
|
| 120 |
+
"max_len_tgt": max_len_tgt,
|
| 121 |
+
"start_token": start_token,
|
| 122 |
+
"end_token": end_token,
|
| 123 |
+
}
|
| 124 |
+
with open("artifacts/meta.pkl", "wb") as f:
|
| 125 |
+
pickle.dump(meta, f)
|