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)
    """
    
    eos = target_vocab_to_int['<EOS>']

    source_sentences = [s for s in source_text.split('\n')]
    target_sentences = [s for s in target_text.split('\n')]
    
    source_id_text = [[source_vocab_to_int[w] for w in s.split()] for s in source_sentences]
    target_id_text = [[target_vocab_to_int[w] for w in s.split()] + [eos] for s in target_sentences]
            
    return source_id_text, target_id_text

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


Tests Passed

Preprocess all the data and save it

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


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

Check Point

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


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

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

Check the Version of TensorFlow and Access to GPU

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


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

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

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


TensorFlow Version: 1.1.0
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:15: UserWarning: No GPU found. Please use a GPU to train your neural network.
  from ipykernel import kernelapp as app

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_data = tf.placeholder(tf.int32, [None, None], name='input')
    targets = tf.placeholder(tf.int32, [None, None], name='target')
    learning_rate = tf.placeholder(tf.float32, name='learning_rate')
    keep_probability = tf.placeholder(tf.float32, None, name='keep_prob')
    target_squence_length = tf.placeholder(tf.int32, (None,), name='target_sequence_length')
    max_target_sequence_length = tf.reduce_max(target_squence_length, name='max_target_len')
    source_sequence_length = tf.placeholder(tf.int32, (None,), name='source_sequence_length')
    
    return (input_data, 
            targets, 
            learning_rate, 
            keep_probability, 
            target_squence_length, 
            max_target_sequence_length, 
            source_sequence_length)

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


Tests Passed

Process Decoder Input

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


In [8]:
def process_decoder_input(target_data, target_vocab_to_int, batch_size):
    """
    Preprocess target data for encoding
    :param target_data: Target Placehoder
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :param batch_size: Batch Size
    :return: Preprocessed target data
    """
    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]:
def make_stacked_lstm_rnn_cell(rnn_size, num_layers, keep_prob):

    def rnn_cell(rnn_size):
        
        lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2)) 
        
        return tf.contrib.rnn.DropoutWrapper(lstm_cell, keep_prob, keep_prob, keep_prob)

    stacked_lstm_cell = tf.contrib.rnn.MultiRNNCell([rnn_cell(rnn_size) for _ in range(num_layers)])

    return stacked_lstm_cell

In [10]:
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)
     
    stacked_cell = make_stacked_lstm_rnn_cell(rnn_size, num_layers, keep_prob)   
    
    return tf.nn.dynamic_rnn(stacked_cell, enc_embed_input, sequence_length=source_sequence_length, dtype=tf.float32)

"""
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 [11]:
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
    """
    
    training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input,
                                                        sequence_length=target_sequence_length,
                                                        time_major=False)
    training_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, training_helper, encoder_state, output_layer)
    
    training_decoder_output, _ = tf.contrib.seq2seq.dynamic_decode(training_decoder, impute_finished=True,
                                                                   maximum_iterations=max_summary_length)
        
    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 [12]:
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_tokens = tf.tile(tf.constant([start_of_sequence_id], dtype=tf.int32), [batch_size], name='start_tokens')
    inference_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings, start_tokens, end_of_sequence_id)

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

    decoder_output, _ = tf.contrib.seq2seq.dynamic_decode(inference_decoder, 
                                                          impute_finished=True, 
                                                          maximum_iterations=max_target_sequence_length)
    
    return 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 [13]:
def decode_stacked_lstm_rnn_cell(rnn_size, num_layers, keep_prob=1.0): # remove keep_prob?

    def rnn_cell(rnn_size):
        
        lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
        
        return lstm_cell

    decoded_lstm_cell = tf.contrib.rnn.MultiRNNCell([rnn_cell(rnn_size) for _ in range(num_layers)])

    return decoded_lstm_cell

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

    decoder_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))
    decoder_embeddings_input = tf.nn.embedding_lookup(decoder_embeddings, dec_input)
    
    decoded_cell = decode_stacked_lstm_rnn_cell(rnn_size, num_layers) 
    
    output_layer = Dense(target_vocab_size, 
                         kernel_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1))
    
    with tf.variable_scope("decoding") as training_scope:
        training_logits = decoding_layer_train(encoder_state, decoded_cell, decoder_embeddings_input,
                                               target_sequence_length, max_target_sequence_length,
                                               output_layer, keep_prob)
    
    start_of_sequence_id = target_vocab_to_int['<GO>']
    end_of_sequence_id = target_vocab_to_int['<EOS>']
    
    with tf.variable_scope("decoding", reuse=True) as inference_scope:
        inference_logits = decoding_layer_infer(encoder_state, decoded_cell, decoder_embeddings,
                                                start_of_sequence_id, end_of_sequence_id,
                                                max_target_sequence_length, target_vocab_size,
                                                output_layer, batch_size, keep_prob)
    
    return training_logits, inference_logits

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

    enc_output, enc_state = encoding_layer(input_data, rnn_size, num_layers, keep_prob,
                                           source_sequence_length, source_vocab_size, enc_embedding_size)
    
    dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size)
    
    training_output, inference_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_output, inference_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 = 10

# Batch Size
batch_size = 256

# RNN Size
rnn_size = 512

# Number of Layers
num_layers = 3

# Embedding Size
encoding_embedding_size = 256
decoding_embedding_size = 256

# Learning Rate
learning_rate = 0.001

# Dropout Keep Probability
keep_probability = 0.8
display_step = 25

Build the Graph

Build the graph using the neural network you implemented.


In [17]:
"""
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 [18]:
"""
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 [19]:
"""
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())

    loss_list = []
    valid_acc_list = []

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

            loss_list.append(loss)
            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)
                valid_acc_list.append(valid_acc)

                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   25/538 - Train Accuracy: 0.2912, Validation Accuracy: 0.3558, Loss: 2.6153
