← All posts

Neural Machine Translation with RNNs in Keras

Recurrent neural network for translation

Tagging words with counts was one thing. Translation is a much harder sequence problem: read a whole sentence in one language, write it in another, where word order changes and the lengths don’t match.

For an individual project I built an English → French translator with recurrent neural networks in Keras and compared five architectures on the same data. The numbers taught me more than the architecture diagrams did. Code is on GitHub.

A short history of machine translation

Before building anything, the project started by looking at how machine translation evolved:

Era Approach Idea Weakness
1950s–80s Rule-based Linguists write grammar rules and dictionaries by hand Doesn’t scale; every exception needs a new rule
1990s–2014 Statistical Learn phrase translation probabilities from parallel texts Translates phrase by phrase, clumsy word order
— Example-based Translate by analogy with stored sentence pairs Limited to what was seen before
2014+ Neural One network reads the whole sentence and writes the whole translation Needs a lot of data

The data and preprocessing

The dataset has 137,860 English–French sentence pairs with a small vocabulary, for example:

new jersey is sometimes quiet during autumn , and it is snowy in april .
new jersey est parfois calme pendant l' automne , et il est neigeux en avril .

Data first. Neural networks work with numbers, not words, so every pipeline needs the same three steps — turn words into ids, make all sentences the same length, and reshape the labels:

from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences

def tokenize(sentences):
    tk = Tokenizer()
    tk.fit_on_texts(sentences)                    # word -> integer id
    return tk.texts_to_sequences(sentences), tk

def pad(seqs, length=None):
    return pad_sequences(seqs, maxlen=length, padding="post")   # zeros at the end

x, x_tk = tokenize(english);  x = pad(x)
y, y_tk = tokenize(french);   y = pad(y)
y = y.reshape(*y.shape, 1)    # sparse_categorical_crossentropy needs this extra dimension

The five models

Then the models, one by one — each adds a single idea to the previous one:

1 Simple RNN 2 Embedding 3 Bidirectional 4 Enc-Dec 5 Final GRU (seq) Dense softmax Embedding GRU (seq) Dense softmax Bi-GRU (seq) Dense softmax GRU encoder Dense 512 RepeatVector GRU decoder Dense softmax Embedding Bi-GRU encoder Dense 512 RepeatVector Bi-GRU decoder Dense softmax All outputs: TimeDistributed Dense over the French vocabulary, one prediction per output position.

1. Simple RNN — a GRU layer reads the word ids and a dense softmax layer predicts a French word at every position. This is the baseline, shown in the picture at the top of the article.

2. Embedding — instead of raw ids, every word becomes a learned vector, so similar words get similar representations:

Embedding layer

3. Bidirectional RNN — the sentence is read in both directions, so every position sees the words before and after it:

Bidirectional RNN

4. Encoder-decoder — the encoder compresses the whole sentence into one vector, and the decoder generates the translation from it. This removes the requirement that input and output have the same length.

5. Final model — all of the above together. This is the Keras code:

def model_final(input_shape, output_len, en_vocab, fr_vocab):
    inputs = Input(shape=input_shape[1:])
    x = Embedding(input_dim=en_vocab, output_dim=output_len)(inputs)
    x = Bidirectional(GRU(output_len))(x)                      # encoder -> one sentence vector
    x = Dense(512, activation="relu")(x)
    x = RepeatVector(output_len)(x)                            # give that vector to every output step
    x = Bidirectional(GRU(512, return_sequences=True))(x)      # decoder
    outputs = TimeDistributed(Dense(fr_vocab, activation="softmax"))(x)

    model = Model(inputs, outputs)
    model.compile(loss="sparse_categorical_crossentropy",
                  optimizer=Adam(1e-3), metrics=["accuracy"])
    return model

The results

These are the real validation accuracies from my notebook:

Simple RNN (20 ep) 81.9% Embedding (15 ep) 91.7% Bidirectional (10 ep) 68.7% Encoder-decoder (15 ep) 63.8% Final (10 ep) 77.3% Final (20 ep) 88.9% validation accuracy, same data, epochs as trained

The winner was not the most advanced model. Simply adding an embedding layer took the plain GRU from 81.9% to 91.7% — better than every more complex architecture with the training each one got. The final model was still improving at 20 epochs (77.3% → 88.9%), so with more training it would probably pass it.

What do these numbers tell us?

  1. Embeddings are the most valuable change. Raw ids suggest that “word 41 is close to word 42”, which means nothing. Learned vectors fix the representation, and everything after it improves.
  2. Encoder-decoder models learn slowly at the start. Squeezing the whole sentence into one 512-number vector is powerful, but at 15 epochs it was actually the worst model.
  3. Compare models with the same training budget. My models were trained for different numbers of epochs, so this ranking is “under these budgets”, not a general rule.
  4. The dataset decides a lot. With a small vocabulary and very similar sentences, words map almost one-to-one, which is exactly what embedding + GRU is good at. On real text with long sentences and word reordering, encoder-decoder models with attention win clearly.

Reading the output: The model outputs a probability for every French word at every position. To read the translation, take the most likely word at each position and map the ids back to words, skipping the padding:

def logits_to_text(logits, tokenizer):
    index_to_word = {i: w for w, i in tokenizer.word_index.items()}
    index_to_word[0] = "<PAD>"
    return " ".join(index_to_word[i] for i in np.argmax(logits, axis=1)
                    if index_to_word[i] != "<PAD>")

What the numbers taught me

Five models on the same data showed that architecture diagrams don’t tell the whole story: the embedding layer gave the biggest jump, the encoder-decoder needed far more training, and the dataset itself favoured the simpler model. The natural next steps are attention, beam search instead of greedy decoding, BLEU for evaluation — and finally Transformers, which dropped recurrence altogether. The notebook is on GitHub; the architecture diagrams come from Udacity’s project template (MIT licence).