Language Translation

In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French.

Get the Data

Since translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus.


In [1]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import problem_unittests as tests

source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)

Explore the Data

Play around with view_sentence_range to view different parts of the data.


In [2]:
view_sentence_range = (30, 40)

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np

print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()})))

sentences = source_text.split('\n')
word_counts = [len(sentence.split()) for sentence in sentences]
print('Number of sentences: {}'.format(len(sentences)))
print('Average number of words in a sentence: {}'.format(np.average(word_counts)))

print()
print('English sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(source_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))
print()
print('French sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(target_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))


Dataset Stats
Roughly the number of unique words: 227
Number of sentences: 137861
Average number of words in a sentence: 13.225277634719028

English sentences 30 to 40:
he dislikes apples , peaches , and grapes .
california is usually freezing during december , and it is busy in april .
your most feared animal is that shark .
paris is usually wet during august , and it is never dry in november .
paris is usually beautiful during september , and it is usually snowy in november .
the united states is never wet during january , but it is usually hot in october .
we like oranges , mangoes , and grapes .
they like pears , apples , and mangoes .
she dislikes that little red truck .
the grapefruit is my most loved fruit , but the banana is her most loved .

French sentences 30 to 40:
il déteste les pommes , les pêches et les raisins .
la californie est le gel habituellement en décembre , et il est occupé en avril .
votre animal le plus redouté est que le requin .
paris est généralement humide au mois d' août , et il est jamais sec en novembre .
paris est généralement beau en septembre , et il est généralement enneigée en novembre .
les états-unis est jamais humide en janvier , mais il est généralement chaud en octobre .
nous aimons les oranges , les mangues et les raisins .
ils aiment les poires , les pommes et les mangues .
elle déteste ce petit camion rouge .
le pamplemousse est mon fruit le plus cher , mais la banane est la plus aimée .

Implement Preprocessing Function

Text to Word Ids

As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of target_text. This will help the neural network predict when the sentence should end.

You can get the <EOS> word id by doing:

target_vocab_to_int['<EOS>']

You can get other word ids using source_vocab_to_int and target_vocab_to_int.


In [3]:
def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
    """
    Convert source and target text to proper word ids
    :param source_text: String that contains all the source text.
    :param target_text: String that contains all the target text.
    :param source_vocab_to_int: Dictionary to go from the source words to an id
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :return: A tuple of lists (source_id_text, target_id_text)
    """
    # Split text into sentences
    source_sentences, target_sentences = source_text.split('\n'), target_text.split('\n')
    
    # Split sentences into words and convert to integers
    source_id_text = [[source_vocab_to_int[word] for word in sentence.split()] for sentence in source_sentences]
    target_id_text = [[target_vocab_to_int[word] for word in sentence.split()] for sentence in target_sentences]
    
    # Append <EOS> to all target sentences
    for sentence in target_id_text:
        sentence.append(target_vocab_to_int['<EOS>'])
    
    return source_id_text, target_id_text

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_text_to_ids(text_to_ids)


Tests Passed

Preprocess all the data and save it

Running the code cell below will preprocess all the data and save it to file.


In [4]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
helper.preprocess_and_save_data(source_path, target_path, text_to_ids)

Check Point

This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.


In [5]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
import helper
import problem_unittests as tests

(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()

Check the Version of TensorFlow and Access to GPU

This will check to make sure you have the correct version of TensorFlow and access to a GPU


In [6]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
from tensorflow.python.layers.core import Dense

# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.1'), 'Please use TensorFlow version 1.1 or newer'
print('TensorFlow Version: {}'.format(tf.__version__))

# Check for a GPU
if not tf.test.gpu_device_name():
    warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))


TensorFlow Version: 1.1.0
Default GPU Device: /gpu:0

Build the Neural Network

You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:

  • model_inputs
  • process_decoder_input
  • encoding_layer
  • decoding_layer_train
  • decoding_layer_infer
  • decoding_layer
  • seq2seq_model

Input

Implement the model_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:

  • Input text placeholder named "input" using the TF Placeholder name parameter with rank 2.
  • Targets placeholder with rank 2.
  • Learning rate placeholder with rank 0.
  • Keep probability placeholder named "keep_prob" using the TF Placeholder name parameter with rank 0.
  • Target sequence length placeholder named "target_sequence_length" with rank 1
  • Max target sequence length tensor named "max_target_len" getting its value from applying tf.reduce_max on the target_sequence_length placeholder. Rank 0.
  • Source sequence length placeholder named "source_sequence_length" with rank 1

Return the placeholders in the following the tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length)


In [7]:
def model_inputs():
    """
    Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences.
    :return: Tuple (input, targets, learning rate, keep probability, target sequence length,
    max target sequence length, source sequence length)
    """
    input_ = tf.placeholder(tf.int32, [None, None], name='input')
    target = tf.placeholder(tf.int32, [None, None])
    learning_rate = tf.placeholder(tf.float32)
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    target_sequence_length = tf.placeholder(tf.int32, [None], name='target_sequence_length')
    max_target_len = tf.reduce_max(target_sequence_length, name='max_target_len')
    source_sequence_length = tf.placeholder(tf.int32, [None], name='source_sequence_length')
    
    return input_, target, learning_rate, keep_prob, target_sequence_length, max_target_len, source_sequence_length


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)


Tests Passed

Process Decoder Input

Implement process_decoder_input by removing the last word id from each batch in target_data and concat the GO ID to the begining of each batch.


In [8]:
def process_decoder_input(target_data, target_vocab_to_int, batch_size):
    """
    Preprocess target data for encoding
    :param target_data: Target Placehoder
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :param batch_size: Batch Size
    :return: Preprocessed target data
    """
    # Code taken from https://github.com/udacity/deep-learning/blob/master/seq2seq/sequence_to_sequence_implementation.ipynb
    
    # Slice out the last column (will remove the last word ids in each batch)
    ending = tf.strided_slice(target_data, [0, 0], [batch_size, -1], [1, 1])
    
    # Fill a new vector column with <GO> tags
    go_fill = tf.fill([batch_size, 1], target_vocab_to_int['<GO>'])
    
    # Concatenate the <GO> fill vector to the beginning of the batches
    preprocessed = tf.concat([go_fill, ending], 1)

    return preprocessed

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_process_encoding_input(process_decoder_input)


Tests Passed

Encoding

Implement encoding_layer() to create a Encoder RNN layer:


In [9]:
from imp import reload
reload(tests)

def build_cell(lstm_size, keep_prob):
    """
    Build a basic LSTM cell with dropout
    :param lstm_size: Number of LSTM units
    :param keep_prob: Dropout keep value
    """
#     initializer = tf.random_uniform_initializer(-0.1, 0.1, seed=100)
    lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
    drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
    return drop

def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, 
                   source_sequence_length, source_vocab_size, 
                   encoding_embedding_size):
    """
    Create encoding layer
    :param rnn_inputs: Inputs for the RNN
    :param rnn_size: RNN Size
    :param num_layers: Number of layers
    :param keep_prob: Dropout keep probability
    :param source_sequence_length: a list of the lengths of each sequence in the batch
    :param source_vocab_size: vocabulary size of source data
    :param encoding_embedding_size: embedding size of source data
    :return: tuple (RNN output, RNN state)
    """
    # Create the embedding layer and LSTM layer(s)
    embed = tf.contrib.layers.embed_sequence(
        rnn_inputs, vocab_size=source_vocab_size, embed_dim=encoding_embedding_size)
    cell = tf.contrib.rnn.MultiRNNCell([build_cell(rnn_size, keep_prob) for _ in range(num_layers)])
    
    # Join the embedding/LSTM layers together
    outputs, final_state = tf.nn.dynamic_rnn(cell, embed, sequence_length=source_sequence_length, dtype=tf.float32)

    return outputs, final_state

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_encoding_layer(encoding_layer)


Tests Passed

Decoding - Training

Create a training decoding layer:


In [10]:
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, 
                         target_sequence_length, max_summary_length, 
                         output_layer, keep_prob):
    """
    Create a decoding layer for training
    :param encoder_state: Encoder State
    :param dec_cell: Decoder RNN Cell
    :param dec_embed_input: Decoder embedded input
    :param target_sequence_length: The lengths of each sequence in the target batch
    :param max_summary_length: The length of the longest sequence in the batch
    :param output_layer: Function to apply the output layer
    :param keep_prob: Dropout keep probability
    :return: BasicDecoderOutput containing training logits and sample_id
    """
    # The training decoding layer takes training examples as input
    helper = tf.contrib.seq2seq.TrainingHelper(dec_embed_input, target_sequence_length)
    decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, helper, encoder_state, output_layer=output_layer)
    final_outputs, final_state = tf.contrib.seq2seq.dynamic_decode(
        decoder, impute_finished=True, maximum_iterations=max_summary_length)
    
    return final_outputs



"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_train(decoding_layer_train)


Tests Passed

Decoding - Inference

Create inference decoder:


In [11]:
def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,
                         end_of_sequence_id, max_target_sequence_length,
                         vocab_size, output_layer, batch_size, keep_prob):
    """
    Create a decoding layer for inference
    :param encoder_state: Encoder state
    :param dec_cell: Decoder RNN Cell
    :param dec_embeddings: Decoder embeddings
    :param start_of_sequence_id: GO ID
    :param end_of_sequence_id: EOS Id
    :param max_target_sequence_length: Maximum length of target sequences
    :param vocab_size: Size of decoder/target vocabulary
    :param decoding_scope: TenorFlow Variable Scope for decoding
    :param output_layer: Function to apply the output layer
    :param batch_size: Batch size
    :param keep_prob: Dropout keep probability
    :return: BasicDecoderOutput containing inference logits and sample_id
    """
    # Broadcast the start sequence id to a list of start tokens, one for each batch
    start_tokens = tf.tile(tf.constant([start_of_sequence_id]), [batch_size])
    
    # The inference decoding layer feeds takes its output as input
    helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings, start_tokens, end_of_sequence_id)
    decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, helper, encoder_state, output_layer=output_layer)
    final_outputs, final_state = tf.contrib.seq2seq.dynamic_decode(
        decoder, impute_finished=True, maximum_iterations=max_target_sequence_length)
    
    return final_outputs

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_infer(decoding_layer_infer)


Tests Passed

Build the Decoding Layer

Implement decoding_layer() to create a Decoder RNN layer.

  • Embed the target sequences
  • Construct the decoder LSTM cell (just like you constructed the encoder cell above)
  • Create an output layer to map the outputs of the decoder to the elements of our vocabulary
  • Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob) function to get the training logits.
  • Use your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob) function to get the inference logits.

Note: You'll need to use tf.variable_scope to share variables between training and inference.


In [14]:
def decoding_layer(dec_input, encoder_state,
                   target_sequence_length, max_target_sequence_length,
                   rnn_size,
                   num_layers, target_vocab_to_int, target_vocab_size,
                   batch_size, keep_prob, decoding_embedding_size):
    """
    Create decoding layer
    :param dec_input: Decoder input
    :param encoder_state: Encoder state
    :param target_sequence_length: The lengths of each sequence in the target batch
    :param max_target_sequence_length: Maximum length of target sequences
    :param rnn_size: RNN Size
    :param num_layers: Number of layers
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :param target_vocab_size: Size of target vocabulary
    :param batch_size: The size of the batch
    :param keep_prob: Dropout keep probability
    :param decoding_embedding_size: Decoding embedding size
    :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
    """
    # Create the embedding layer; note that an embedding lookup is passed to the training decoder,
    # while the whole embedding is passed to the inference decoder (pass the output back into itself) 
    dec_embedding = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size], -1, 1))
    dec_embed = tf.nn.embedding_lookup(dec_embedding, dec_input)
    
    dec_cell = tf.contrib.rnn.MultiRNNCell([build_cell(rnn_size, keep_prob) for _ in range(num_layers)])
    
    # Define a dense layer for both training and inference decoders, outputs vocabulary
    kernel_initializer = tf.truncated_normal_initializer(mean=0.0, stddev=0.1)
    output_layer = Dense(target_vocab_size, kernel_initializer=kernel_initializer)
    
    with tf.variable_scope('decode') as decoding_scope:
        # Training decoder
        train_output = decoding_layer_train(
            encoder_state, dec_cell, dec_embed, target_sequence_length, 
            max_target_sequence_length, output_layer, keep_prob)
        
        # Reuse the same components from the training decoder
        decoding_scope.reuse_variables()
        
        # Inference decoder
        infer_output = decoding_layer_infer(
            encoder_state, dec_cell, dec_embedding, target_vocab_to_int['<GO>'], 
            target_vocab_to_int['<EOS>'], max_target_sequence_length, 
            target_vocab_size, output_layer, batch_size, keep_prob)

    return train_output, infer_output



"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer(decoding_layer)


Tests Passed

Build the Neural Network

Apply the functions you implemented above to:

  • Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size).
  • Process target data using your process_decoder_input(target_data, target_vocab_to_int, batch_size) function.
  • Decode the encoded input using your decoding_layer(dec_input, enc_state, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size) function.

In [15]:
def seq2seq_model(input_data, target_data, keep_prob, batch_size,
                  source_sequence_length, target_sequence_length,
                  max_target_sentence_length,
                  source_vocab_size, target_vocab_size,
                  enc_embedding_size, dec_embedding_size,
                  rnn_size, num_layers, target_vocab_to_int):
    """
    Build the Sequence-to-Sequence part of the neural network
    :param input_data: Input placeholder
    :param target_data: Target placeholder
    :param keep_prob: Dropout keep probability placeholder
    :param batch_size: Batch Size
    :param source_sequence_length: Sequence Lengths of source sequences in the batch
    :param target_sequence_length: Sequence Lengths of target sequences in the batch
    :param source_vocab_size: Source vocabulary size
    :param target_vocab_size: Target vocabulary size
    :param enc_embedding_size: Decoder embedding size
    :param dec_embedding_size: Encoder embedding size
    :param rnn_size: RNN Size
    :param num_layers: Number of layers
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
    """
    # Pass input through the encoder, retrieving the state (discard output)
    _, encoder_state = encoding_layer(
        input_data, rnn_size, num_layers, keep_prob,
        source_sequence_length, source_vocab_size, enc_embedding_size)
    
    # Preprocess the target input for the training decoder
    dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size)
    
    # Decode encoded input
    train_output, infer_output = decoding_layer(
        dec_input, encoder_state, target_sequence_length, 
        max_target_sentence_length, rnn_size, num_layers,
        target_vocab_to_int, target_vocab_size, batch_size,
        keep_prob, dec_embedding_size)
    
    return train_output, infer_output


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_seq2seq_model(seq2seq_model)


Tests Passed

Neural Network Training

Hyperparameters

Tune the following parameters:

  • Set epochs to the number of epochs.
  • Set batch_size to the batch size.
  • Set rnn_size to the size of the RNNs.
  • Set num_layers to the number of layers.
  • Set encoding_embedding_size to the size of the embedding for the encoder.
  • Set decoding_embedding_size to the size of the embedding for the decoder.
  • Set learning_rate to the learning rate.
  • Set keep_probability to the Dropout keep probability
  • Set display_step to state how many steps between each debug output statement

In [83]:
# Number of Epochs
epochs = 10
# Batch Size
batch_size = 256
# RNN Size
rnn_size = 256
# Number of Layers
num_layers = 3
# Embedding Size
encoding_embedding_size = 128
decoding_embedding_size = 128
# Learning Rate
learning_rate = 0.001
# Dropout Keep Probability
keep_probability = 0.7
display_step = 50

Build the Graph

Build the graph using the neural network you implemented.


In [84]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
save_path = 'checkpoints/dev'
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
max_target_sentence_length = max([len(sentence) for sentence in source_int_text])

train_graph = tf.Graph()
with train_graph.as_default():
    input_data, targets, lr, keep_prob, target_sequence_length, max_target_sequence_length, source_sequence_length = model_inputs()

    #sequence_length = tf.placeholder_with_default(max_target_sentence_length, None, name='sequence_length')
    input_shape = tf.shape(input_data)

    train_logits, inference_logits = seq2seq_model(tf.reverse(input_data, [-1]),
                                                   targets,
                                                   keep_prob,
                                                   batch_size,
                                                   source_sequence_length,
                                                   target_sequence_length,
                                                   max_target_sequence_length,
                                                   len(source_vocab_to_int),
                                                   len(target_vocab_to_int),
                                                   encoding_embedding_size,
                                                   decoding_embedding_size,
                                                   rnn_size,
                                                   num_layers,
                                                   target_vocab_to_int)


    training_logits = tf.identity(train_logits.rnn_output, name='logits')
    inference_logits = tf.identity(inference_logits.sample_id, name='predictions')

    masks = tf.sequence_mask(target_sequence_length, max_target_sequence_length, dtype=tf.float32, name='masks')

    with tf.name_scope("optimization"):
        # Loss function
        cost = tf.contrib.seq2seq.sequence_loss(
            training_logits,
            targets,
            masks)

        # Optimizer
        optimizer = tf.train.AdamOptimizer(lr)

        # Gradient Clipping
        gradients = optimizer.compute_gradients(cost)
        capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]
        train_op = optimizer.apply_gradients(capped_gradients)

Batch and pad the source and target sequences


In [85]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def pad_sentence_batch(sentence_batch, pad_int):
    """Pad sentences with <PAD> so that each sentence of a batch has the same length"""
    max_sentence = max([len(sentence) for sentence in sentence_batch])
    return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]


def get_batches(sources, targets, batch_size, source_pad_int, target_pad_int):
    """Batch targets, sources, and the lengths of their sentences together"""
    for batch_i in range(0, len(sources)//batch_size):
        start_i = batch_i * batch_size

        # Slice the right amount for the batch
        sources_batch = sources[start_i:start_i + batch_size]
        targets_batch = targets[start_i:start_i + batch_size]

        # Pad
        pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int))
        pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int))

        # Need the lengths for the _lengths parameters
        pad_targets_lengths = []
        for target in pad_targets_batch:
            pad_targets_lengths.append(len(target))

        pad_source_lengths = []
        for source in pad_sources_batch:
            pad_source_lengths.append(len(source))

        yield pad_sources_batch, pad_targets_batch, pad_source_lengths, pad_targets_lengths

Train

Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.


In [86]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def get_accuracy(target, logits):
    """
    Calculate accuracy
    """
    max_seq = max(target.shape[1], logits.shape[1])
    if max_seq - target.shape[1]:
        target = np.pad(
            target,
            [(0,0),(0,max_seq - target.shape[1])],
            'constant')
    if max_seq - logits.shape[1]:
        logits = np.pad(
            logits,
            [(0,0),(0,max_seq - logits.shape[1])],
            'constant')

    return np.mean(np.equal(target, logits))

# Split data to training and validation sets
train_source = source_int_text[batch_size:]
train_target = target_int_text[batch_size:]
valid_source = source_int_text[:batch_size]
valid_target = target_int_text[:batch_size]
(valid_sources_batch, valid_targets_batch, valid_sources_lengths, valid_targets_lengths ) = next(get_batches(valid_source,
                                                                                                             valid_target,
                                                                                                             batch_size,
                                                                                                             source_vocab_to_int['<PAD>'],
                                                                                                             target_vocab_to_int['<PAD>']))                                                                                                  
with tf.Session(graph=train_graph) as sess:
    sess.run(tf.global_variables_initializer())

    for epoch_i in range(epochs):
        for batch_i, (source_batch, target_batch, sources_lengths, targets_lengths) in enumerate(
                get_batches(train_source, train_target, batch_size,
                            source_vocab_to_int['<PAD>'],
                            target_vocab_to_int['<PAD>'])):

            _, loss = sess.run(
                [train_op, cost],
                {input_data: source_batch,
                 targets: target_batch,
                 lr: learning_rate,
                 target_sequence_length: targets_lengths,
                 source_sequence_length: sources_lengths,
                 keep_prob: keep_probability})


            if batch_i % display_step == 0 and batch_i > 0:


                batch_train_logits = sess.run(
                    inference_logits,
                    {input_data: source_batch,
                     source_sequence_length: sources_lengths,
                     target_sequence_length: targets_lengths,
                     keep_prob: 1.0})


                batch_valid_logits = sess.run(
                    inference_logits,
                    {input_data: valid_sources_batch,
                     source_sequence_length: valid_sources_lengths,
                     target_sequence_length: valid_targets_lengths,
                     keep_prob: 1.0})

                train_acc = get_accuracy(target_batch, batch_train_logits)

                valid_acc = get_accuracy(valid_targets_batch, batch_valid_logits)

                print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.4f}, Validation Accuracy: {:>6.4f}, Loss: {:>6.4f}'
                      .format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss))

    # Save Model
    saver = tf.train.Saver()
    saver.save(sess, save_path)
    print('Model Trained and Saved')


Epoch   0 Batch   50/538 - Train Accuracy: 0.4037, Validation Accuracy: 0.4666, Loss: 2.2978
Epoch   0 Batch  100/538 - Train Accuracy: 0.4533, Validation Accuracy: 0.5105, Loss: 1.6012
Epoch   0 Batch  150/538 - Train Accuracy: 0.4846, Validation Accuracy: 0.5202, Loss: 1.3221
Epoch   0 Batch  200/538 - Train Accuracy: 0.4988, Validation Accuracy: 0.5371, Loss: 1.1274
Epoch   0 Batch  250/538 - Train Accuracy: 0.5027, Validation Accuracy: 0.5437, Loss: 0.9739
Epoch   0 Batch  300/538 - Train Accuracy: 0.5818, Validation Accuracy: 0.5767, Loss: 0.8557
Epoch   0 Batch  350/538 - Train Accuracy: 0.5755, Validation Accuracy: 0.5748, Loss: 0.8017
Epoch   0 Batch  400/538 - Train Accuracy: 0.5813, Validation Accuracy: 0.5950, Loss: 0.7130
Epoch   0 Batch  450/538 - Train Accuracy: 0.6146, Validation Accuracy: 0.6136, Loss: 0.6928
Epoch   0 Batch  500/538 - Train Accuracy: 0.6115, Validation Accuracy: 0.6090, Loss: 0.5891
Epoch   1 Batch   50/538 - Train Accuracy: 0.6391, Validation Accuracy: 0.6369, Loss: 0.5745
Epoch   1 Batch  100/538 - Train Accuracy: 0.6451, Validation Accuracy: 0.6316, Loss: 0.5245
Epoch   1 Batch  150/538 - Train Accuracy: 0.6412, Validation Accuracy: 0.6509, Loss: 0.5139
Epoch   1 Batch  200/538 - Train Accuracy: 0.6963, Validation Accuracy: 0.6765, Loss: 0.4540
Epoch   1 Batch  250/538 - Train Accuracy: 0.6937, Validation Accuracy: 0.6834, Loss: 0.4301
Epoch   1 Batch  300/538 - Train Accuracy: 0.7264, Validation Accuracy: 0.7147, Loss: 0.4009
Epoch   1 Batch  350/538 - Train Accuracy: 0.7228, Validation Accuracy: 0.7216, Loss: 0.3757
Epoch   1 Batch  400/538 - Train Accuracy: 0.7597, Validation Accuracy: 0.7539, Loss: 0.3502
Epoch   1 Batch  450/538 - Train Accuracy: 0.7839, Validation Accuracy: 0.7667, Loss: 0.3288
Epoch   1 Batch  500/538 - Train Accuracy: 0.8100, Validation Accuracy: 0.7875, Loss: 0.2723
Epoch   2 Batch   50/538 - Train Accuracy: 0.8420, Validation Accuracy: 0.8168, Loss: 0.2431
Epoch   2 Batch  100/538 - Train Accuracy: 0.8482, Validation Accuracy: 0.8132, Loss: 0.2216
Epoch   2 Batch  150/538 - Train Accuracy: 0.8471, Validation Accuracy: 0.8446, Loss: 0.2089
Epoch   2 Batch  200/538 - Train Accuracy: 0.8551, Validation Accuracy: 0.8516, Loss: 0.1823
Epoch   2 Batch  250/538 - Train Accuracy: 0.8920, Validation Accuracy: 0.8571, Loss: 0.1704
Epoch   2 Batch  300/538 - Train Accuracy: 0.8757, Validation Accuracy: 0.8576, Loss: 0.1581
Epoch   2 Batch  350/538 - Train Accuracy: 0.9133, Validation Accuracy: 0.8720, Loss: 0.1472
Epoch   2 Batch  400/538 - Train Accuracy: 0.8878, Validation Accuracy: 0.8782, Loss: 0.1256
Epoch   2 Batch  450/538 - Train Accuracy: 0.8964, Validation Accuracy: 0.9016, Loss: 0.1398
Epoch   2 Batch  500/538 - Train Accuracy: 0.9157, Validation Accuracy: 0.8835, Loss: 0.0961
Epoch   3 Batch   50/538 - Train Accuracy: 0.9088, Validation Accuracy: 0.8956, Loss: 0.0906
Epoch   3 Batch  100/538 - Train Accuracy: 0.9158, Validation Accuracy: 0.8750, Loss: 0.0867
Epoch   3 Batch  150/538 - Train Accuracy: 0.9248, Validation Accuracy: 0.9041, Loss: 0.0807
Epoch   3 Batch  200/538 - Train Accuracy: 0.9113, Validation Accuracy: 0.8908, Loss: 0.0728
Epoch   3 Batch  250/538 - Train Accuracy: 0.9256, Validation Accuracy: 0.9062, Loss: 0.0752
Epoch   3 Batch  300/538 - Train Accuracy: 0.9115, Validation Accuracy: 0.9031, Loss: 0.0787
Epoch   3 Batch  350/538 - Train Accuracy: 0.9273, Validation Accuracy: 0.9180, Loss: 0.0822
Epoch   3 Batch  400/538 - Train Accuracy: 0.9221, Validation Accuracy: 0.9116, Loss: 0.0748
Epoch   3 Batch  450/538 - Train Accuracy: 0.6895, Validation Accuracy: 0.6639, Loss: 0.1206
Epoch   3 Batch  500/538 - Train Accuracy: 0.9343, Validation Accuracy: 0.8995, Loss: 0.0663
Epoch   4 Batch   50/538 - Train Accuracy: 0.9279, Validation Accuracy: 0.9128, Loss: 0.0606
Epoch   4 Batch  100/538 - Train Accuracy: 0.9416, Validation Accuracy: 0.9197, Loss: 0.0567
Epoch   4 Batch  150/538 - Train Accuracy: 0.9402, Validation Accuracy: 0.9235, Loss: 0.0530
Epoch   4 Batch  200/538 - Train Accuracy: 0.9334, Validation Accuracy: 0.9242, Loss: 0.0496
Epoch   4 Batch  250/538 - Train Accuracy: 0.9354, Validation Accuracy: 0.9151, Loss: 0.0575
Epoch   4 Batch  300/538 - Train Accuracy: 0.9239, Validation Accuracy: 0.9251, Loss: 0.0568
Epoch   4 Batch  350/538 - Train Accuracy: 0.9462, Validation Accuracy: 0.9343, Loss: 0.0568
Epoch   4 Batch  400/538 - Train Accuracy: 0.9431, Validation Accuracy: 0.9441, Loss: 0.0496
Epoch   4 Batch  450/538 - Train Accuracy: 0.9243, Validation Accuracy: 0.9412, Loss: 0.0647
Epoch   4 Batch  500/538 - Train Accuracy: 0.9508, Validation Accuracy: 0.9345, Loss: 0.0387
Epoch   5 Batch   50/538 - Train Accuracy: 0.9535, Validation Accuracy: 0.9345, Loss: 0.0417
Epoch   5 Batch  100/538 - Train Accuracy: 0.9449, Validation Accuracy: 0.9505, Loss: 0.0353
Epoch   5 Batch  150/538 - Train Accuracy: 0.9527, Validation Accuracy: 0.9494, Loss: 0.0430
Epoch   5 Batch  200/538 - Train Accuracy: 0.9320, Validation Accuracy: 0.9487, Loss: 0.0408
Epoch   5 Batch  250/538 - Train Accuracy: 0.9539, Validation Accuracy: 0.9311, Loss: 0.0465
Epoch   5 Batch  300/538 - Train Accuracy: 0.9366, Validation Accuracy: 0.9437, Loss: 0.0451
Epoch   5 Batch  350/538 - Train Accuracy: 0.9561, Validation Accuracy: 0.9510, Loss: 0.0495
Epoch   5 Batch  400/538 - Train Accuracy: 0.9568, Validation Accuracy: 0.9453, Loss: 0.0410
Epoch   5 Batch  450/538 - Train Accuracy: 0.9265, Validation Accuracy: 0.9450, Loss: 0.0551
Epoch   5 Batch  500/538 - Train Accuracy: 0.9696, Validation Accuracy: 0.9499, Loss: 0.0269
Epoch   6 Batch   50/538 - Train Accuracy: 0.9553, Validation Accuracy: 0.9560, Loss: 0.0344
Epoch   6 Batch  100/538 - Train Accuracy: 0.9705, Validation Accuracy: 0.9627, Loss: 0.0310
Epoch   6 Batch  150/538 - Train Accuracy: 0.9668, Validation Accuracy: 0.9471, Loss: 0.0304
Epoch   6 Batch  200/538 - Train Accuracy: 0.9625, Validation Accuracy: 0.9537, Loss: 0.0295
Epoch   6 Batch  250/538 - Train Accuracy: 0.9605, Validation Accuracy: 0.9600, Loss: 0.0352
Epoch   6 Batch  300/538 - Train Accuracy: 0.9438, Validation Accuracy: 0.9533, Loss: 0.0376
Epoch   6 Batch  350/538 - Train Accuracy: 0.9648, Validation Accuracy: 0.9595, Loss: 0.0394
Epoch   6 Batch  400/538 - Train Accuracy: 0.9767, Validation Accuracy: 0.9544, Loss: 0.0318
Epoch   6 Batch  450/538 - Train Accuracy: 0.9386, Validation Accuracy: 0.9615, Loss: 0.0501
Epoch   6 Batch  500/538 - Train Accuracy: 0.9764, Validation Accuracy: 0.9453, Loss: 0.0238
Epoch   7 Batch   50/538 - Train Accuracy: 0.9736, Validation Accuracy: 0.9519, Loss: 0.0301
Epoch   7 Batch  100/538 - Train Accuracy: 0.9734, Validation Accuracy: 0.9588, Loss: 0.0284
Epoch   7 Batch  150/538 - Train Accuracy: 0.9705, Validation Accuracy: 0.9672, Loss: 0.0268
Epoch   7 Batch  200/538 - Train Accuracy: 0.9674, Validation Accuracy: 0.9570, Loss: 0.0258
Epoch   7 Batch  250/538 - Train Accuracy: 0.9725, Validation Accuracy: 0.9609, Loss: 0.0327
Epoch   7 Batch  300/538 - Train Accuracy: 0.9594, Validation Accuracy: 0.9707, Loss: 0.0340
Epoch   7 Batch  350/538 - Train Accuracy: 0.9771, Validation Accuracy: 0.9663, Loss: 0.0312
Epoch   7 Batch  400/538 - Train Accuracy: 0.9823, Validation Accuracy: 0.9606, Loss: 0.0288
Epoch   7 Batch  450/538 - Train Accuracy: 0.9496, Validation Accuracy: 0.9691, Loss: 0.0422
Epoch   7 Batch  500/538 - Train Accuracy: 0.9744, Validation Accuracy: 0.9604, Loss: 0.0197
Epoch   8 Batch   50/538 - Train Accuracy: 0.9660, Validation Accuracy: 0.9570, Loss: 0.0251
Epoch   8 Batch  100/538 - Train Accuracy: 0.9742, Validation Accuracy: 0.9686, Loss: 0.0211
Epoch   8 Batch  150/538 - Train Accuracy: 0.9762, Validation Accuracy: 0.9691, Loss: 0.0267
Epoch   8 Batch  200/538 - Train Accuracy: 0.9719, Validation Accuracy: 0.9585, Loss: 0.0235
Epoch   8 Batch  250/538 - Train Accuracy: 0.9715, Validation Accuracy: 0.9608, Loss: 0.0267
Epoch   8 Batch  300/538 - Train Accuracy: 0.9617, Validation Accuracy: 0.9689, Loss: 0.0245
Epoch   8 Batch  350/538 - Train Accuracy: 0.9708, Validation Accuracy: 0.9611, Loss: 0.0289
Epoch   8 Batch  400/538 - Train Accuracy: 0.9732, Validation Accuracy: 0.9577, Loss: 0.0242
Epoch   8 Batch  450/538 - Train Accuracy: 0.9503, Validation Accuracy: 0.9544, Loss: 0.0352
Epoch   8 Batch  500/538 - Train Accuracy: 0.9895, Validation Accuracy: 0.9583, Loss: 0.0174
Epoch   9 Batch   50/538 - Train Accuracy: 0.9701, Validation Accuracy: 0.9682, Loss: 0.0242
Epoch   9 Batch  100/538 - Train Accuracy: 0.9750, Validation Accuracy: 0.9714, Loss: 0.0222
Epoch   9 Batch  150/538 - Train Accuracy: 0.9777, Validation Accuracy: 0.9595, Loss: 0.0188
Epoch   9 Batch  200/538 - Train Accuracy: 0.9812, Validation Accuracy: 0.9569, Loss: 0.0217
Epoch   9 Batch  250/538 - Train Accuracy: 0.9754, Validation Accuracy: 0.9686, Loss: 0.0242
Epoch   9 Batch  300/538 - Train Accuracy: 0.9721, Validation Accuracy: 0.9712, Loss: 0.0262
Epoch   9 Batch  350/538 - Train Accuracy: 0.9736, Validation Accuracy: 0.9625, Loss: 0.0246
Epoch   9 Batch  400/538 - Train Accuracy: 0.9805, Validation Accuracy: 0.9684, Loss: 0.0205
Epoch   9 Batch  450/538 - Train Accuracy: 0.9650, Validation Accuracy: 0.9608, Loss: 0.0299
Epoch   9 Batch  500/538 - Train Accuracy: 0.9849, Validation Accuracy: 0.9670, Loss: 0.0135
Model Trained and Saved

Save Parameters

Save the batch_size and save_path parameters for inference.


In [87]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
# Save parameters for checkpoint
helper.save_params(save_path)

Checkpoint


In [88]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import tensorflow as tf
import numpy as np
import helper
import problem_unittests as tests

_, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess()
load_path = helper.load_params()

Sentence to Sequence

To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.

  • Convert the sentence to lowercase
  • Convert words into ids using vocab_to_int
    • Convert words not in the vocabulary, to the <UNK> word id.

In [89]:
def sentence_to_seq(sentence, vocab_to_int):
    """
    Convert a sentence to a sequence of ids
    :param sentence: String
    :param vocab_to_int: Dictionary to go from the words to an id
    :return: List of word ids
    """
    sentence_lower = [word.lower() for word in sentence.split()]
    sentence_int = [
        vocab_to_int[word] if word in vocab_to_int 
        else vocab_to_int['<UNK>']
        for word in sentence_lower
    ]

    return sentence_int


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_sentence_to_seq(sentence_to_seq)


Tests Passed

Translate

This will translate translate_sentence from English to French.


In [98]:
# translate_sentence = 'he saw a old yellow truck .'
translate_sentence = sentences[10]

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
translate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int)

loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
    # Load saved model
    loader = tf.train.import_meta_graph(load_path + '.meta')
    loader.restore(sess, load_path)

    input_data = loaded_graph.get_tensor_by_name('input:0')
    logits = loaded_graph.get_tensor_by_name('predictions:0')
    target_sequence_length = loaded_graph.get_tensor_by_name('target_sequence_length:0')
    source_sequence_length = loaded_graph.get_tensor_by_name('source_sequence_length:0')
    keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')

    translate_logits = sess.run(logits, {input_data: [translate_sentence]*batch_size,
                                         target_sequence_length: [len(translate_sentence)*2]*batch_size,
                                         source_sequence_length: [len(translate_sentence)]*batch_size,
                                         keep_prob: 1.0})[0]

print('Input')
print('  Word Ids:      {}'.format([i for i in translate_sentence]))
print('  English Words: {}'.format([source_int_to_vocab[i] for i in translate_sentence]))

print('\nPrediction')
print('  Word Ids:      {}'.format([i for i in translate_logits]))
print('  French Words: {}'.format(" ".join([target_int_to_vocab[i] for i in translate_logits])))


INFO:tensorflow:Restoring parameters from checkpoints/dev
Input
  Word Ids:      [54, 222, 94, 178, 26, 158, 223, 175, 48, 54, 77, 94, 90, 26, 158, 6]
  English Words: ['the', 'lime', 'is', 'her', 'least', 'liked', 'fruit', ',', 'but', 'the', 'banana', 'is', 'my', 'least', 'liked', '.']

Prediction
  Word Ids:      [239, 36, 67, 315, 356, 340, 30, 166, 345, 239, 135, 67, 262, 340, 113, 1]
  French Words: la chaux est son fruit moins aimé , mais la banane est mon moins aimé. <EOS>

Imperfect Translation

You might notice that some sentences translate better than others. Since the dataset you're using only has a vocabulary of 227 English words of the thousands that you use, you're only going to see good results using these words. For this project, you don't need a perfect translation. However, if you want to create a better translation model, you'll need better data.

You can train on the WMT10 French-English corpus. This dataset has more vocabulary and richer in topics discussed. However, this will take you days to train, so make sure you've a GPU and the neural network is performing well on dataset we provided. Just make sure you play with the WMT10 corpus after you've submitted this project.

Submitting This Project

When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_language_translation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.