Epoch   0 Batch   50/538 - Train Accuracy: 0.4461, Validation Accuracy: 0.4798, Loss: 2.0645
Epoch   0 Batch   75/538 - Train Accuracy: 0.4563, Validation Accuracy: 0.4798, Loss: 1.6255
Epoch   0 Batch  100/538 - Train Accuracy: 0.4510, Validation Accuracy: 0.4906, Loss: 1.3948
Epoch   0 Batch  125/538 - Train Accuracy: 0.5002, Validation Accuracy: 0.5316, Loss: 1.2457
Epoch   0 Batch  150/538 - Train Accuracy: 0.4941, Validation Accuracy: 0.5160, Loss: 1.1387
Epoch   0 Batch  175/538 - Train Accuracy: 0.3879, Validation Accuracy: 0.4466, Loss: 1.0557
Epoch   0 Batch  200/538 - Train Accuracy: 0.5039, Validation Accuracy: 0.5188, Loss: 0.9372
Epoch   0 Batch  225/538 - Train Accuracy: 0.5190, Validation Accuracy: 0.5328, Loss: 0.8446
Epoch   0 Batch  250/538 - Train Accuracy: 0.5447, Validation Accuracy: 0.5806, Loss: 0.7842
Epoch   0 Batch  275/538 - Train Accuracy: 0.5207, Validation Accuracy: 0.5630, Loss: 0.8002
Epoch   0 Batch  300/538 - Train Accuracy: 0.5612, Validation Accuracy: 0.5629, Loss: 0.6953
Epoch   0 Batch  325/538 - Train Accuracy: 0.5796, Validation Accuracy: 0.5719, Loss: 0.6569
Epoch   0 Batch  350/538 - Train Accuracy: 0.5911, Validation Accuracy: 0.5985, Loss: 0.6406
Epoch   0 Batch  375/538 - Train Accuracy: 0.5954, Validation Accuracy: 0.6056, Loss: 0.5828
Epoch   0 Batch  400/538 - Train Accuracy: 0.5964, Validation Accuracy: 0.6016, Loss: 0.5699
Epoch   0 Batch  425/538 - Train Accuracy: 0.6202, Validation Accuracy: 0.6280, Loss: 0.5579
Epoch   0 Batch  450/538 - Train Accuracy: 0.6380, Validation Accuracy: 0.6346, Loss: 0.5538
Epoch   0 Batch  475/538 - Train Accuracy: 0.6241, Validation Accuracy: 0.6314, Loss: 0.5188
Epoch   0 Batch  500/538 - Train Accuracy: 0.6289, Validation Accuracy: 0.6381, Loss: 0.4801
Epoch   0 Batch  525/538 - Train Accuracy: 0.6611, Validation Accuracy: 0.6330, Loss: 0.4821
Epoch   1 Batch   25/538 - Train Accuracy: 0.6141, Validation Accuracy: 0.6534, Loss: 0.4885
Epoch   1 Batch   50/538 - Train Accuracy: 0.6430, Validation Accuracy: 0.6593, Loss: 0.4811
Epoch   1 Batch   75/538 - Train Accuracy: 0.6687, Validation Accuracy: 0.6697, Loss: 0.4290
Epoch   1 Batch  100/538 - Train Accuracy: 0.6816, Validation Accuracy: 0.6729, Loss: 0.4332
Epoch   1 Batch  125/538 - Train Accuracy: 0.6749, Validation Accuracy: 0.6990, Loss: 0.4130
Epoch   1 Batch  150/538 - Train Accuracy: 0.6631, Validation Accuracy: 0.6926, Loss: 0.4081
Epoch   1 Batch  175/538 - Train Accuracy: 0.6559, Validation Accuracy: 0.6495, Loss: 0.3907
Epoch   1 Batch  200/538 - Train Accuracy: 0.7236, Validation Accuracy: 0.7060, Loss: 0.3532
Epoch   1 Batch  225/538 - Train Accuracy: 0.7087, Validation Accuracy: 0.7022, Loss: 0.3373
Epoch   1 Batch  250/538 - Train Accuracy: 0.7166, Validation Accuracy: 0.7301, Loss: 0.3407
Epoch   1 Batch  275/538 - Train Accuracy: 0.7076, Validation Accuracy: 0.7509, Loss: 0.3312
Epoch   1 Batch  300/538 - Train Accuracy: 0.7368, Validation Accuracy: 0.7544, Loss: 0.2951
Epoch   1 Batch  325/538 - Train Accuracy: 0.7539, Validation Accuracy: 0.7498, Loss: 0.2965
Epoch   1 Batch  350/538 - Train Accuracy: 0.7504, Validation Accuracy: 0.7646, Loss: 0.2892
Epoch   1 Batch  375/538 - Train Accuracy: 0.7740, Validation Accuracy: 0.7816, Loss: 0.2633
Epoch   1 Batch  400/538 - Train Accuracy: 0.7593, Validation Accuracy: 0.7727, Loss: 0.2683
Epoch   1 Batch  425/538 - Train Accuracy: 0.7744, Validation Accuracy: 0.7862, Loss: 0.2547
Epoch   1 Batch  450/538 - Train Accuracy: 0.7879, Validation Accuracy: 0.7658, Loss: 0.2493
Epoch   1 Batch  475/538 - Train Accuracy: 0.8080, Validation Accuracy: 0.7688, Loss: 0.2268
Epoch   1 Batch  500/538 - Train Accuracy: 0.8260, Validation Accuracy: 0.7937, Loss: 0.2047
Epoch   1 Batch  525/538 - Train Accuracy: 0.8147, Validation Accuracy: 0.7850, Loss: 0.2145
Epoch   2 Batch   25/538 - Train Accuracy: 0.8105, Validation Accuracy: 0.8102, Loss: 0.2180
Epoch   2 Batch   50/538 - Train Accuracy: 0.8109, Validation Accuracy: 0.8004, Loss: 0.2059
Epoch   2 Batch   75/538 - Train Accuracy: 0.8158, Validation Accuracy: 0.8180, Loss: 0.1862
Epoch   2 Batch  100/538 - Train Accuracy: 0.8145, Validation Accuracy: 0.8278, Loss: 0.1887
Epoch   2 Batch  125/538 - Train Accuracy: 0.8406, Validation Accuracy: 0.8079, Loss: 0.1856
Epoch   2 Batch  150/538 - Train Accuracy: 0.8191, Validation Accuracy: 0.8091, Loss: 0.1733
Epoch   2 Batch  175/538 - Train Accuracy: 0.8396, Validation Accuracy: 0.8244, Loss: 0.1594
Epoch   2 Batch  200/538 - Train Accuracy: 0.8525, Validation Accuracy: 0.8455, Loss: 0.1474
Epoch   2 Batch  225/538 - Train Accuracy: 0.8655, Validation Accuracy: 0.8276, Loss: 0.1440
Epoch   2 Batch  250/538 - Train Accuracy: 0.8742, Validation Accuracy: 0.8578, Loss: 0.1437
Epoch   2 Batch  275/538 - Train Accuracy: 0.8650, Validation Accuracy: 0.8683, Loss: 0.1392
Epoch   2 Batch  300/538 - Train Accuracy: 0.8832, Validation Accuracy: 0.8960, Loss: 0.1246
Epoch   2 Batch  325/538 - Train Accuracy: 0.9023, Validation Accuracy: 0.8801, Loss: 0.1304
Epoch   2 Batch  350/538 - Train Accuracy: 0.8891, Validation Accuracy: 0.8926, Loss: 0.1256
Epoch   2 Batch  375/538 - Train Accuracy: 0.9109, Validation Accuracy: 0.8956, Loss: 0.1044
Epoch   2 Batch  400/538 - Train Accuracy: 0.9062, Validation Accuracy: 0.8903, Loss: 0.1021
Epoch   2 Batch  425/538 - Train Accuracy: 0.9221, Validation Accuracy: 0.9066, Loss: 0.1156
Epoch   2 Batch  450/538 - Train Accuracy: 0.9022, Validation Accuracy: 0.9091, Loss: 0.1158
Epoch   2 Batch  475/538 - Train Accuracy: 0.9213, Validation Accuracy: 0.9052, Loss: 0.0887
Epoch   2 Batch  500/538 - Train Accuracy: 0.9370, Validation Accuracy: 0.9199, Loss: 0.0613
Epoch   2 Batch  525/538 - Train Accuracy: 0.9381, Validation Accuracy: 0.9213, Loss: 0.0703
Epoch   3 Batch   25/538 - Train Accuracy: 0.9176, Validation Accuracy: 0.9146, Loss: 0.0842
Epoch   3 Batch   50/538 - Train Accuracy: 0.9318, Validation Accuracy: 0.9123, Loss: 0.0715
Epoch   3 Batch   75/538 - Train Accuracy: 0.9375, Validation Accuracy: 0.9164, Loss: 0.0691
Epoch   3 Batch  100/538 - Train Accuracy: 0.9301, Validation Accuracy: 0.9150, Loss: 0.0606
Epoch   3 Batch  125/538 - Train Accuracy: 0.9386, Validation Accuracy: 0.9228, Loss: 0.0706
Epoch   3 Batch  150/538 - Train Accuracy: 0.9449, Validation Accuracy: 0.9224, Loss: 0.0668
Epoch   3 Batch  175/538 - Train Accuracy: 0.9320, Validation Accuracy: 0.9180, Loss: 0.0534
Epoch   3 Batch  200/538 - Train Accuracy: 0.9400, Validation Accuracy: 0.9256, Loss: 0.0560
Epoch   3 Batch  225/538 - Train Accuracy: 0.9483, Validation Accuracy: 0.9185, Loss: 0.0575
Epoch   3 Batch  250/538 - Train Accuracy: 0.9523, Validation Accuracy: 0.9336, Loss: 0.0574
Epoch   3 Batch  275/538 - Train Accuracy: 0.9193, Validation Accuracy: 0.9313, Loss: 0.0832
Epoch   3 Batch  300/538 - Train Accuracy: 0.9230, Validation Accuracy: 0.9309, Loss: 0.0571
Epoch   3 Batch  325/538 - Train Accuracy: 0.9384, Validation Accuracy: 0.9217, Loss: 0.0478
Epoch   3 Batch  350/538 - Train Accuracy: 0.9429, Validation Accuracy: 0.9345, Loss: 0.0537
Epoch   3 Batch  375/538 - Train Accuracy: 0.9490, Validation Accuracy: 0.9235, Loss: 0.0439
Epoch   3 Batch  400/538 - Train Accuracy: 0.9444, Validation Accuracy: 0.9226, Loss: 0.0441
Epoch   3 Batch  425/538 - Train Accuracy: 0.9416, Validation Accuracy: 0.9361, Loss: 0.0507
Epoch   3 Batch  450/538 - Train Accuracy: 0.9288, Validation Accuracy: 0.9251, Loss: 0.0577
Epoch   3 Batch  475/538 - Train Accuracy: 0.9462, Validation Accuracy: 0.9254, Loss: 0.0508
Epoch   3 Batch  500/538 - Train Accuracy: 0.9718, Validation Accuracy: 0.9350, Loss: 0.0367
Epoch   3 Batch  525/538 - Train Accuracy: 0.9516, Validation Accuracy: 0.9450, Loss: 0.0422
Epoch   4 Batch   25/538 - Train Accuracy: 0.9367, Validation Accuracy: 0.9304, Loss: 0.0457
Epoch   4 Batch   50/538 - Train Accuracy: 0.9672, Validation Accuracy: 0.9320, Loss: 0.0384
Epoch   4 Batch   75/538 - Train Accuracy: 0.9555, Validation Accuracy: 0.9457, Loss: 0.0353
Epoch   4 Batch  100/538 - Train Accuracy: 0.9520, Validation Accuracy: 0.9558, Loss: 0.0330
Epoch   4 Batch  125/538 - Train Accuracy: 0.9621, Validation Accuracy: 0.9616, Loss: 0.0436
Epoch   4 Batch  150/538 - Train Accuracy: 0.9625, Validation Accuracy: 0.9482, Loss: 0.0354
Epoch   4 Batch  175/538 - Train Accuracy: 0.9572, Validation Accuracy: 0.9345, Loss: 0.0371
Epoch   4 Batch  200/538 - Train Accuracy: 0.9629, Validation Accuracy: 0.9506, Loss: 0.0319
Epoch   4 Batch  225/538 - Train Accuracy: 0.9598, Validation Accuracy: 0.9409, Loss: 0.0377
Epoch   4 Batch  250/538 - Train Accuracy: 0.9600, Validation Accuracy: 0.9339, Loss: 0.0452
Epoch   4 Batch  275/538 - Train Accuracy: 0.9623, Validation Accuracy: 0.9400, Loss: 0.0425
Epoch   4 Batch  300/538 - Train Accuracy: 0.9513, Validation Accuracy: 0.9393, Loss: 0.0337
Epoch   4 Batch  325/538 - Train Accuracy: 0.9539, Validation Accuracy: 0.9368, Loss: 0.0336
Epoch   4 Batch  350/538 - Train Accuracy: 0.9522, Validation Accuracy: 0.9556, Loss: 0.0348
Epoch   4 Batch  375/538 - Train Accuracy: 0.9667, Validation Accuracy: 0.9490, Loss: 0.0310
Epoch   4 Batch  400/538 - Train Accuracy: 0.9617, Validation Accuracy: 0.9590, Loss: 0.0300
Epoch   4 Batch  425/538 - Train Accuracy: 0.9559, Validation Accuracy: 0.9558, Loss: 0.0401
Epoch   4 Batch  450/538 - Train Accuracy: 0.9405, Validation Accuracy: 0.9560, Loss: 0.0356
Epoch   4 Batch  475/538 - Train Accuracy: 0.9617, Validation Accuracy: 0.9476, Loss: 0.0253
Epoch   4 Batch  500/538 - Train Accuracy: 0.9714, Validation Accuracy: 0.9455, Loss: 0.0215
Epoch   4 Batch  525/538 - Train Accuracy: 0.9609, Validation Accuracy: 0.9531, Loss: 0.0316
Epoch   5 Batch   25/538 - Train Accuracy: 0.9557, Validation Accuracy: 0.9393, Loss: 0.0344
Epoch   5 Batch   50/538 - Train Accuracy: 0.9672, Validation Accuracy: 0.9471, Loss: 0.0283
Epoch   5 Batch   75/538 - Train Accuracy: 0.9596, Validation Accuracy: 0.9458, Loss: 0.0274
Epoch   5 Batch  100/538 - Train Accuracy: 0.9715, Validation Accuracy: 0.9577, Loss: 0.0245
Epoch   5 Batch  125/538 - Train Accuracy: 0.9727, Validation Accuracy: 0.9553, Loss: 0.0289
Epoch   5 Batch  150/538 - Train Accuracy: 0.9631, Validation Accuracy: 0.9519, Loss: 0.0262
Epoch   5 Batch  175/538 - Train Accuracy: 0.9758, Validation Accuracy: 0.9460, Loss: 0.0252
Epoch   5 Batch  200/538 - Train Accuracy: 0.9738, Validation Accuracy: 0.9569, Loss: 0.0206
Epoch   5 Batch  225/538 - Train Accuracy: 0.9695, Validation Accuracy: 0.9423, Loss: 0.0269
Epoch   5 Batch  250/538 - Train Accuracy: 0.9623, Validation Accuracy: 0.9464, Loss: 0.0260
Epoch   5 Batch  275/538 - Train Accuracy: 0.9551, Validation Accuracy: 0.9466, Loss: 0.0323
Epoch   5 Batch  300/538 - Train Accuracy: 0.9565, Validation Accuracy: 0.9473, Loss: 0.0288
Epoch   5 Batch  325/538 - Train Accuracy: 0.9723, Validation Accuracy: 0.9551, Loss: 0.0276
Epoch   5 Batch  350/538 - Train Accuracy: 0.9676, Validation Accuracy: 0.9496, Loss: 0.0262
Epoch   5 Batch  375/538 - Train Accuracy: 0.9723, Validation Accuracy: 0.9556, Loss: 0.0223
Epoch   5 Batch  400/538 - Train Accuracy: 0.9730, Validation Accuracy: 0.9499, Loss: 0.0234
Epoch   5 Batch  425/538 - Train Accuracy: 0.9604, Validation Accuracy: 0.9542, Loss: 0.0390
Epoch   5 Batch  450/538 - Train Accuracy: 0.9557, Validation Accuracy: 0.9668, Loss: 0.0303
Epoch   5 Batch  475/538 - Train Accuracy: 0.9725, Validation Accuracy: 0.9645, Loss: 0.0209
Epoch   5 Batch  500/538 - Train Accuracy: 0.9846, Validation Accuracy: 0.9583, Loss: 0.0154
Epoch   5 Batch  525/538 - Train Accuracy: 0.9647, Validation Accuracy: 0.9533, Loss: 0.0216
Epoch   6 Batch   25/538 - Train Accuracy: 0.9645, Validation Accuracy: 0.9586, Loss: 0.0265
Epoch   6 Batch   50/538 - Train Accuracy: 0.9609, Validation Accuracy: 0.9432, Loss: 0.0479
Epoch   6 Batch   75/538 - Train Accuracy: 0.9585, Validation Accuracy: 0.9638, Loss: 0.0310
Epoch   6 Batch  100/538 - Train Accuracy: 0.9627, Validation Accuracy: 0.9533, Loss: 0.0413
Epoch   6 Batch  125/538 - Train Accuracy: 0.9673, Validation Accuracy: 0.9538, Loss: 0.0328
Epoch   6 Batch  150/538 - Train Accuracy: 0.9738, Validation Accuracy: 0.9547, Loss: 0.0278
Epoch   6 Batch  175/538 - Train Accuracy: 0.9555, Validation Accuracy: 0.9499, Loss: 0.0237
Epoch   6 Batch  200/538 - Train Accuracy: 0.9697, Validation Accuracy: 0.9576, Loss: 0.0182
Epoch   6 Batch  225/538 - Train Accuracy: 0.9658, Validation Accuracy: 0.9494, Loss: 0.0261
Epoch   6 Batch  250/538 - Train Accuracy: 0.9674, Validation Accuracy: 0.9510, Loss: 0.0211
Epoch   6 Batch  275/538 - Train Accuracy: 0.9623, Validation Accuracy: 0.9442, Loss: 0.0227
Epoch   6 Batch  300/538 - Train Accuracy: 0.9710, Validation Accuracy: 0.9718, Loss: 0.0213
Epoch   6 Batch  325/538 - Train Accuracy: 0.9777, Validation Accuracy: 0.9647, Loss: 0.0234
Epoch   6 Batch  350/538 - Train Accuracy: 0.9708, Validation Accuracy: 0.9615, Loss: 0.0284
Epoch   6 Batch  375/538 - Train Accuracy: 0.9738, Validation Accuracy: 0.9574, Loss: 0.0184
Epoch   6 Batch  400/538 - Train Accuracy: 0.9736, Validation Accuracy: 0.9624, Loss: 0.0221
Epoch   6 Batch  425/538 - Train Accuracy: 0.9583, Validation Accuracy: 0.9661, Loss: 0.0446
Epoch   6 Batch  450/538 - Train Accuracy: 0.9516, Validation Accuracy: 0.9512, Loss: 0.0417
Epoch   6 Batch  475/538 - Train Accuracy: 0.9838, Validation Accuracy: 0.9460, Loss: 0.0267
Epoch   6 Batch  500/538 - Train Accuracy: 0.9812, Validation Accuracy: 0.9528, Loss: 0.0182
Epoch   6 Batch  525/538 - Train Accuracy: 0.9725, Validation Accuracy: 0.9503, Loss: 0.0225
Epoch   7 Batch   25/538 - Train Accuracy: 0.9639, Validation Accuracy: 0.9631, Loss: 0.0215
Epoch   7 Batch   50/538 - Train Accuracy: 0.9691, Validation Accuracy: 0.9593, Loss: 0.0234
Epoch   7 Batch   75/538 - Train Accuracy: 0.9660, Validation Accuracy: 0.9553, Loss: 0.0212
Epoch   7 Batch  100/538 - Train Accuracy: 0.9332, Validation Accuracy: 0.9292, Loss: 0.0797
Epoch   7 Batch  125/538 - Train Accuracy: 0.9652, Validation Accuracy: 0.9457, Loss: 0.0410
Epoch   7 Batch  150/538 - Train Accuracy: 0.9678, Validation Accuracy: 0.9570, Loss: 0.0283
Epoch   7 Batch  175/538 - Train Accuracy: 0.9691, Validation Accuracy: 0.9597, Loss: 0.0243
Epoch   7 Batch  200/538 - Train Accuracy: 0.9703, Validation Accuracy: 0.9604, Loss: 0.0181
Epoch   7 Batch  225/538 - Train Accuracy: 0.9717, Validation Accuracy: 0.9572, Loss: 0.0232
Epoch   7 Batch  250/538 - Train Accuracy: 0.9691, Validation Accuracy: 0.9641, Loss: 0.0215
Epoch   7 Batch  275/538 - Train Accuracy: 0.9729, Validation Accuracy: 0.9542, Loss: 0.0197
Epoch   7 Batch  300/538 - Train Accuracy: 0.9734, Validation Accuracy: 0.9574, Loss: 0.0212
Epoch   7 Batch  325/538 - Train Accuracy: 0.9814, Validation Accuracy: 0.9604, Loss: 0.0201
Epoch   7 Batch  350/538 - Train Accuracy: 0.9766, Validation Accuracy: 0.9579, Loss: 0.0213
Epoch   7 Batch  375/538 - Train Accuracy: 0.9849, Validation Accuracy: 0.9576, Loss: 0.0132
Epoch   7 Batch  400/538 - Train Accuracy: 0.9805, Validation Accuracy: 0.9693, Loss: 0.0198
Epoch   7 Batch  425/538 - Train Accuracy: 0.9680, Validation Accuracy: 0.9585, Loss: 0.0262
Epoch   7 Batch  450/538 - Train Accuracy: 0.9626, Validation Accuracy: 0.9640, Loss: 0.0255
Epoch   7 Batch  475/538 - Train Accuracy: 0.9745, Validation Accuracy: 0.9554, Loss: 0.0162
Epoch   7 Batch  500/538 - Train Accuracy: 0.9940, Validation Accuracy: 0.9631, Loss: 0.0109
Epoch   7 Batch  525/538 - Train Accuracy: 0.9708, Validation Accuracy: 0.9632, Loss: 0.0186
Epoch   8 Batch   25/538 - Train Accuracy: 0.9744, Validation Accuracy: 0.9460, Loss: 0.0213
Epoch   8 Batch   50/538 - Train Accuracy: 0.9744, Validation Accuracy: 0.9565, Loss: 0.0182
Epoch   8 Batch   75/538 - Train Accuracy: 0.9754, Validation Accuracy: 0.9679, Loss: 0.0190
Epoch   8 Batch  100/538 - Train Accuracy: 0.9832, Validation Accuracy: 0.9652, Loss: 0.0165
Epoch   8 Batch  125/538 - Train Accuracy: 0.9799, Validation Accuracy: 0.9631, Loss: 0.0216
Epoch   8 Batch  150/538 - Train Accuracy: 0.9756, Validation Accuracy: 0.9689, Loss: 0.0183
Epoch   8 Batch  175/538 - Train Accuracy: 0.9805, Validation Accuracy: 0.9632, Loss: 0.0139
Epoch   8 Batch  200/538 - Train Accuracy: 0.9740, Validation Accuracy: 0.9593, Loss: 0.0194
Epoch   8 Batch  225/538 - Train Accuracy: 0.9665, Validation Accuracy: 0.9428, Loss: 0.0317
Epoch   8 Batch  250/538 - Train Accuracy: 0.9816, Validation Accuracy: 0.9641, Loss: 0.0263
Epoch   8 Batch  275/538 - Train Accuracy: 0.9732, Validation Accuracy: 0.9664, Loss: 0.0229
Epoch   8 Batch  300/538 - Train Accuracy: 0.9758, Validation Accuracy: 0.9702, Loss: 0.0199
Epoch   8 Batch  325/538 - Train Accuracy: 0.9851, Validation Accuracy: 0.9707, Loss: 0.0177
Epoch   8 Batch  350/538 - Train Accuracy: 0.9781, Validation Accuracy: 0.9682, Loss: 0.0175
Epoch   8 Batch  375/538 - Train Accuracy: 0.9825, Validation Accuracy: 0.9602, Loss: 0.0161
Epoch   8 Batch  400/538 - Train Accuracy: 0.9829, Validation Accuracy: 0.9602, Loss: 0.0120
Epoch   8 Batch  425/538 - Train Accuracy: 0.9676, Validation Accuracy: 0.9691, Loss: 0.0305
Epoch   8 Batch  450/538 - Train Accuracy: 0.9658, Validation Accuracy: 0.9650, Loss: 0.0247
Epoch   8 Batch  475/538 - Train Accuracy: 0.9894, Validation Accuracy: 0.9718, Loss: 0.0129
Epoch   8 Batch  500/538 - Train Accuracy: 0.9856, Validation Accuracy: 0.9647, Loss: 0.0152
Epoch   8 Batch  525/538 - Train Accuracy: 0.9799, Validation Accuracy: 0.9702, Loss: 0.0198
Epoch   9 Batch   25/538 - Train Accuracy: 0.9703, Validation Accuracy: 0.9707, Loss: 0.0151
Epoch   9 Batch   50/538 - Train Accuracy: 0.9814, Validation Accuracy: 0.9679, Loss: 0.0151
Epoch   9 Batch   75/538 - Train Accuracy: 0.9762, Validation Accuracy: 0.9666, Loss: 0.0125
Epoch   9 Batch  100/538 - Train Accuracy: 0.9838, Validation Accuracy: 0.9709, Loss: 0.0154
Epoch   9 Batch  125/538 - Train Accuracy: 0.9730, Validation Accuracy: 0.9652, Loss: 0.0196
Epoch   9 Batch  150/538 - Train Accuracy: 0.9854, Validation Accuracy: 0.9767, Loss: 0.0153
Epoch   9 Batch  175/538 - Train Accuracy: 0.9779, Validation Accuracy: 0.9652, Loss: 0.0122
Epoch   9 Batch  200/538 - Train Accuracy: 0.9771, Validation Accuracy: 0.9654, Loss: 0.0141
Epoch   9 Batch  225/538 - Train Accuracy: 0.9788, Validation Accuracy: 0.9602, Loss: 0.0223
Epoch   9 Batch  250/538 - Train Accuracy: 0.9764, Validation Accuracy: 0.9672, Loss: 0.0370
Epoch   9 Batch  275/538 - Train Accuracy: 0.9648, Validation Accuracy: 0.9647, Loss: 0.0340
Epoch   9 Batch  300/538 - Train Accuracy: 0.9753, Validation Accuracy: 0.9677, Loss: 0.0265
Epoch   9 Batch  325/538 - Train Accuracy: 0.9764, Validation Accuracy: 0.9664, Loss: 0.0223
Epoch   9 Batch  350/538 - Train Accuracy: 0.9753, Validation Accuracy: 0.9661, Loss: 0.0251
Epoch   9 Batch  375/538 - Train Accuracy: 0.9879, Validation Accuracy: 0.9629, Loss: 0.0195
Epoch   9 Batch  400/538 - Train Accuracy: 0.9877, Validation Accuracy: 0.9604, Loss: 0.0181
Epoch   9 Batch  425/538 - Train Accuracy: 0.9751, Validation Accuracy: 0.9734, Loss: 0.0256
Epoch   9 Batch  450/538 - Train Accuracy: 0.9738, Validation Accuracy: 0.9730, Loss: 0.0195
Epoch   9 Batch  475/538 - Train Accuracy: 0.9857, Validation Accuracy: 0.9647, Loss: 0.0190
Epoch   9 Batch  500/538 - Train Accuracy: 0.9917, Validation Accuracy: 0.9609, Loss: 0.0104
Epoch   9 Batch  525/538 - Train Accuracy: 0.9749, Validation Accuracy: 0.9723, Loss: 0.0182
Model Trained and Saved

