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)

In [2]:
#Test
print(source_text[:100])
unique_words = set([word for word in source_text.split()])
print("Roughly number of words:{}".format(len(unique_words)))


new jersey is sometimes quiet during autumn , and it is snowy in april .
the united states is usuall
Roughly number of words:227

Explore the Data

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


In [3]:
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()})))

source_sentences = source_text.split('\n')
target_sentences = target_text.split('\n')

word_counts = [len(sentence.split()) for sentence in source_sentences]
print('Number of sentences: {}'.format(len(source_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_sentences[view_sentence_range[0]:view_sentence_range[1]]))
print()
print('French sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(target_sentences[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 [4]:
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)
    """
    # TODO: Implement Function
    source_id_text = [[source_vocab_to_int[word] for word in sentence.split()] for sentence in source_text.split("\n")]
    target_id_text = [[target_vocab_to_int[word] for word in sentence.split()+['<EOS>']] for sentence in target_text.split("\n")]
    
    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 [5]:
"""
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 [6]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
import helper

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

In [7]:
print(source_int_text[:10])


[[155, 88, 56, 57, 111, 221, 17, 120, 169, 4, 56, 183, 82, 188, 18], [84, 210, 195, 56, 14, 167, 221, 19, 120, 169, 4, 56, 14, 72, 82, 63, 18], [224, 56, 14, 111, 221, 49, 120, 169, 4, 56, 14, 42, 82, 126, 18], [84, 210, 195, 56, 57, 76, 221, 126, 120, 169, 4, 56, 166, 82, 207, 18], [122, 152, 141, 117, 56, 84, 103, 120, 174, 106, 152, 141, 56, 84, 214, 18], [22, 11, 117, 56, 84, 147, 120, 174, 106, 11, 56, 84, 103, 18], [5, 56, 185, 221, 199, 120, 174, 4, 56, 14, 167, 82, 19, 18], [155, 88, 56, 43, 221, 203, 120, 169, 4, 56, 50, 42, 82, 49, 18], [113, 152, 141, 117, 56, 84, 132, 120, 174, 106, 152, 141, 56, 84, 103, 18], [84, 210, 195, 56, 57, 43, 221, 28, 120, 169, 4, 56, 57, 44, 82, 63, 18]]

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 [8]:
"""
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.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 tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length)


In [9]:
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)
    """
    # TODO: Implement Function
    input_ = tf.placeholder(tf.int32, (None, None), name="input")
    targets_ = tf.placeholder(tf.int32, (None, None))
    learning_rate = tf.placeholder(tf.float32)
    keep_prob = 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")
    src_seq_len = tf.placeholder(tf.int32, (None,), name="source_sequence_length")
    
    return input_, targets_, learning_rate, keep_prob, target_seq_len, max_target_seq_len, src_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 2683, in run_cell\n    interactivity=interactivity, compiler=compiler, result=result)', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2793, in run_ast_nodes\n    if self.run_code(code, result):', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2847, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)', 'File "<ipython-input-9-2a3b05a2f1cc>", 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 2683, in run_cell\n    interactivity=interactivity, compiler=compiler, result=result)', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2793, in run_ast_nodes\n    if self.run_code(code, result):', 'File "/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2847, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)', 'File "<ipython-input-9-2a3b05a2f1cc>", 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. If the target_data batch is:

[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

And GO ID is 100.Then the preprocessed data should be:

[[100,1,2],[100,4,5],[100,7,8],[100,10,11]]


In [10]:
def process_decoder_input(target_data, target_vocab_to_int, batch_size):
    """
    Preprocess target data for encoding
    :param target_data: Target Placeholder
    :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
    go_id = target_vocab_to_int["<GO>"]
    batch_target = tf.strided_slice(target_data, [0,0], [batch_size,-1], [1,1])
    pre_target = tf.concat([tf.fill((batch_size,1), go_id), batch_target], axis=1)
    
    return pre_target

"""
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 [11]:
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)
    """
    # TODO: Implement Function
    # Encoder Embedding
    embed_input = tf.contrib.layers.embed_sequence(rnn_inputs, source_vocab_size, encoding_embedding_size)
    
    # RNN Cell
    layer = []    
    for i in range(num_layers):
        lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.truncated_normal_initializer(stddev=0.1))
        drop = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=keep_prob)
        layer.append(drop)
    enc_cell = tf.contrib.rnn.MultiRNNCell(layer)
    output_enc, state_enc = tf.nn.dynamic_rnn(enc_cell, embed_input, sequence_length=source_sequence_length, dtype=tf.float32)
    
    return output_enc, state_enc

"""
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]:
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, 
                         target_sequence_length, max_target_sequence_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
    """
    # TODO: Implement Function
    # Dropout Cell
    decode_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input,\
                                                      sequence_length=target_sequence_length)
    dec_train_cell = tf.contrib.rnn.DropoutWrapper(cell=dec_cell, output_keep_prob=keep_prob)
    train_decoder = tf.contrib.seq2seq.BasicDecoder(cell=dec_train_cell,\
                                                    helper=decode_helper,\
                                                    initial_state=encoder_state,\
                                                    output_layer=output_layer)
    decoder_train_output, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder=train_decoder,\
                                                                   impute_finished=True,\
                                                                   maximum_iterations=max_target_sequence_length)
    
    return decoder_train_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
    """
    # TODO: Implement Function    
    start_tokens = tf.tile(tf.constant([start_of_sequence_id], dtype=tf.int32), [batch_size])
    
    infer_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embedding=dec_embeddings,\
                                                            start_tokens=start_tokens,\
                                                            end_token=end_of_sequence_id)
    dec_infer_cell = tf.contrib.rnn.DropoutWrapper(cell=dec_cell, input_keep_prob=keep_prob)
    decoder_infer = tf.contrib.seq2seq.BasicDecoder(cell=dec_infer_cell,\
                                                    helper=infer_helper,\
                                                    initial_state=encoder_state,\
                                                    output_layer=output_layer)
    dec_infer_output,_,_ = tf.contrib.seq2seq.dynamic_decode(decoder=decoder_infer,\
                                                         impute_finished=True,\
                                                         maximum_iterations=max_target_sequence_length)
    
    
    return dec_infer_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)
    """
    # TODO: Implement Function
    # Embed Input of Training Decoder
    dec_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))
    embed_input = tf.nn.embedding_lookup(params=dec_embeddings, ids=dec_input)
   
    #Build RNN Cell   
    lstm_layer = []
    for i in range(num_layers):
        cell = tf.contrib.rnn.BasicLSTMCell(num_units=rnn_size)
        lstm_layer.append(cell)
    cell = tf.contrib.rnn.MultiRNNCell(lstm_layer)
    
    #Dense Layer
    output_layer = tf.contrib.keras.layers.Dense(units=target_vocab_size,\
                                                 kernel_initializer=tf.truncated_normal_initializer(stddev=0.1))
    
    #Construct RNN Cell    
    with tf.variable_scope(name_or_scope="decode"):
        logits_decode_train = decoding_layer_train(encoder_state=encoder_state,\
                                                   dec_cell=cell,\
                                                   dec_embed_input=embed_input,\
                                                   target_sequence_length=target_sequence_length,
                                                   max_target_sequence_length=max_target_sequence_length,\
                                                   output_layer=output_layer,\
                                                   keep_prob=keep_prob)
    with tf.variable_scope(name_or_scope="decode",reuse=True):
        logits_decode_infer = decoding_layer_infer(encoder_state=encoder_state,\
                                                   dec_cell=cell,\
                                                   dec_embeddings=dec_embeddings,\
                                                   start_of_sequence_id=target_vocab_to_int["<GO>"],\
                                                   end_of_sequence_id=target_vocab_to_int["<EOS>"],\
                                                   max_target_sequence_length=max_target_sequence_length,\
                                                   vocab_size=target_vocab_size,\
                                                   output_layer=output_layer,\
                                                   batch_size=batch_size,\
                                                   keep_prob=keep_prob)
    
    return logits_decode_train, logits_decode_infer


"""
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 [16]:
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
    output_enc, state_enc = encoding_layer(rnn_inputs=input_data,\
                                           rnn_size=rnn_size,\
                                           num_layers=num_layers,\
                                           keep_prob=keep_prob,\
                                           source_sequence_length=source_sequence_length,\
                                           source_vocab_size=source_vocab_size,\
                                           encoding_embedding_size=enc_embedding_size)
    dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size) 
    logits_train, logits_infer = decoding_layer(dec_input=dec_input,\
                                                encoder_state=state_enc,\
                                                target_sequence_length=target_sequence_length,\
                                                max_target_sequence_length=max_target_sentence_length,\
                                                rnn_size=rnn_size,\
                                                num_layers=num_layers,\
                                                target_vocab_to_int=target_vocab_to_int,\
                                                target_vocab_size=target_vocab_size,\
                                                batch_size=batch_size,\
                                                keep_prob=keep_prob,\
                                                decoding_embedding_size=dec_embedding_size)
    
    
    return logits_train, logits_infer


"""
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 [17]:
# Number of Epochs
epochs = 10
# Batch Size
batch_size = 256
# RNN Size
rnn_size = 256
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 30
decoding_embedding_size = 30
# Learning Rate
learning_rate = 0.005
# Dropout Keep Probability
keep_probability = 0.5
display_step = 20

Build the Graph

Build the graph using the neural network you implemented.


In [18]:
"""
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 [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

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 [20]:
"""
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   20/538 - Train Accuracy: 0.3372, Validation Accuracy: 0.3853, Loss: 3.2281
Epoch   0 Batch   40/538 - Train Accuracy: 0.4615, Validation Accuracy: 0.4679, Loss: 2.3805
Epoch   0 Batch   60/538 - Train Accuracy: 0.4207, Validation Accuracy: 0.4819, Loss: 2.2587
Epoch   0 Batch   80/538 - Train Accuracy: 0.4023, Validation Accuracy: 0.4478, Loss: 1.9773
Epoch   0 Batch  100/538 - Train Accuracy: 0.4322, Validation Accuracy: 0.4819, Loss: 1.6190
Epoch   0 Batch  120/538 - Train Accuracy: 0.4344, Validation Accuracy: 0.4815, Loss: 1.4055
Epoch   0 Batch  140/538 - Train Accuracy: 0.4398, Validation Accuracy: 0.5078, Loss: 1.1987
Epoch   0 Batch  160/538 - Train Accuracy: 0.4890, Validation Accuracy: 0.5183, Loss: 0.9494
Epoch   0 Batch  180/538 - Train Accuracy: 0.5188, Validation Accuracy: 0.5204, Loss: 0.8918
Epoch   0 Batch  200/538 - Train Accuracy: 0.4691, Validation Accuracy: 0.5082, Loss: 0.8347
Epoch   0 Batch  220/538 - Train Accuracy: 0.4799, Validation Accuracy: 0.5241, Loss: 0.7699
Epoch   0 Batch  240/538 - Train Accuracy: 0.3947, Validation Accuracy: 0.4309, Loss: 1.8101
Epoch   0 Batch  260/538 - Train Accuracy: 0.4702, Validation Accuracy: 0.5020, Loss: 0.8828
Epoch   0 Batch  280/538 - Train Accuracy: 0.5244, Validation Accuracy: 0.5247, Loss: 0.7527
Epoch   0 Batch  300/538 - Train Accuracy: 0.5262, Validation Accuracy: 0.5403, Loss: 0.7257
Epoch   0 Batch  320/538 - Train Accuracy: 0.5419, Validation Accuracy: 0.5524, Loss: 0.6959
Epoch   0 Batch  340/538 - Train Accuracy: 0.5434, Validation Accuracy: 0.5742, Loss: 0.7245
Epoch   0 Batch  360/538 - Train Accuracy: 0.5574, Validation Accuracy: 0.5891, Loss: 0.6867
Epoch   0 Batch  380/538 - Train Accuracy: 0.5428, Validation Accuracy: 0.5756, Loss: 0.6638
Epoch   0 Batch  400/538 - Train Accuracy: 0.5406, Validation Accuracy: 0.5597, Loss: 0.6417
Epoch   0 Batch  420/538 - Train Accuracy: 0.5770, Validation Accuracy: 0.5835, Loss: 0.6436
Epoch   0 Batch  440/538 - Train Accuracy: 0.5648, Validation Accuracy: 0.5875, Loss: 0.6591
Epoch   0 Batch  460/538 - Train Accuracy: 0.5766, Validation Accuracy: 0.5913, Loss: 0.6071
Epoch   0 Batch  480/538 - Train Accuracy: 0.6083, Validation Accuracy: 0.6065, Loss: 0.6042
Epoch   0 Batch  500/538 - Train Accuracy: 0.6167, Validation Accuracy: 0.6197, Loss: 0.5634
Epoch   0 Batch  520/538 - Train Accuracy: 0.6062, Validation Accuracy: 0.6397, Loss: 0.6204
Epoch   1 Batch   20/538 - Train Accuracy: 0.6155, Validation Accuracy: 0.6341, Loss: 0.5928
Epoch   1 Batch   40/538 - Train Accuracy: 0.6760, Validation Accuracy: 0.6518, Loss: 0.5116
Epoch   1 Batch   60/538 - Train Accuracy: 0.6420, Validation Accuracy: 0.6513, Loss: 0.5635
Epoch   1 Batch   80/538 - Train Accuracy: 0.6279, Validation Accuracy: 0.6550, Loss: 0.5710
Epoch   1 Batch  100/538 - Train Accuracy: 0.6287, Validation Accuracy: 0.6451, Loss: 0.5486
Epoch   1 Batch  120/538 - Train Accuracy: 0.6516, Validation Accuracy: 0.6589, Loss: 0.5187
Epoch   1 Batch  140/538 - Train Accuracy: 0.6080, Validation Accuracy: 0.6417, Loss: 0.5635
Epoch   1 Batch  160/538 - Train Accuracy: 0.6468, Validation Accuracy: 0.6696, Loss: 0.5067
Epoch   1 Batch  180/538 - Train Accuracy: 0.6877, Validation Accuracy: 0.6731, Loss: 0.4921
Epoch   1 Batch  200/538 - Train Accuracy: 0.6658, Validation Accuracy: 0.6735, Loss: 0.4871
Epoch   1 Batch  220/538 - Train Accuracy: 0.6395, Validation Accuracy: 0.6728, Loss: 0.4727
Epoch   1 Batch  240/538 - Train Accuracy: 0.6584, Validation Accuracy: 0.6825, Loss: 0.4649
Epoch   1 Batch  260/538 - Train Accuracy: 0.6449, Validation Accuracy: 0.6781, Loss: 0.4507
Epoch   1 Batch  280/538 - Train Accuracy: 0.7158, Validation Accuracy: 0.6895, Loss: 0.4225
Epoch   1 Batch  300/538 - Train Accuracy: 0.6842, Validation Accuracy: 0.6967, Loss: 0.4197
Epoch   1 Batch  320/538 - Train Accuracy: 0.7005, Validation Accuracy: 0.6777, Loss: 0.4068
Epoch   1 Batch  340/538 - Train Accuracy: 0.6602, Validation Accuracy: 0.6934, Loss: 0.4481
Epoch   1 Batch  360/538 - Train Accuracy: 0.6643, Validation Accuracy: 0.6781, Loss: 0.3962
Epoch   1 Batch  380/538 - Train Accuracy: 0.6865, Validation Accuracy: 0.6863, Loss: 0.3689
Epoch   1 Batch  400/538 - Train Accuracy: 0.7301, Validation Accuracy: 0.7038, Loss: 0.3525
Epoch   1 Batch  420/538 - Train Accuracy: 0.7314, Validation Accuracy: 0.6948, Loss: 0.3414
Epoch   1 Batch  440/538 - Train Accuracy: 0.7311, Validation Accuracy: 0.7161, Loss: 0.3579
Epoch   1 Batch  460/538 - Train Accuracy: 0.7273, Validation Accuracy: 0.7248, Loss: 0.3009
Epoch   1 Batch  480/538 - Train Accuracy: 0.7238, Validation Accuracy: 0.6983, Loss: 0.3163
Epoch   1 Batch  500/538 - Train Accuracy: 0.7763, Validation Accuracy: 0.7349, Loss: 0.2599
Epoch   1 Batch  520/538 - Train Accuracy: 0.7490, Validation Accuracy: 0.7299, Loss: 0.2869
Epoch   2 Batch   20/538 - Train Accuracy: 0.7764, Validation Accuracy: 0.7548, Loss: 0.2656
Epoch   2 Batch   40/538 - Train Accuracy: 0.7860, Validation Accuracy: 0.7456, Loss: 0.2246
Epoch   2 Batch   60/538 - Train Accuracy: 0.7871, Validation Accuracy: 0.7617, Loss: 0.2462
Epoch   2 Batch   80/538 - Train Accuracy: 0.7918, Validation Accuracy: 0.7518, Loss: 0.2384
Epoch   2 Batch  100/538 - Train Accuracy: 0.7740, Validation Accuracy: 0.7418, Loss: 0.2344
Epoch   2 Batch  120/538 - Train Accuracy: 0.8127, Validation Accuracy: 0.7710, Loss: 0.2129
Epoch   2 Batch  140/538 - Train Accuracy: 0.7658, Validation Accuracy: 0.7852, Loss: 0.2328
Epoch   2 Batch  160/538 - Train Accuracy: 0.7898, Validation Accuracy: 0.7809, Loss: 0.2029
Epoch   2 Batch  180/538 - Train Accuracy: 0.8363, Validation Accuracy: 0.7825, Loss: 0.2077
Epoch   2 Batch  200/538 - Train Accuracy: 0.8279, Validation Accuracy: 0.7928, Loss: 0.1877
Epoch   2 Batch  220/538 - Train Accuracy: 0.7816, Validation Accuracy: 0.7862, Loss: 0.1914
Epoch   2 Batch  240/538 - Train Accuracy: 0.8279, Validation Accuracy: 0.8278, Loss: 0.1832
Epoch   2 Batch  260/538 - Train Accuracy: 0.7868, Validation Accuracy: 0.8058, Loss: 0.1846
Epoch   2 Batch  280/538 - Train Accuracy: 0.8237, Validation Accuracy: 0.8072, Loss: 0.1734
Epoch   2 Batch  300/538 - Train Accuracy: 0.8408, Validation Accuracy: 0.8208, Loss: 0.1741
Epoch   2 Batch  320/538 - Train Accuracy: 0.8274, Validation Accuracy: 0.8358, Loss: 0.1477
Epoch   2 Batch  340/538 - Train Accuracy: 0.8486, Validation Accuracy: 0.8427, Loss: 0.1771
Epoch   2 Batch  360/538 - Train Accuracy: 0.8326, Validation Accuracy: 0.8548, Loss: 0.1562
Epoch   2 Batch  380/538 - Train Accuracy: 0.8730, Validation Accuracy: 0.8642, Loss: 0.1405
Epoch   2 Batch  400/538 - Train Accuracy: 0.8504, Validation Accuracy: 0.8551, Loss: 0.1411
Epoch   2 Batch  420/538 - Train Accuracy: 0.8541, Validation Accuracy: 0.8363, Loss: 0.1429
Epoch   2 Batch  440/538 - Train Accuracy: 0.8514, Validation Accuracy: 0.8494, Loss: 0.1472
Epoch   2 Batch  460/538 - Train Accuracy: 0.8497, Validation Accuracy: 0.8594, Loss: 0.1429
Epoch   2 Batch  480/538 - Train Accuracy: 0.8705, Validation Accuracy: 0.8574, Loss: 0.1254
Epoch   2 Batch  500/538 - Train Accuracy: 0.8906, Validation Accuracy: 0.8743, Loss: 0.1041
Epoch   2 Batch  520/538 - Train Accuracy: 0.8766, Validation Accuracy: 0.8659, Loss: 0.1256
Epoch   3 Batch   20/538 - Train Accuracy: 0.8882, Validation Accuracy: 0.8828, Loss: 0.1194
Epoch   3 Batch   40/538 - Train Accuracy: 0.9135, Validation Accuracy: 0.8748, Loss: 0.0981
Epoch   3 Batch   60/538 - Train Accuracy: 0.9061, Validation Accuracy: 0.8725, Loss: 0.1156
Epoch   3 Batch   80/538 - Train Accuracy: 0.8881, Validation Accuracy: 0.8789, Loss: 0.1279
Epoch   3 Batch  100/538 - Train Accuracy: 0.9037, Validation Accuracy: 0.9027, Loss: 0.1013
Epoch   3 Batch  120/538 - Train Accuracy: 0.9146, Validation Accuracy: 0.8855, Loss: 0.0985
Epoch   3 Batch  140/538 - Train Accuracy: 0.8750, Validation Accuracy: 0.8981, Loss: 0.1326
Epoch   3 Batch  160/538 - Train Accuracy: 0.8943, Validation Accuracy: 0.8817, Loss: 0.1013
Epoch   3 Batch  180/538 - Train Accuracy: 0.9156, Validation Accuracy: 0.8999, Loss: 0.1006
Epoch   3 Batch  200/538 - Train Accuracy: 0.8998, Validation Accuracy: 0.9027, Loss: 0.0849
Epoch   3 Batch  220/538 - Train Accuracy: 0.8983, Validation Accuracy: 0.8938, Loss: 0.0914
Epoch   3 Batch  240/538 - Train Accuracy: 0.8961, Validation Accuracy: 0.8931, Loss: 0.0946
Epoch   3 Batch  260/538 - Train Accuracy: 0.8731, Validation Accuracy: 0.8984, Loss: 0.0961
Epoch   3 Batch  280/538 - Train Accuracy: 0.9051, Validation Accuracy: 0.8814, Loss: 0.0811
Epoch   3 Batch  300/538 - Train Accuracy: 0.8953, Validation Accuracy: 0.9016, Loss: 0.0798
Epoch   3 Batch  320/538 - Train Accuracy: 0.9276, Validation Accuracy: 0.9178, Loss: 0.0686
Epoch   3 Batch  340/538 - Train Accuracy: 0.9025, Validation Accuracy: 0.9029, Loss: 0.0746
Epoch   3 Batch  360/538 - Train Accuracy: 0.9113, Validation Accuracy: 0.9164, Loss: 0.0766
Epoch   3 Batch  380/538 - Train Accuracy: 0.9201, Validation Accuracy: 0.9091, Loss: 0.0661
Epoch   3 Batch  400/538 - Train Accuracy: 0.9157, Validation Accuracy: 0.9047, Loss: 0.1149
Epoch   3 Batch  420/538 - Train Accuracy: 0.9100, Validation Accuracy: 0.9126, Loss: 0.0831
Epoch   3 Batch  440/538 - Train Accuracy: 0.9150, Validation Accuracy: 0.9102, Loss: 0.0770
Epoch   3 Batch  460/538 - Train Accuracy: 0.9087, Validation Accuracy: 0.9157, Loss: 0.0734
Epoch   3 Batch  480/538 - Train Accuracy: 0.9453, Validation Accuracy: 0.9157, Loss: 0.0539
Epoch   3 Batch  500/538 - Train Accuracy: 0.9506, Validation Accuracy: 0.9206, Loss: 0.0476
Epoch   3 Batch  520/538 - Train Accuracy: 0.9352, Validation Accuracy: 0.9052, Loss: 0.0619
Epoch   4 Batch   20/538 - Train Accuracy: 0.9325, Validation Accuracy: 0.9180, Loss: 0.0571
Epoch   4 Batch   40/538 - Train Accuracy: 0.9331, Validation Accuracy: 0.9391, Loss: 0.0488
Epoch   4 Batch   60/538 - Train Accuracy: 0.9471, Validation Accuracy: 0.9219, Loss: 0.0556
Epoch   4 Batch   80/538 - Train Accuracy: 0.9365, Validation Accuracy: 0.9189, Loss: 0.0554
Epoch   4 Batch  100/538 - Train Accuracy: 0.9406, Validation Accuracy: 0.9208, Loss: 0.0456
Epoch   4 Batch  120/538 - Train Accuracy: 0.9615, Validation Accuracy: 0.9231, Loss: 0.0419
Epoch   4 Batch  140/538 - Train Accuracy: 0.9148, Validation Accuracy: 0.9270, Loss: 0.0688
Epoch   4 Batch  160/538 - Train Accuracy: 0.9196, Validation Accuracy: 0.9256, Loss: 0.0505
Epoch   4 Batch  180/538 - Train Accuracy: 0.9395, Validation Accuracy: 0.9213, Loss: 0.0492
Epoch   4 Batch  200/538 - Train Accuracy: 0.9469, Validation Accuracy: 0.9180, Loss: 0.0485
Epoch   4 Batch  220/538 - Train Accuracy: 0.9278, Validation Accuracy: 0.9032, Loss: 0.0519
Epoch   4 Batch  240/538 - Train Accuracy: 0.9365, Validation Accuracy: 0.9339, Loss: 0.0555
Epoch   4 Batch  260/538 - Train Accuracy: 0.9174, Validation Accuracy: 0.9345, Loss: 0.0527
Epoch   4 Batch  280/538 - Train Accuracy: 0.9412, Validation Accuracy: 0.9203, Loss: 0.0381
Epoch   4 Batch  300/538 - Train Accuracy: 0.9401, Validation Accuracy: 0.9359, Loss: 0.0480
Epoch   4 Batch  320/538 - Train Accuracy: 0.9481, Validation Accuracy: 0.9409, Loss: 0.0415
Epoch   4 Batch  340/538 - Train Accuracy: 0.9426, Validation Accuracy: 0.9309, Loss: 0.0423
Epoch   4 Batch  360/538 - Train Accuracy: 0.9307, Validation Accuracy: 0.9423, Loss: 0.0405
Epoch   4 Batch  380/538 - Train Accuracy: 0.9410, Validation Accuracy: 0.9315, Loss: 0.0398
Epoch   4 Batch  400/538 - Train Accuracy: 0.9453, Validation Accuracy: 0.9391, Loss: 0.0458
Epoch   4 Batch  420/538 - Train Accuracy: 0.9437, Validation Accuracy: 0.9395, Loss: 0.0413
Epoch   4 Batch  440/538 - Train Accuracy: 0.9436, Validation Accuracy: 0.9439, Loss: 0.0479
Epoch   4 Batch  460/538 - Train Accuracy: 0.9319, Validation Accuracy: 0.9467, Loss: 0.0479
Epoch   4 Batch  480/538 - Train Accuracy: 0.9477, Validation Accuracy: 0.9441, Loss: 0.0428
Epoch   4 Batch  500/538 - Train Accuracy: 0.9524, Validation Accuracy: 0.9510, Loss: 0.0318
Epoch   4 Batch  520/538 - Train Accuracy: 0.9574, Validation Accuracy: 0.9256, Loss: 0.0478
Epoch   5 Batch   20/538 - Train Accuracy: 0.9427, Validation Accuracy: 0.9396, Loss: 0.0451
Epoch   5 Batch   40/538 - Train Accuracy: 0.9426, Validation Accuracy: 0.9380, Loss: 0.0347
Epoch   5 Batch   60/538 - Train Accuracy: 0.9523, Validation Accuracy: 0.9304, Loss: 0.0440
Epoch   5 Batch   80/538 - Train Accuracy: 0.9594, Validation Accuracy: 0.9302, Loss: 0.0421
Epoch   5 Batch  100/538 - Train Accuracy: 0.9568, Validation Accuracy: 0.9498, Loss: 0.0389
Epoch   5 Batch  120/538 - Train Accuracy: 0.9705, Validation Accuracy: 0.9345, Loss: 0.0262
Epoch   5 Batch  140/538 - Train Accuracy: 0.9369, Validation Accuracy: 0.9377, Loss: 0.0521
Epoch   5 Batch  160/538 - Train Accuracy: 0.9507, Validation Accuracy: 0.9442, Loss: 0.0358
Epoch   5 Batch  180/538 - Train Accuracy: 0.9559, Validation Accuracy: 0.9476, Loss: 0.0397
Epoch   5 Batch  200/538 - Train Accuracy: 0.9459, Validation Accuracy: 0.9434, Loss: 0.0333
Epoch   5 Batch  220/538 - Train Accuracy: 0.9355, Validation Accuracy: 0.9341, Loss: 0.0398
Epoch   5 Batch  240/538 - Train Accuracy: 0.9508, Validation Accuracy: 0.9547, Loss: 0.0421
Epoch   5 Batch  260/538 - Train Accuracy: 0.9336, Validation Accuracy: 0.9249, Loss: 0.0413
Epoch   5 Batch  280/538 - Train Accuracy: 0.9539, Validation Accuracy: 0.9361, Loss: 0.0329
Epoch   5 Batch  300/538 - Train Accuracy: 0.9559, Validation Accuracy: 0.9411, Loss: 0.0414
Epoch   5 Batch  320/538 - Train Accuracy: 0.9488, Validation Accuracy: 0.9405, Loss: 0.0315
Epoch   5 Batch  340/538 - Train Accuracy: 0.9475, Validation Accuracy: 0.9412, Loss: 0.0370
Epoch   5 Batch  360/538 - Train Accuracy: 0.9500, Validation Accuracy: 0.9466, Loss: 0.0325
Epoch   5 Batch  380/538 - Train Accuracy: 0.9502, Validation Accuracy: 0.9382, Loss: 0.0299
Epoch   5 Batch  400/538 - Train Accuracy: 0.9682, Validation Accuracy: 0.9494, Loss: 0.0409
Epoch   5 Batch  420/538 - Train Accuracy: 0.9502, Validation Accuracy: 0.9455, Loss: 0.0409
Epoch   5 Batch  440/538 - Train Accuracy: 0.9588, Validation Accuracy: 0.9425, Loss: 0.0428
Epoch   5 Batch  460/538 - Train Accuracy: 0.9459, Validation Accuracy: 0.9602, Loss: 0.0390
Epoch   5 Batch  480/538 - Train Accuracy: 0.9581, Validation Accuracy: 0.9455, Loss: 0.0372
Epoch   5 Batch  500/538 - Train Accuracy: 0.9698, Validation Accuracy: 0.9411, Loss: 0.0276
Epoch   5 Batch  520/538 - Train Accuracy: 0.9553, Validation Accuracy: 0.9391, Loss: 0.0365
Epoch   6 Batch   20/538 - Train Accuracy: 0.9515, Validation Accuracy: 0.9418, Loss: 0.0378
Epoch   6 Batch   40/538 - Train Accuracy: 0.9521, Validation Accuracy: 0.9439, Loss: 0.0262
Epoch   6 Batch   60/538 - Train Accuracy: 0.9418, Validation Accuracy: 0.9542, Loss: 0.0364
Epoch   6 Batch   80/538 - Train Accuracy: 0.9693, Validation Accuracy: 0.9553, Loss: 0.0286
Epoch   6 Batch  100/538 - Train Accuracy: 0.9553, Validation Accuracy: 0.9542, Loss: 0.0282
Epoch   6 Batch  120/538 - Train Accuracy: 0.9611, Validation Accuracy: 0.9466, Loss: 0.0250
Epoch   6 Batch  140/538 - Train Accuracy: 0.9447, Validation Accuracy: 0.9398, Loss: 0.0428
Epoch   6 Batch  160/538 - Train Accuracy: 0.9593, Validation Accuracy: 0.9382, Loss: 0.0306
Epoch   6 Batch  180/538 - Train Accuracy: 0.9606, Validation Accuracy: 0.9487, Loss: 0.0310
Epoch   6 Batch  200/538 - Train Accuracy: 0.9645, Validation Accuracy: 0.9526, Loss: 0.0254
Epoch   6 Batch  220/538 - Train Accuracy: 0.9446, Validation Accuracy: 0.9451, Loss: 0.0389
Epoch   6 Batch  240/538 - Train Accuracy: 0.9506, Validation Accuracy: 0.9517, Loss: 0.0392
Epoch   6 Batch  260/538 - Train Accuracy: 0.9494, Validation Accuracy: 0.9476, Loss: 0.0432
Epoch   6 Batch  280/538 - Train Accuracy: 0.9621, Validation Accuracy: 0.9306, Loss: 0.0350
Epoch   6 Batch  300/538 - Train Accuracy: 0.9561, Validation Accuracy: 0.9469, Loss: 0.0356
Epoch   6 Batch  320/538 - Train Accuracy: 0.9548, Validation Accuracy: 0.9519, Loss: 0.0329
Epoch   6 Batch  340/538 - Train Accuracy: 0.9549, Validation Accuracy: 0.9458, Loss: 0.0358
Epoch   6 Batch  360/538 - Train Accuracy: 0.9576, Validation Accuracy: 0.9553, Loss: 0.0279
Epoch   6 Batch  380/538 - Train Accuracy: 0.9502, Validation Accuracy: 0.9501, Loss: 0.0290
Epoch   6 Batch  400/538 - Train Accuracy: 0.9674, Validation Accuracy: 0.9620, Loss: 0.0312
Epoch   6 Batch  420/538 - Train Accuracy: 0.9590, Validation Accuracy: 0.9565, Loss: 0.0303
Epoch   6 Batch  440/538 - Train Accuracy: 0.9588, Validation Accuracy: 0.9547, Loss: 0.0288
Epoch   6 Batch  460/538 - Train Accuracy: 0.9557, Validation Accuracy: 0.9513, Loss: 0.0286
Epoch   6 Batch  480/538 - Train Accuracy: 0.9660, Validation Accuracy: 0.9592, Loss: 0.0244
Epoch   6 Batch  500/538 - Train Accuracy: 0.9702, Validation Accuracy: 0.9473, Loss: 0.0197
Epoch   6 Batch  520/538 - Train Accuracy: 0.9596, Validation Accuracy: 0.9526, Loss: 0.0259
Epoch   7 Batch   20/538 - Train Accuracy: 0.9671, Validation Accuracy: 0.9624, Loss: 0.0305
Epoch   7 Batch   40/538 - Train Accuracy: 0.9686, Validation Accuracy: 0.9592, Loss: 0.0206
Epoch   7 Batch   60/538 - Train Accuracy: 0.9555, Validation Accuracy: 0.9790, Loss: 0.0316
Epoch   7 Batch   80/538 - Train Accuracy: 0.9641, Validation Accuracy: 0.9569, Loss: 0.0316
Epoch   7 Batch  100/538 - Train Accuracy: 0.9693, Validation Accuracy: 0.9624, Loss: 0.0249
Epoch   7 Batch  120/538 - Train Accuracy: 0.9627, Validation Accuracy: 0.9519, Loss: 0.0253
Epoch   7 Batch  140/538 - Train Accuracy: 0.9525, Validation Accuracy: 0.9627, Loss: 0.0383
Epoch   7 Batch  160/538 - Train Accuracy: 0.9622, Validation Accuracy: 0.9498, Loss: 0.0246
Epoch   7 Batch  180/538 - Train Accuracy: 0.9544, Validation Accuracy: 0.9499, Loss: 0.0307
Epoch   7 Batch  200/538 - Train Accuracy: 0.9699, Validation Accuracy: 0.9558, Loss: 0.0277
Epoch   7 Batch  220/538 - Train Accuracy: 0.9522, Validation Accuracy: 0.9576, Loss: 0.0308
Epoch   7 Batch  240/538 - Train Accuracy: 0.9596, Validation Accuracy: 0.9533, Loss: 0.0335
Epoch   7 Batch  260/538 - Train Accuracy: 0.9438, Validation Accuracy: 0.9348, Loss: 0.0286
Epoch   7 Batch  280/538 - Train Accuracy: 0.9565, Validation Accuracy: 0.9643, Loss: 0.0261
Epoch   7 Batch  300/538 - Train Accuracy: 0.9727, Validation Accuracy: 0.9570, Loss: 0.0306
Epoch   7 Batch  320/538 - Train Accuracy: 0.9647, Validation Accuracy: 0.9588, Loss: 0.0253
Epoch   7 Batch  340/538 - Train Accuracy: 0.9592, Validation Accuracy: 0.9627, Loss: 0.0245
Epoch   7 Batch  360/538 - Train Accuracy: 0.9652, Validation Accuracy: 0.9666, Loss: 0.0202
Epoch   7 Batch  380/538 - Train Accuracy: 0.9713, Validation Accuracy: 0.9632, Loss: 0.0219
Epoch   7 Batch  400/538 - Train Accuracy: 0.9732, Validation Accuracy: 0.9620, Loss: 0.0226
Epoch   7 Batch  420/538 - Train Accuracy: 0.9615, Validation Accuracy: 0.9544, Loss: 0.0299
Epoch   7 Batch  440/538 - Train Accuracy: 0.9629, Validation Accuracy: 0.9519, Loss: 0.0285
Epoch   7 Batch  460/538 - Train Accuracy: 0.9632, Validation Accuracy: 0.9569, Loss: 0.0287
Epoch   7 Batch  480/538 - Train Accuracy: 0.9727, Validation Accuracy: 0.9661, Loss: 0.0250
Epoch   7 Batch  500/538 - Train Accuracy: 0.9652, Validation Accuracy: 0.9622, Loss: 0.0215
Epoch   7 Batch  520/538 - Train Accuracy: 0.9656, Validation Accuracy: 0.9572, Loss: 0.0242
Epoch   8 Batch   20/538 - Train Accuracy: 0.9771, Validation Accuracy: 0.9673, Loss: 0.0245
Epoch   8 Batch   40/538 - Train Accuracy: 0.9631, Validation Accuracy: 0.9600, Loss: 0.0198
Epoch   8 Batch   60/538 - Train Accuracy: 0.9656, Validation Accuracy: 0.9657, Loss: 0.0253
Epoch   8 Batch   80/538 - Train Accuracy: 0.9688, Validation Accuracy: 0.9673, Loss: 0.0217
Epoch   8 Batch  100/538 - Train Accuracy: 0.9791, Validation Accuracy: 0.9689, Loss: 0.0212
Epoch   8 Batch  120/538 - Train Accuracy: 0.9752, Validation Accuracy: 0.9590, Loss: 0.0177
Epoch   8 Batch  140/538 - Train Accuracy: 0.9617, Validation Accuracy: 0.9483, Loss: 0.0337
Epoch   8 Batch  160/538 - Train Accuracy: 0.9719, Validation Accuracy: 0.9535, Loss: 0.0197
Epoch   8 Batch  180/538 - Train Accuracy: 0.9555, Validation Accuracy: 0.9636, Loss: 0.0296
Epoch   8 Batch  200/538 - Train Accuracy: 0.9713, Validation Accuracy: 0.9673, Loss: 0.0183
Epoch   8 Batch  220/538 - Train Accuracy: 0.9581, Validation Accuracy: 0.9654, Loss: 0.0228
Epoch   8 Batch  240/538 - Train Accuracy: 0.9574, Validation Accuracy: 0.9579, Loss: 0.0301
Epoch   8 Batch  260/538 - Train Accuracy: 0.9594, Validation Accuracy: 0.9702, Loss: 0.0319
Epoch   8 Batch  280/538 - Train Accuracy: 0.9710, Validation Accuracy: 0.9684, Loss: 0.0211
Epoch   8 Batch  300/538 - Train Accuracy: 0.9712, Validation Accuracy: 0.9725, Loss: 0.0233
Epoch   8 Batch  320/538 - Train Accuracy: 0.9732, Validation Accuracy: 0.9659, Loss: 0.0184
Epoch   8 Batch  340/538 - Train Accuracy: 0.9744, Validation Accuracy: 0.9641, Loss: 0.0220
Epoch   8 Batch  360/538 - Train Accuracy: 0.9633, Validation Accuracy: 0.9673, Loss: 0.0209
Epoch   8 Batch  380/538 - Train Accuracy: 0.9744, Validation Accuracy: 0.9636, Loss: 0.0206
Epoch   8 Batch  400/538 - Train Accuracy: 0.9857, Validation Accuracy: 0.9535, Loss: 0.0255
Epoch   8 Batch  420/538 - Train Accuracy: 0.9621, Validation Accuracy: 0.9529, Loss: 0.0299
Epoch   8 Batch  440/538 - Train Accuracy: 0.9668, Validation Accuracy: 0.9567, Loss: 0.0288
Epoch   8 Batch  460/538 - Train Accuracy: 0.9680, Validation Accuracy: 0.9663, Loss: 0.0283
Epoch   8 Batch  480/538 - Train Accuracy: 0.9676, Validation Accuracy: 0.9600, Loss: 0.0230
Epoch   8 Batch  500/538 - Train Accuracy: 0.9790, Validation Accuracy: 0.9590, Loss: 0.0156
Epoch   8 Batch  520/538 - Train Accuracy: 0.9760, Validation Accuracy: 0.9629, Loss: 0.0225
Epoch   9 Batch   20/538 - Train Accuracy: 0.9673, Validation Accuracy: 0.9672, Loss: 0.0294
Epoch   9 Batch   40/538 - Train Accuracy: 0.9672, Validation Accuracy: 0.9643, Loss: 0.0199
Epoch   9 Batch   60/538 - Train Accuracy: 0.9756, Validation Accuracy: 0.9648, Loss: 0.0225
Epoch   9 Batch   80/538 - Train Accuracy: 0.9707, Validation Accuracy: 0.9522, Loss: 0.0168
Epoch   9 Batch  100/538 - Train Accuracy: 0.9881, Validation Accuracy: 0.9679, Loss: 0.0179
Epoch   9 Batch  120/538 - Train Accuracy: 0.9842, Validation Accuracy: 0.9634, Loss: 0.0138
Epoch   9 Batch  140/538 - Train Accuracy: 0.9629, Validation Accuracy: 0.9632, Loss: 0.0335
Epoch   9 Batch  160/538 - Train Accuracy: 0.9756, Validation Accuracy: 0.9531, Loss: 0.0217
Epoch   9 Batch  180/538 - Train Accuracy: 0.9708, Validation Accuracy: 0.9604, Loss: 0.0227
Epoch   9 Batch  200/538 - Train Accuracy: 0.9814, Validation Accuracy: 0.9643, Loss: 0.0177
Epoch   9 Batch  220/538 - Train Accuracy: 0.9760, Validation Accuracy: 0.9624, Loss: 0.0230
Epoch   9 Batch  240/538 - Train Accuracy: 0.9639, Validation Accuracy: 0.9558, Loss: 0.0262
Epoch   9 Batch  260/538 - Train Accuracy: 0.9503, Validation Accuracy: 0.9647, Loss: 0.0259
Epoch   9 Batch  280/538 - Train Accuracy: 0.9803, Validation Accuracy: 0.9709, Loss: 0.0233
Epoch   9 Batch  300/538 - Train Accuracy: 0.9779, Validation Accuracy: 0.9675, Loss: 0.0192
Epoch   9 Batch  320/538 - Train Accuracy: 0.9784, Validation Accuracy: 0.9647, Loss: 0.0151
Epoch   9 Batch  340/538 - Train Accuracy: 0.9635, Validation Accuracy: 0.9688, Loss: 0.0195
Epoch   9 Batch  360/538 - Train Accuracy: 0.9648, Validation Accuracy: 0.9615, Loss: 0.0238
Epoch   9 Batch  380/538 - Train Accuracy: 0.9742, Validation Accuracy: 0.9698, Loss: 0.0220
Epoch   9 Batch  400/538 - Train Accuracy: 0.9779, Validation Accuracy: 0.9727, Loss: 0.0226
Epoch   9 Batch  420/538 - Train Accuracy: 0.9688, Validation Accuracy: 0.9739, Loss: 0.0288
Epoch   9 Batch  440/538 - Train Accuracy: 0.9736, Validation Accuracy: 0.9620, Loss: 0.0250
Epoch   9 Batch  460/538 - Train Accuracy: 0.9611, Validation Accuracy: 0.9602, Loss: 0.0227
Epoch   9 Batch  480/538 - Train Accuracy: 0.9741, Validation Accuracy: 0.9611, Loss: 0.0182
Epoch   9 Batch  500/538 - Train Accuracy: 0.9760, Validation Accuracy: 0.9593, Loss: 0.0188
Epoch   9 Batch  520/538 - Train Accuracy: 0.9721, Validation Accuracy: 0.9558, Loss: 0.0205
Model Trained and Saved

Save Parameters

Save the batch_size and save_path parameters for inference.


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

Checkpoint


In [22]:
"""
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 [28]:
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
    """
    # TODO: Implement Function
    low_sentence = sentence.lower()
    sentence_int = [vocab_to_int.get(word, vocab_to_int["<UNK>"]) for word in low_sentence.split()]
    
    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 [29]:
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 + '.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:      [81, 129, 10, 145, 204, 227, 18]
  English Words: ['he', 'saw', 'a', 'old', 'yellow', 'truck', '.']

Prediction
  Word Ids:      [93, 6, 129, 122, 287, 289, 100, 85, 1]
  French Words: il a vu un vieux camion blanc . <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.