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 = (0, 10)

"""
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 0 to 10:
new jersey is sometimes quiet during autumn , and it is snowy in april .
the united states is usually chilly during july , and it is usually freezing in november .
california is usually quiet during march , and it is usually hot in june .
the united states is sometimes mild during june , and it is cold in september .
your least liked fruit is the grape , but my least liked is the apple .
his favorite fruit is the orange , but my favorite is the grape .
paris is relaxing during december , but it is usually chilly in july .
new jersey is busy during spring , and it is never hot in march .
our least liked fruit is the lemon , but my least liked is the grape .
the united states is sometimes busy during january , and it is sometimes warm in november .

French sentences 0 to 10:
new jersey est parfois calme pendant l' automne , et il est neigeux en avril .
les états-unis est généralement froid en juillet , et il gèle habituellement en novembre .
california est généralement calme en mars , et il est généralement chaud en juin .
les états-unis est parfois légère en juin , et il fait froid en septembre .
votre moins aimé fruit est le raisin , mais mon moins aimé est la pomme .
son fruit préféré est l'orange , mais mon préféré est le raisin .
paris est relaxant en décembre , mais il est généralement froid en juillet .
new jersey est occupé au printemps , et il est jamais chaude en mars .
notre fruit est moins aimé le citron , mais mon moins aimé est le raisin .
les états-unis est parfois occupé en janvier , et il est parfois chaud en novembre .

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)
    """
  
    # Process source text
    words = [[word for word in line.split()] for line in source_text.split('\n')]
    source_word_ids = [[source_vocab_to_int.get(word, source_vocab_to_int['<UNK>']) for word in line.split()] for line in source_text.split('\n')] # use get to replace ignored/unknown characters by <UNK>
    
    
    # Process target text
    target_word_ids = [[target_vocab_to_int.get(word, target_vocab_to_int['<UNK>']) for word in line.split()] + [target_vocab_to_int['<EOS>']] for line in target_text.split('\n')]
    
    
    return source_word_ids, target_word_ids

"""
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.2.1
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_text = tf.placeholder(tf.int32, [None, None], name='input')
    targets = tf.placeholder(tf.int32, [None, None], name='targets')
    lr = tf.placeholder(tf.float32, name='learning_rate' )
    keep = tf.placeholder(tf.float32, name='keep_prob')
    target_seq_len = tf.placeholder(tf.int32, (None,), name='target_sequence_length')
    max_target_seq_len = tf.reduce_max(target_seq_len, name='max_target_len')
    source_seq_len = tf.placeholder(tf.int32, (None,), name='source_sequence_length')

    return input_text, targets, lr, keep, target_seq_len, max_target_seq_len, source_seq_len  


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
ERROR:tensorflow:==================================
Object was never used (type <class 'tensorflow.python.framework.ops.Operation'>):
<tf.Operation 'assert_rank_2/Assert/Assert' type=Assert>
If you want to mark it as used call its "mark_used()" method.
It was originally created here:
['File "/usr/local/lib/python3.5/runpy.py", line 193, in _run_module_as_main\n    "__main__", mod_spec)', 'File "/usr/local/lib/python3.5/runpy.py", line 85, in _run_code\n    exec(code, run_globals)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel_launcher.py", line 16, in <module>\n    app.launch_new_instance()', 'File "/usr/local/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance\n    app.start()', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 477, in start\n    ioloop.IOLoop.instance().start()', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start\n    super(ZMQIOLoop, self).start()', 'File "/usr/local/lib/python3.5/site-packages/tornado/ioloop.py", line 888, in start\n    handler_func(fd_obj, events)', 'File "/usr/local/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper\n    return fn(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events\n    self._handle_recv()', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv\n    self._run_callback(callback, msg)', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback\n    callback(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper\n    return fn(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher\n    return self.dispatch_shell(stream, msg)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell\n    handler(stream, idents, msg)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 399, in execute_request\n    user_expressions, allow_stdin)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 196, in do_execute\n    res = shell.run_cell(code, store_history=store_history, silent=silent)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 533, in run_cell\n    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell\n    interactivity=interactivity, compiler=compiler, result=result)', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2808, in run_ast_nodes\n    if self.run_code(code, result):', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)', 'File "<ipython-input-7-6c45c8fd5ae4>", line 22, in <module>\n    tests.test_model_inputs(model_inputs)', 'File "/output/problem_unittests.py", line 106, in test_model_inputs\n    assert tf.assert_rank(lr, 0, message=\'Learning Rate has wrong rank\')', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/ops/check_ops.py", line 617, in assert_rank\n    dynamic_condition, data, summarize)', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/ops/check_ops.py", line 571, in _assert_rank_condition\n    return control_flow_ops.Assert(condition, data, summarize=summarize)', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py", line 170, in wrapped\n    return _add_should_use_warning(fn(*args, **kwargs))', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py", line 139, in _add_should_use_warning\n    wrapped = TFShouldUseWarningWrapper(x)', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py", line 96, in __init__\n    stack = [s.strip() for s in traceback.format_stack()]']
==================================
ERROR:tensorflow:==================================
Object was never used (type <class 'tensorflow.python.framework.ops.Operation'>):
<tf.Operation 'assert_rank_3/Assert/Assert' type=Assert>
If you want to mark it as used call its "mark_used()" method.
It was originally created here:
['File "/usr/local/lib/python3.5/runpy.py", line 193, in _run_module_as_main\n    "__main__", mod_spec)', 'File "/usr/local/lib/python3.5/runpy.py", line 85, in _run_code\n    exec(code, run_globals)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel_launcher.py", line 16, in <module>\n    app.launch_new_instance()', 'File "/usr/local/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance\n    app.start()', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 477, in start\n    ioloop.IOLoop.instance().start()', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start\n    super(ZMQIOLoop, self).start()', 'File "/usr/local/lib/python3.5/site-packages/tornado/ioloop.py", line 888, in start\n    handler_func(fd_obj, events)', 'File "/usr/local/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper\n    return fn(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events\n    self._handle_recv()', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv\n    self._run_callback(callback, msg)', 'File "/usr/local/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback\n    callback(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper\n    return fn(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher\n    return self.dispatch_shell(stream, msg)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell\n    handler(stream, idents, msg)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 399, in execute_request\n    user_expressions, allow_stdin)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 196, in do_execute\n    res = shell.run_cell(code, store_history=store_history, silent=silent)', 'File "/usr/local/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 533, in run_cell\n    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell\n    interactivity=interactivity, compiler=compiler, result=result)', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2808, in run_ast_nodes\n    if self.run_code(code, result):', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)', 'File "<ipython-input-7-6c45c8fd5ae4>", line 22, in <module>\n    tests.test_model_inputs(model_inputs)', 'File "/output/problem_unittests.py", line 107, in test_model_inputs\n    assert tf.assert_rank(keep_prob, 0, message=\'Keep Probability has wrong rank\')', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/ops/check_ops.py", line 617, in assert_rank\n    dynamic_condition, data, summarize)', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/ops/check_ops.py", line 571, in _assert_rank_condition\n    return control_flow_ops.Assert(condition, data, summarize=summarize)', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py", line 170, in wrapped\n    return _add_should_use_warning(fn(*args, **kwargs))', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py", line 139, in _add_should_use_warning\n    wrapped = TFShouldUseWarningWrapper(x)', 'File "/usr/local/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py", line 96, in __init__\n    stack = [s.strip() for s in traceback.format_stack()]']
==================================
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
    """
    # TODO: Implement Function
    ending = tf.strided_slice(target_data, [0,0], [batch_size, -1], [1,1])
    dec_input = tf.concat([tf.fill([batch_size, 1], target_vocab_to_int['<GO>']), ending], 1)
    
    return dec_input

"""
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 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)
    """
    
    enc_embed_input = tf.contrib.layers.embed_sequence(rnn_inputs, source_vocab_size, encoding_embedding_size)
    
    #Rnn cell
    def make_cell(rnn_size):
        cell = tf.contrib.rnn.LSTMCell(rnn_size,
                                           initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
        # add dropout layer
        enc_cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)
        return enc_cell
    
    enc_cell = tf.contrib.rnn.MultiRNNCell([make_cell(rnn_size) for _ in range(num_layers)])
    
    enc_output, enc_state = tf.nn.dynamic_rnn(enc_cell, enc_embed_input, sequence_length=source_sequence_length, dtype=tf.float32)

    
    return enc_output, enc_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 [12]:
from IPython.core.debugger import Tracer

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
    """
    # Question: Why are we receiving keep_prob here
    # Where would we add dropout layer here
    
    # Helper for the training process. Used by BasicDecoder to read inputs.
    training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input,
                                                        sequence_length=target_sequence_length,
                                                        time_major=False)

    
    # Basic decoder
    training_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell,
                                                       training_helper,
                                                       encoder_state,
                                                       output_layer) 

    # Perform dynamic decoding using the decoder
    training_decoder_output = tf.contrib.seq2seq.dynamic_decode(training_decoder,
                                                                   impute_finished=True,
                                                                   maximum_iterations=max_summary_length)[0]
    
    return training_decoder_output



"""
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 [13]:
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
    """
    # Start from GO
    start_tokens = tf.tile(tf.constant([start_of_sequence_id], dtype=tf.int32), [batch_size], name='start_tokens')

    
    # Helper for the inference process.
    inference_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings,
                                                            start_tokens,
                                                            end_of_sequence_id)

    # Basic decoder
    inference_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell,
                                                    inference_helper,
                                                    encoder_state,
                                                    output_layer)

    # Perform dynamic decoding using the decoder
    inference_decoder_output = tf.contrib.seq2seq.dynamic_decode(inference_decoder,
                                                        impute_finished=True,
                                                        maximum_iterations=max_target_sequence_length)[0]

    return inference_decoder_output



"""
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)
    """
    
    # 1. Decoder Embedding
    dec_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))
    dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input)
    
    # 2. Construct the decoder cell
    def make_cell(rnn_size):
        dec_cell = tf.contrib.rnn.LSTMCell(rnn_size,
                                           initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
        
        # Add dropout layer
        dec_cell = tf.contrib.rnn.DropoutWrapper(dec_cell, output_keep_prob=keep_prob)
        
        return dec_cell
    
    dec_cell = tf.contrib.rnn.MultiRNNCell([make_cell(rnn_size) for _ in range(num_layers)])
    
    # 3. Dense layer to translate the decoder's output at each time 
    # step into a choice from the target vocabulary
    output_layer = Dense(target_vocab_size,
                         kernel_initializer = tf.truncated_normal_initializer(mean = 0.0, stddev=0.1))
    
    
    # 4. Get training and inference outputs
    
    ## In training mode
    with tf.variable_scope('decode'):
    
        training_decoder_output = decoding_layer_train(encoder_state, 
                             dec_cell, 
                             dec_embed_input, 
                             target_sequence_length, 
                             max_target_sequence_length, 
                             output_layer, 
                             keep_prob)
    
    ## In inference mode we reuse variables
    with tf.variable_scope('decode') as scope:
        scope.reuse_variables()
        
        inference_decoder_output = decoding_layer_infer(encoder_state, 
                             dec_cell, 
                             dec_embeddings, 
                             target_vocab_to_int['<GO>'], #start of seq ID
                             target_vocab_to_int['<EOS>'],  # end of seq ID
                             max_target_sequence_length, 
                             target_vocab_size,
                             output_layer,
                             batch_size,
                             keep_prob)
    
    
    
    return training_decoder_output, inference_decoder_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)
    """
    # TODO: Implement Function
    
    
    # Pass the input data through the encoder. We'll ignore the encoder output, but use the state
    _, enc_state = encoding_layer(input_data, 
                                  rnn_size, 
                                  num_layers,
                                  keep_prob,
                                  source_sequence_length,
                                  source_vocab_size, 
                                  enc_embedding_size)
    
    # Prepare the target sequences we'll feed to the decoder in training mode
    dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size)
    
    
    # Pass encoder state and decoder inputs to the decoders
    training_decoder_output, inference_decoder_output = 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) 
    
    
    return training_decoder_output, inference_decoder_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 [16]:
# Number of Epochs
epochs = 5
# Batch Size
batch_size = 256
# RNN Size
rnn_size = 256
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 260
decoding_embedding_size = 260
# Learning Rate
learning_rate = 0.001
# Dropout Keep Probability
keep_probability = 0.5
display_step = 10
In [17]:
RUN_NUMBER = 1
LOG_DIR = '/output/run_{}/logs/'
CHECKPOINT_DIR = '/output/run_{}/checkpoints/'
CHECKPOINT_PATH = CHECKPOINT_DIR.format(RUN_NUMBER)
LOG_PATH = LOG_DIR.format(RUN_NUMBER)

Build the Graph

Build the graph using the neural network you implemented.

In [18]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
save_path = CHECKPOINT_PATH
(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)
        tf.summary.scalar('cost', cost)

        # 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)

    merged = tf.summary.merge_all()
    

Batch and pad the source and target sequences

In [19]:
"""
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
In [20]:
# write out the graph for tensorboard

with tf.Session(graph=train_graph) as sess:
    train_writer = tf.summary.FileWriter(LOG_PATH + '/train', sess.graph)
    test_writer = tf.summary.FileWriter(LOG_PATH + '/test')

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 [21]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def get_accuracy(target, logits, _type):
    """
    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')
        
    acc = np.mean(np.equal(target, logits))
    if _type is 'train':
        with tf.name_scope('optimization'):
            summary = tf.Summary(value=[tf.Summary.Value(tag="accuracy", simple_value=acc)])
    else:
        with tf.name_scope('validation'):
            summary = tf.Summary(value=[tf.Summary.Value(tag="accuracy", simple_value=acc)])
    return summary, acc

# 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())
    
    saver = tf.train.Saver(keep_checkpoint_every_n_hours=0.5)
    
    
    for epoch_i in range(epochs):
        
        
        n_batches = len(train_source)//batch_size            
        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>'])):
            
            iteration = epoch_i*n_batches + batch_i
            
            summary, _, loss = sess.run(
                [merged, 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})
            
            train_writer.add_summary(summary, iteration)
            
            if epoch_i % 5 == 0:
                saver.save(sess, save_path + 'ckpt', global_step=epoch_i)

            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_sum, train_acc = get_accuracy(target_batch, batch_train_logits, _type='train')
                                
                valid_acc_sum, valid_acc = get_accuracy(valid_targets_batch, batch_valid_logits, _type='test')
                
                
                train_writer.add_summary(train_acc_sum, iteration)
                test_writer.add_summary(valid_acc_sum, iteration)
                
               

                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.save(sess, save_path + 'last-ckpt')
    print('Model Trained and Saved')
Epoch   0 Batch   10/538 - Train Accuracy: 0.3002, Validation Accuracy: 0.3885, Loss: 3.6955
Epoch   0 Batch   20/538 - Train Accuracy: 0.3960, Validation Accuracy: 0.4355, Loss: 2.9661
Epoch   0 Batch   30/538 - Train Accuracy: 0.4240, Validation Accuracy: 0.4792, Loss: 2.8062
Epoch   0 Batch   40/538 - Train Accuracy: 0.4979, Validation Accuracy: 0.4789, Loss: 2.3624
Epoch   0 Batch   50/538 - Train Accuracy: 0.4619, Validation Accuracy: 0.4980, Loss: 2.3190
Epoch   0 Batch   60/538 - Train Accuracy: 0.4660, Validation Accuracy: 0.5165, Loss: 2.1668
Epoch   0 Batch   70/538 - Train Accuracy: 0.4650, Validation Accuracy: 0.4949, Loss: 1.9192
Epoch   0 Batch   80/538 - Train Accuracy: 0.4391, Validation Accuracy: 0.4949, Loss: 1.8879
Epoch   0 Batch   90/538 - Train Accuracy: 0.4801, Validation Accuracy: 0.5039, Loss: 1.6966
Epoch   0 Batch  100/538 - Train Accuracy: 0.4752, Validation Accuracy: 0.5099, Loss: 1.6296
Epoch   0 Batch  110/538 - Train Accuracy: 0.4352, Validation Accuracy: 0.4862, Loss: 1.5980
Epoch   0 Batch  120/538 - Train Accuracy: 0.4332, Validation Accuracy: 0.4838, Loss: 1.4634
Epoch   0 Batch  130/538 - Train Accuracy: 0.4494, Validation Accuracy: 0.4920, Loss: 1.3480
Epoch   0 Batch  140/538 - Train Accuracy: 0.4623, Validation Accuracy: 0.5130, Loss: 1.3912
Epoch   0 Batch  150/538 - Train Accuracy: 0.4697, Validation Accuracy: 0.5064, Loss: 1.2529
Epoch   0 Batch  160/538 - Train Accuracy: 0.5378, Validation Accuracy: 0.5508, Loss: 1.1481
Epoch   0 Batch  170/538 - Train Accuracy: 0.5491, Validation Accuracy: 0.5581, Loss: 1.1118
Epoch   0 Batch  180/538 - Train Accuracy: 0.5534, Validation Accuracy: 0.5476, Loss: 1.0687
Epoch   0 Batch  190/538 - Train Accuracy: 0.5234, Validation Accuracy: 0.5506, Loss: 1.0583
Epoch   0 Batch  200/538 - Train Accuracy: 0.5455, Validation Accuracy: 0.5676, Loss: 0.9990
Epoch   0 Batch  210/538 - Train Accuracy: 0.5406, Validation Accuracy: 0.5680, Loss: 0.9413
Epoch   0 Batch  220/538 - Train Accuracy: 0.5461, Validation Accuracy: 0.5843, Loss: 0.9197
Epoch   0 Batch  230/538 - Train Accuracy: 0.5428, Validation Accuracy: 0.5879, Loss: 0.9156
Epoch   0 Batch  240/538 - Train Accuracy: 0.5592, Validation Accuracy: 0.5795, Loss: 0.9008
Epoch   0 Batch  250/538 - Train Accuracy: 0.5785, Validation Accuracy: 0.5959, Loss: 0.8396
Epoch   0 Batch  260/538 - Train Accuracy: 0.5858, Validation Accuracy: 0.5989, Loss: 0.8275
Epoch   0 Batch  270/538 - Train Accuracy: 0.5781, Validation Accuracy: 0.5953, Loss: 0.8222
Epoch   0 Batch  280/538 - Train Accuracy: 0.6267, Validation Accuracy: 0.6154, Loss: 0.7569
Epoch   0 Batch  290/538 - Train Accuracy: 0.5830, Validation Accuracy: 0.6152, Loss: 0.7818
Epoch   0 Batch  300/538 - Train Accuracy: 0.6114, Validation Accuracy: 0.6170, Loss: 0.7352
Epoch   0 Batch  310/538 - Train Accuracy: 0.6029, Validation Accuracy: 0.6183, Loss: 0.7385
Epoch   0 Batch  320/538 - Train Accuracy: 0.6151, Validation Accuracy: 0.6255, Loss: 0.7263
Epoch   0 Batch  330/538 - Train Accuracy: 0.6170, Validation Accuracy: 0.6175, Loss: 0.6908
Epoch   0 Batch  340/538 - Train Accuracy: 0.5717, Validation Accuracy: 0.6213, Loss: 0.7202
Epoch   0 Batch  350/538 - Train Accuracy: 0.6075, Validation Accuracy: 0.6262, Loss: 0.6923
Epoch   0 Batch  360/538 - Train Accuracy: 0.6197, Validation Accuracy: 0.6333, Loss: 0.6942
Epoch   0 Batch  370/538 - Train Accuracy: 0.5906, Validation Accuracy: 0.6261, Loss: 0.6843
Epoch   0 Batch  380/538 - Train Accuracy: 0.6012, Validation Accuracy: 0.6374, Loss: 0.6539
Epoch   0 Batch  390/538 - Train Accuracy: 0.6603, Validation Accuracy: 0.6362, Loss: 0.6228
Epoch   0 Batch  400/538 - Train Accuracy: 0.6224, Validation Accuracy: 0.6440, Loss: 0.6205
Epoch   0 Batch  410/538 - Train Accuracy: 0.6279, Validation Accuracy: 0.6499, Loss: 0.6378
Epoch   0 Batch  420/538 - Train Accuracy: 0.6564, Validation Accuracy: 0.6273, Loss: 0.5990
Epoch   0 Batch  430/538 - Train Accuracy: 0.6490, Validation Accuracy: 0.6410, Loss: 0.5944
Epoch   0 Batch  440/538 - Train Accuracy: 0.6680, Validation Accuracy: 0.6566, Loss: 0.6338
Epoch   0 Batch  450/538 - Train Accuracy: 0.6522, Validation Accuracy: 0.6367, Loss: 0.5990
Epoch   0 Batch  460/538 - Train Accuracy: 0.6263, Validation Accuracy: 0.6557, Loss: 0.5675
Epoch   0 Batch  470/538 - Train Accuracy: 0.6847, Validation Accuracy: 0.6632, Loss: 0.5484
Epoch   0 Batch  480/538 - Train Accuracy: 0.6702, Validation Accuracy: 0.6550, Loss: 0.5310
Epoch   0 Batch  490/538 - Train Accuracy: 0.6851, Validation Accuracy: 0.6616, Loss: 0.5299
Epoch   0 Batch  500/538 - Train Accuracy: 0.7125, Validation Accuracy: 0.6777, Loss: 0.4948
Epoch   0 Batch  510/538 - Train Accuracy: 0.7161, Validation Accuracy: 0.6928, Loss: 0.5111
Epoch   0 Batch  520/538 - Train Accuracy: 0.6756, Validation Accuracy: 0.6717, Loss: 0.5343
Epoch   0 Batch  530/538 - Train Accuracy: 0.6719, Validation Accuracy: 0.6916, Loss: 0.5309
Epoch   1 Batch   10/538 - Train Accuracy: 0.6598, Validation Accuracy: 0.6651, Loss: 0.5121
Epoch   1 Batch   20/538 - Train Accuracy: 0.7059, Validation Accuracy: 0.6916, Loss: 0.5024
Epoch   1 Batch   30/538 - Train Accuracy: 0.6945, Validation Accuracy: 0.7005, Loss: 0.4938
Epoch   1 Batch   40/538 - Train Accuracy: 0.7244, Validation Accuracy: 0.7205, Loss: 0.4183
Epoch   1 Batch   50/538 - Train Accuracy: 0.7258, Validation Accuracy: 0.7227, Loss: 0.4692
Epoch   1 Batch   60/538 - Train Accuracy: 0.7250, Validation Accuracy: 0.7232, Loss: 0.4479
Epoch   1 Batch   70/538 - Train Accuracy: 0.7342, Validation Accuracy: 0.7106, Loss: 0.4234
Epoch   1 Batch   80/538 - Train Accuracy: 0.6930, Validation Accuracy: 0.7134, Loss: 0.4511
Epoch   1 Batch   90/538 - Train Accuracy: 0.7254, Validation Accuracy: 0.7244, Loss: 0.4251
Epoch   1 Batch  100/538 - Train Accuracy: 0.7746, Validation Accuracy: 0.7441, Loss: 0.3935
Epoch   1 Batch  110/538 - Train Accuracy: 0.7248, Validation Accuracy: 0.7354, Loss: 0.4242
Epoch   1 Batch  120/538 - Train Accuracy: 0.7604, Validation Accuracy: 0.7431, Loss: 0.3804
Epoch   1 Batch  130/538 - Train Accuracy: 0.7779, Validation Accuracy: 0.7353, Loss: 0.3716
Epoch   1 Batch  140/538 - Train Accuracy: 0.7469, Validation Accuracy: 0.7411, Loss: 0.4122
Epoch   1 Batch  150/538 - Train Accuracy: 0.7646, Validation Accuracy: 0.7475, Loss: 0.3716
Epoch   1 Batch  160/538 - Train Accuracy: 0.7413, Validation Accuracy: 0.7488, Loss: 0.3484
Epoch   1 Batch  170/538 - Train Accuracy: 0.7809, Validation Accuracy: 0.7473, Loss: 0.3566
Epoch   1 Batch  180/538 - Train Accuracy: 0.7853, Validation Accuracy: 0.7710, Loss: 0.3506
Epoch   1 Batch  190/538 - Train Accuracy: 0.7781, Validation Accuracy: 0.7884, Loss: 0.3540
Epoch   1 Batch  200/538 - Train Accuracy: 0.7994, Validation Accuracy: 0.7729, Loss: 0.3315
Epoch   1 Batch  210/538 - Train Accuracy: 0.7920, Validation Accuracy: 0.7990, Loss: 0.3154
Epoch   1 Batch  220/538 - Train Accuracy: 0.7798, Validation Accuracy: 0.7930, Loss: 0.3094
Epoch   1 Batch  230/538 - Train Accuracy: 0.8049, Validation Accuracy: 0.7884, Loss: 0.3151
Epoch   1 Batch  240/538 - Train Accuracy: 0.8084, Validation Accuracy: 0.7898, Loss: 0.3224
Epoch   1 Batch  250/538 - Train Accuracy: 0.8141, Validation Accuracy: 0.7791, Loss: 0.3067
Epoch   1 Batch  260/538 - Train Accuracy: 0.8039, Validation Accuracy: 0.7994, Loss: 0.3074
Epoch   1 Batch  270/538 - Train Accuracy: 0.8023, Validation Accuracy: 0.8104, Loss: 0.2979
Epoch   1 Batch  280/538 - Train Accuracy: 0.8402, Validation Accuracy: 0.8226, Loss: 0.2656
Epoch   1 Batch  290/538 - Train Accuracy: 0.8338, Validation Accuracy: 0.8349, Loss: 0.2634
Epoch   1 Batch  300/538 - Train Accuracy: 0.8153, Validation Accuracy: 0.8221, Loss: 0.2657
Epoch   1 Batch  310/538 - Train Accuracy: 0.8773, Validation Accuracy: 0.8292, Loss: 0.2728
Epoch   1 Batch  320/538 - Train Accuracy: 0.8304, Validation Accuracy: 0.8379, Loss: 0.2527
Epoch   1 Batch  330/538 - Train Accuracy: 0.8346, Validation Accuracy: 0.8303, Loss: 0.2402
Epoch   1 Batch  340/538 - Train Accuracy: 0.8539, Validation Accuracy: 0.8530, Loss: 0.2550
Epoch   1 Batch  350/538 - Train Accuracy: 0.8564, Validation Accuracy: 0.8331, Loss: 0.2609
Epoch   1 Batch  360/538 - Train Accuracy: 0.8438, Validation Accuracy: 0.8459, Loss: 0.2485
Epoch   1 Batch  370/538 - Train Accuracy: 0.8422, Validation Accuracy: 0.8427, Loss: 0.2579
Epoch   1 Batch  380/538 - Train Accuracy: 0.8684, Validation Accuracy: 0.8526, Loss: 0.2178
Epoch   1 Batch  390/538 - Train Accuracy: 0.8994, Validation Accuracy: 0.8661, Loss: 0.2011
Epoch   1 Batch  400/538 - Train Accuracy: 0.8687, Validation Accuracy: 0.8601, Loss: 0.2281
Epoch   1 Batch  410/538 - Train Accuracy: 0.8727, Validation Accuracy: 0.8610, Loss: 0.2327
Epoch   1 Batch  420/538 - Train Accuracy: 0.8832, Validation Accuracy: 0.8642, Loss: 0.2038
Epoch   1 Batch  430/538 - Train Accuracy: 0.8641, Validation Accuracy: 0.8608, Loss: 0.2079
Epoch   1 Batch  440/538 - Train Accuracy: 0.8586, Validation Accuracy: 0.8743, Loss: 0.2274
Epoch   1 Batch  450/538 - Train Accuracy: 0.8555, Validation Accuracy: 0.8489, Loss: 0.2110
Epoch   1 Batch  460/538 - Train Accuracy: 0.8590, Validation Accuracy: 0.8661, Loss: 0.2009
Epoch   1 Batch  470/538 - Train Accuracy: 0.8910, Validation Accuracy: 0.8786, Loss: 0.1802
Epoch   1 Batch  480/538 - Train Accuracy: 0.9007, Validation Accuracy: 0.8564, Loss: 0.1726
Epoch   1 Batch  490/538 - Train Accuracy: 0.8858, Validation Accuracy: 0.8729, Loss: 0.1721
Epoch   1 Batch  500/538 - Train Accuracy: 0.9032, Validation Accuracy: 0.8848, Loss: 0.1630
Epoch   1 Batch  510/538 - Train Accuracy: 0.8923, Validation Accuracy: 0.8812, Loss: 0.1686
Epoch   1 Batch  520/538 - Train Accuracy: 0.8877, Validation Accuracy: 0.8807, Loss: 0.1807
Epoch   1 Batch  530/538 - Train Accuracy: 0.8719, Validation Accuracy: 0.8919, Loss: 0.1775
Epoch   2 Batch   10/538 - Train Accuracy: 0.8943, Validation Accuracy: 0.8833, Loss: 0.1768
Epoch   2 Batch   20/538 - Train Accuracy: 0.9003, Validation Accuracy: 0.8975, Loss: 0.1649
Epoch   2 Batch   30/538 - Train Accuracy: 0.8777, Validation Accuracy: 0.8794, Loss: 0.1737
Epoch   2 Batch   40/538 - Train Accuracy: 0.9002, Validation Accuracy: 0.8903, Loss: 0.1366
Epoch   2 Batch   50/538 - Train Accuracy: 0.8979, Validation Accuracy: 0.9062, Loss: 0.1507
Epoch   2 Batch   60/538 - Train Accuracy: 0.9189, Validation Accuracy: 0.8782, Loss: 0.1457
Epoch   2 Batch   70/538 - Train Accuracy: 0.9040, Validation Accuracy: 0.8890, Loss: 0.1353
Epoch   2 Batch   80/538 - Train Accuracy: 0.8957, Validation Accuracy: 0.8880, Loss: 0.1490
Epoch   2 Batch   90/538 - Train Accuracy: 0.8865, Validation Accuracy: 0.8857, Loss: 0.1564
Epoch   2 Batch  100/538 - Train Accuracy: 0.9148, Validation Accuracy: 0.8975, Loss: 0.1301
Epoch   2 Batch  110/538 - Train Accuracy: 0.9000, Validation Accuracy: 0.8961, Loss: 0.1463
Epoch   2 Batch  120/538 - Train Accuracy: 0.9225, Validation Accuracy: 0.8929, Loss: 0.1330
Epoch   2 Batch  130/538 - Train Accuracy: 0.9167, Validation Accuracy: 0.8938, Loss: 0.1224
Epoch   2 Batch  140/538 - Train Accuracy: 0.8850, Validation Accuracy: 0.9027, Loss: 0.1490
Epoch   2 Batch  150/538 - Train Accuracy: 0.9227, Validation Accuracy: 0.9036, Loss: 0.1205
Epoch   2 Batch  160/538 - Train Accuracy: 0.8951, Validation Accuracy: 0.9013, Loss: 0.1173
Epoch   2 Batch  170/538 - Train Accuracy: 0.9022, Validation Accuracy: 0.8952, Loss: 0.1259
Epoch   2 Batch  180/538 - Train Accuracy: 0.9142, Validation Accuracy: 0.9048, Loss: 0.1225
Epoch   2 Batch  190/538 - Train Accuracy: 0.8973, Validation Accuracy: 0.8922, Loss: 0.1413
Epoch   2 Batch  200/538 - Train Accuracy: 0.9115, Validation Accuracy: 0.8938, Loss: 0.1011
Epoch   2 Batch  210/538 - Train Accuracy: 0.8906, Validation Accuracy: 0.9109, Loss: 0.1198
Epoch   2 Batch  220/538 - Train Accuracy: 0.9049, Validation Accuracy: 0.8967, Loss: 0.1083
Epoch   2 Batch  230/538 - Train Accuracy: 0.9115, Validation Accuracy: 0.9043, Loss: 0.1163
Epoch   2 Batch  240/538 - Train Accuracy: 0.8994, Validation Accuracy: 0.9043, Loss: 0.1244
Epoch   2 Batch  250/538 - Train Accuracy: 0.9187, Validation Accuracy: 0.9041, Loss: 0.1043
Epoch   2 Batch  260/538 - Train Accuracy: 0.8854, Validation Accuracy: 0.9167, Loss: 0.1173
Epoch   2 Batch  270/538 - Train Accuracy: 0.9098, Validation Accuracy: 0.9023, Loss: 0.1026
Epoch   2 Batch  280/538 - Train Accuracy: 0.9276, Validation Accuracy: 0.9128, Loss: 0.1005
Epoch   2 Batch  290/538 - Train Accuracy: 0.9283, Validation Accuracy: 0.9109, Loss: 0.0956
Epoch   2 Batch  300/538 - Train Accuracy: 0.9031, Validation Accuracy: 0.9087, Loss: 0.1090
Epoch   2 Batch  310/538 - Train Accuracy: 0.9424, Validation Accuracy: 0.9032, Loss: 0.1099
Epoch   2 Batch  320/538 - Train Accuracy: 0.9044, Validation Accuracy: 0.9102, Loss: 0.1009
Epoch   2 Batch  330/538 - Train Accuracy: 0.9115, Validation Accuracy: 0.9155, Loss: 0.0948
Epoch   2 Batch  340/538 - Train Accuracy: 0.9164, Validation Accuracy: 0.9162, Loss: 0.0972
Epoch   2 Batch  350/538 - Train Accuracy: 0.9336, Validation Accuracy: 0.9197, Loss: 0.1178
Epoch   2 Batch  360/538 - Train Accuracy: 0.9156, Validation Accuracy: 0.9112, Loss: 0.1010
Epoch   2 Batch  370/538 - Train Accuracy: 0.9375, Validation Accuracy: 0.9240, Loss: 0.0992
Epoch   2 Batch  380/538 - Train Accuracy: 0.9258, Validation Accuracy: 0.9103, Loss: 0.0927
Epoch   2 Batch  390/538 - Train Accuracy: 0.9306, Validation Accuracy: 0.9194, Loss: 0.0812
Epoch   2 Batch  400/538 - Train Accuracy: 0.9280, Validation Accuracy: 0.9132, Loss: 0.0971
Epoch   2 Batch  410/538 - Train Accuracy: 0.9201, Validation Accuracy: 0.9215, Loss: 0.1057
Epoch   2 Batch  420/538 - Train Accuracy: 0.9252, Validation Accuracy: 0.9132, Loss: 0.0920
Epoch   2 Batch  430/538 - Train Accuracy: 0.9156, Validation Accuracy: 0.9329, Loss: 0.0862
Epoch   2 Batch  440/538 - Train Accuracy: 0.9209, Validation Accuracy: 0.9165, Loss: 0.0949
Epoch   2 Batch  450/538 - Train Accuracy: 0.9089, Validation Accuracy: 0.9048, Loss: 0.1095
Epoch   2 Batch  460/538 - Train Accuracy: 0.9042, Validation Accuracy: 0.9219, Loss: 0.0971
Epoch   2 Batch  470/538 - Train Accuracy: 0.9312, Validation Accuracy: 0.9066, Loss: 0.0836
Epoch   2 Batch  480/538 - Train Accuracy: 0.9399, Validation Accuracy: 0.9205, Loss: 0.0793
Epoch   2 Batch  490/538 - Train Accuracy: 0.9373, Validation Accuracy: 0.9297, Loss: 0.0801
Epoch   2 Batch  500/538 - Train Accuracy: 0.9368, Validation Accuracy: 0.9114, Loss: 0.0709
Epoch   2 Batch  510/538 - Train Accuracy: 0.9474, Validation Accuracy: 0.9283, Loss: 0.0799
Epoch   2 Batch  520/538 - Train Accuracy: 0.9313, Validation Accuracy: 0.9176, Loss: 0.0847
Epoch   2 Batch  530/538 - Train Accuracy: 0.9039, Validation Accuracy: 0.9155, Loss: 0.0907
Epoch   3 Batch   10/538 - Train Accuracy: 0.9393, Validation Accuracy: 0.9096, Loss: 0.0886
Epoch   3 Batch   20/538 - Train Accuracy: 0.9271, Validation Accuracy: 0.9194, Loss: 0.0780
Epoch   3 Batch   30/538 - Train Accuracy: 0.9258, Validation Accuracy: 0.9027, Loss: 0.0883
Epoch   3 Batch   40/538 - Train Accuracy: 0.9295, Validation Accuracy: 0.9228, Loss: 0.0671
Epoch   3 Batch   50/538 - Train Accuracy: 0.9236, Validation Accuracy: 0.9137, Loss: 0.0772
Epoch   3 Batch   60/538 - Train Accuracy: 0.9363, Validation Accuracy: 0.9238, Loss: 0.0739
Epoch   3 Batch   70/538 - Train Accuracy: 0.9237, Validation Accuracy: 0.9215, Loss: 0.0715
Epoch   3 Batch   80/538 - Train Accuracy: 0.9256, Validation Accuracy: 0.9196, Loss: 0.0774
Epoch   3 Batch   90/538 - Train Accuracy: 0.9362, Validation Accuracy: 0.9132, Loss: 0.0828
Epoch   3 Batch  100/538 - Train Accuracy: 0.9453, Validation Accuracy: 0.9189, Loss: 0.0651
Epoch   3 Batch  110/538 - Train Accuracy: 0.9301, Validation Accuracy: 0.9206, Loss: 0.0758
Epoch   3 Batch  120/538 - Train Accuracy: 0.9428, Validation Accuracy: 0.9244, Loss: 0.0613
Epoch   3 Batch  130/538 - Train Accuracy: 0.9384, Validation Accuracy: 0.9256, Loss: 0.0720
Epoch   3 Batch  140/538 - Train Accuracy: 0.9145, Validation Accuracy: 0.9267, Loss: 0.0938
Epoch   3 Batch  150/538 - Train Accuracy: 0.9373, Validation Accuracy: 0.9366, Loss: 0.0668
Epoch   3 Batch  160/538 - Train Accuracy: 0.9202, Validation Accuracy: 0.9210, Loss: 0.0660
Epoch   3 Batch  170/538 - Train Accuracy: 0.9213, Validation Accuracy: 0.9288, Loss: 0.0789
Epoch   3 Batch  180/538 - Train Accuracy: 0.9343, Validation Accuracy: 0.9292, Loss: 0.0717
Epoch   3 Batch  190/538 - Train Accuracy: 0.9081, Validation Accuracy: 0.9174, Loss: 0.0896
Epoch   3 Batch  200/538 - Train Accuracy: 0.9447, Validation Accuracy: 0.9258, Loss: 0.0563
Epoch   3 Batch  210/538 - Train Accuracy: 0.9355, Validation Accuracy: 0.9412, Loss: 0.0726
Epoch   3 Batch  220/538 - Train Accuracy: 0.9167, Validation Accuracy: 0.9334, Loss: 0.0654
Epoch   3 Batch  230/538 - Train Accuracy: 0.9230, Validation Accuracy: 0.9192, Loss: 0.0697
Epoch   3 Batch  240/538 - Train Accuracy: 0.9172, Validation Accuracy: 0.9272, Loss: 0.0713
Epoch   3 Batch  250/538 - Train Accuracy: 0.9494, Validation Accuracy: 0.9274, Loss: 0.0620
Epoch   3 Batch  260/538 - Train Accuracy: 0.9172, Validation Accuracy: 0.9219, Loss: 0.0720
Epoch   3 Batch  270/538 - Train Accuracy: 0.9465, Validation Accuracy: 0.9347, Loss: 0.0710
Epoch   3 Batch  280/538 - Train Accuracy: 0.9488, Validation Accuracy: 0.9086, Loss: 0.0637
Epoch   3 Batch  290/538 - Train Accuracy: 0.9414, Validation Accuracy: 0.9258, Loss: 0.0536
Epoch   3 Batch  300/538 - Train Accuracy: 0.9362, Validation Accuracy: 0.9196, Loss: 0.0745
Epoch   3 Batch  310/538 - Train Accuracy: 0.9510, Validation Accuracy: 0.9286, Loss: 0.0677
Epoch   3 Batch  320/538 - Train Accuracy: 0.9353, Validation Accuracy: 0.9386, Loss: 0.0688
Epoch   3 Batch  330/538 - Train Accuracy: 0.9334, Validation Accuracy: 0.9338, Loss: 0.0605
Epoch   3 Batch  340/538 - Train Accuracy: 0.9221, Validation Accuracy: 0.9276, Loss: 0.0685
Epoch   3 Batch  350/538 - Train Accuracy: 0.9399, Validation Accuracy: 0.9332, Loss: 0.0599
Epoch   3 Batch  360/538 - Train Accuracy: 0.9377, Validation Accuracy: 0.9458, Loss: 0.0652
Epoch   3 Batch  370/538 - Train Accuracy: 0.9437, Validation Accuracy: 0.9284, Loss: 0.0641
Epoch   3 Batch  380/538 - Train Accuracy: 0.9459, Validation Accuracy: 0.9398, Loss: 0.0615
Epoch   3 Batch  390/538 - Train Accuracy: 0.9468, Validation Accuracy: 0.9490, Loss: 0.0536
Epoch   3 Batch  400/538 - Train Accuracy: 0.9464, Validation Accuracy: 0.9304, Loss: 0.0583
Epoch   3 Batch  410/538 - Train Accuracy: 0.9502, Validation Accuracy: 0.9426, Loss: 0.0672
Epoch   3 Batch  420/538 - Train Accuracy: 0.9510, Validation Accuracy: 0.9416, Loss: 0.0593
Epoch   3 Batch  430/538 - Train Accuracy: 0.9355, Validation Accuracy: 0.9370, Loss: 0.0615
Epoch   3 Batch  440/538 - Train Accuracy: 0.9391, Validation Accuracy: 0.9329, Loss: 0.0732
Epoch   3 Batch  450/538 - Train Accuracy: 0.9258, Validation Accuracy: 0.9483, Loss: 0.0722
Epoch   3 Batch  460/538 - Train Accuracy: 0.9278, Validation Accuracy: 0.9336, Loss: 0.0666
Epoch   3 Batch  470/538 - Train Accuracy: 0.9524, Validation Accuracy: 0.9382, Loss: 0.0591
Epoch   3 Batch  480/538 - Train Accuracy: 0.9464, Validation Accuracy: 0.9288, Loss: 0.0622
Epoch   3 Batch  490/538 - Train Accuracy: 0.9420, Validation Accuracy: 0.9208, Loss: 0.0564
Epoch   3 Batch  500/538 - Train Accuracy: 0.9673, Validation Accuracy: 0.9219, Loss: 0.0608
Epoch   3 Batch  510/538 - Train Accuracy: 0.9487, Validation Accuracy: 0.9396, Loss: 0.0625
Epoch   3 Batch  520/538 - Train Accuracy: 0.9352, Validation Accuracy: 0.9231, Loss: 0.0610
Epoch   3 Batch  530/538 - Train Accuracy: 0.9221, Validation Accuracy: 0.9405, Loss: 0.0664
Epoch   4 Batch   10/538 - Train Accuracy: 0.9418, Validation Accuracy: 0.9480, Loss: 0.0639
Epoch   4 Batch   20/538 - Train Accuracy: 0.9501, Validation Accuracy: 0.9364, Loss: 0.0593
Epoch   4 Batch   30/538 - Train Accuracy: 0.9477, Validation Accuracy: 0.9409, Loss: 0.0579
Epoch   4 Batch   40/538 - Train Accuracy: 0.9411, Validation Accuracy: 0.9490, Loss: 0.0446
Epoch   4 Batch   50/538 - Train Accuracy: 0.9486, Validation Accuracy: 0.9398, Loss: 0.0528
Epoch   4 Batch   60/538 - Train Accuracy: 0.9490, Validation Accuracy: 0.9338, Loss: 0.0595
Epoch   4 Batch   70/538 - Train Accuracy: 0.9611, Validation Accuracy: 0.9345, Loss: 0.0431
Epoch   4 Batch   80/538 - Train Accuracy: 0.9496, Validation Accuracy: 0.9467, Loss: 0.0569
Epoch   4 Batch   90/538 - Train Accuracy: 0.9548, Validation Accuracy: 0.9545, Loss: 0.0565
Epoch   4 Batch  100/538 - Train Accuracy: 0.9693, Validation Accuracy: 0.9416, Loss: 0.0468
Epoch   4 Batch  110/538 - Train Accuracy: 0.9477, Validation Accuracy: 0.9325, Loss: 0.0519
Epoch   4 Batch  120/538 - Train Accuracy: 0.9596, Validation Accuracy: 0.9471, Loss: 0.0380
Epoch   4 Batch  130/538 - Train Accuracy: 0.9542, Validation Accuracy: 0.9373, Loss: 0.0409
Epoch   4 Batch  140/538 - Train Accuracy: 0.9229, Validation Accuracy: 0.9272, Loss: 0.0687
Epoch   4 Batch  150/538 - Train Accuracy: 0.9510, Validation Accuracy: 0.9471, Loss: 0.0444
Epoch   4 Batch  160/538 - Train Accuracy: 0.9221, Validation Accuracy: 0.9252, Loss: 0.0451
Epoch   4 Batch  170/538 - Train Accuracy: 0.9345, Validation Accuracy: 0.9460, Loss: 0.0549
Epoch   4 Batch  180/538 - Train Accuracy: 0.9420, Validation Accuracy: 0.9416, Loss: 0.0512
Epoch   4 Batch  190/538 - Train Accuracy: 0.9241, Validation Accuracy: 0.9267, Loss: 0.0738
Epoch   4 Batch  200/538 - Train Accuracy: 0.9672, Validation Accuracy: 0.9430, Loss: 0.0420
Epoch   4 Batch  210/538 - Train Accuracy: 0.9472, Validation Accuracy: 0.9467, Loss: 0.0544
Epoch   4 Batch  220/538 - Train Accuracy: 0.9384, Validation Accuracy: 0.9377, Loss: 0.0508
Epoch   4 Batch  230/538 - Train Accuracy: 0.9449, Validation Accuracy: 0.9403, Loss: 0.0480
Epoch   4 Batch  240/538 - Train Accuracy: 0.9383, Validation Accuracy: 0.9325, Loss: 0.0475
Epoch   4 Batch  250/538 - Train Accuracy: 0.9588, Validation Accuracy: 0.9434, Loss: 0.0499
Epoch   4 Batch  260/538 - Train Accuracy: 0.9340, Validation Accuracy: 0.9384, Loss: 0.0525
Epoch   4 Batch  270/538 - Train Accuracy: 0.9498, Validation Accuracy: 0.9400, Loss: 0.0432
Epoch   4 Batch  280/538 - Train Accuracy: 0.9511, Validation Accuracy: 0.9373, Loss: 0.0405
Epoch   4 Batch  290/538 - Train Accuracy: 0.9777, Validation Accuracy: 0.9345, Loss: 0.0382
Epoch   4 Batch  300/538 - Train Accuracy: 0.9520, Validation Accuracy: 0.9569, Loss: 0.0495
Epoch   4 Batch  310/538 - Train Accuracy: 0.9652, Validation Accuracy: 0.9570, Loss: 0.0517
Epoch   4 Batch  320/538 - Train Accuracy: 0.9528, Validation Accuracy: 0.9485, Loss: 0.0477
Epoch   4 Batch  330/538 - Train Accuracy: 0.9621, Validation Accuracy: 0.9474, Loss: 0.0446
Epoch   4 Batch  340/538 - Train Accuracy: 0.9430, Validation Accuracy: 0.9425, Loss: 0.0472
Epoch   4 Batch  350/538 - Train Accuracy: 0.9555, Validation Accuracy: 0.9501, Loss: 0.0529
Epoch   4 Batch  360/538 - Train Accuracy: 0.9471, Validation Accuracy: 0.9567, Loss: 0.0441
Epoch   4 Batch  370/538 - Train Accuracy: 0.9637, Validation Accuracy: 0.9501, Loss: 0.0498
Epoch   4 Batch  380/538 - Train Accuracy: 0.9516, Validation Accuracy: 0.9565, Loss: 0.0451
Epoch   4 Batch  390/538 - Train Accuracy: 0.9461, Validation Accuracy: 0.9522, Loss: 0.0348
Epoch   4 Batch  400/538 - Train Accuracy: 0.9680, Validation Accuracy: 0.9600, Loss: 0.0426
Epoch   4 Batch  410/538 - Train Accuracy: 0.9588, Validation Accuracy: 0.9494, Loss: 0.0504
Epoch   4 Batch  420/538 - Train Accuracy: 0.9525, Validation Accuracy: 0.9542, Loss: 0.0439
Epoch   4 Batch  430/538 - Train Accuracy: 0.9389, Validation Accuracy: 0.9517, Loss: 0.0446
Epoch   4 Batch  440/538 - Train Accuracy: 0.9537, Validation Accuracy: 0.9510, Loss: 0.0538
Epoch   4 Batch  450/538 - Train Accuracy: 0.9299, Validation Accuracy: 0.9513, Loss: 0.0570
Epoch   4 Batch  460/538 - Train Accuracy: 0.9472, Validation Accuracy: 0.9576, Loss: 0.0453
Epoch   4 Batch  470/538 - Train Accuracy: 0.9550, Validation Accuracy: 0.9547, Loss: 0.0474
Epoch   4 Batch  480/538 - Train Accuracy: 0.9678, Validation Accuracy: 0.9487, Loss: 0.0453
Epoch   4 Batch  490/538 - Train Accuracy: 0.9528, Validation Accuracy: 0.9556, Loss: 0.0409
Epoch   4 Batch  500/538 - Train Accuracy: 0.9686, Validation Accuracy: 0.9627, Loss: 0.0355
Epoch   4 Batch  510/538 - Train Accuracy: 0.9513, Validation Accuracy: 0.9480, Loss: 0.0488
Epoch   4 Batch  520/538 - Train Accuracy: 0.9535, Validation Accuracy: 0.9565, Loss: 0.0444
Epoch   4 Batch  530/538 - Train Accuracy: 0.9363, Validation Accuracy: 0.9498, Loss: 0.0512
Model Trained and Saved

Save Parameters

Save the batch_size and save_path parameters for inference.

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

Checkpoint

In [23]:
"""
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 [24]:
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
    """
      
    
    return [vocab_to_int.get(word, vocab_to_int['<UNK>']) for word in sentence.lower().split(' ')]



"""
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 [27]:
translate_sentence = 'he saw a old yellow truck .'


"""
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 + 'last-ckpt.meta')
    loader.restore(sess, load_path + 'last-ckpt')

    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 /output/run_1/checkpoints/last-ckpt
Input
  Word Ids:      [161, 156, 158, 103, 42, 112, 169]
  English Words: ['he', 'saw', 'a', 'old', 'yellow', 'truck', '.']

Prediction
  Word Ids:      [224, 237, 230, 340, 282, 78, 64, 1]
  French Words: il a un vieux camion jaune . <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.