In [20]:
# Visualize the loss and accuracy
import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 6))
ax1.plot(loss_list, color='red')
ax1.set_title('Traning Loss')
ax1.set_ylabel('Loss value')

ax2.plot(valid_acc_list)
ax2.set_xlabel('Iterations')
ax2.set_ylabel('Accuracy')
ax2.set_title('Validation Accuracy')
plt.show()


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 [23]:
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
    """
    # Convert the sentence to lowercase
    slower = sentence.lower()

    # Convert words into ids using vocab_to_int
    word_ids = []
    for s in slower.split():
        # Convert words not in the vocabulary, to the <UNK> word id.
        if s not in vocab_to_int:
            s = '<UNK>'
        word_ids.append(vocab_to_int[s])   
    
    return word_ids


"""
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 [33]:
#translate_sentence = 'he saw a old yellow truck .' # il a vu un vieux camion jaune = He saw an old yellow truck
#translate_sentence = 'india is never busy during autumn' # inde est jamais occupé à l'automne , mais il est parfois = India is never busy in the autumn, but it is sometimes
#translate_sentence = 'france is never cold during september' # france ne fait jamais froid au mois de septembre , mais il = France is never cold in September, but it
#translate_sentence = 'your most feared animal is that shark' # la pomme est votre fruit le moins aimé = The apple is your least liked fruit
#translate_sentence = 'our least favorite fruit is the banana' # notre fruit préféré moins est la banane = Our favorite fruit less is banana
#translate_sentence = 'china is hot during july' # chine est chaud en juillet , mais il est calme = Chine is hot in July, but it is quiet
#translate_sentence = 'i fear yellow sharks' # aime la mangue est le français et les = Loves mango is French and
translate_sentence = 'french sharks are yellow' # le pamplemousse et les moins les mangues = Grapefruit and minus mangoes


"""
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:      [134, 11, 92, 191]
  English Words: ['french', 'sharks', 'are', 'yellow']

Prediction
  Word Ids:      [323, 112, 83, 114, 289, 114, 41, 345]
  French Words: le pamplemousse et les moins les mangues .

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.


In [ ]: