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)
    """
    
    source_id_text = []
    for line in source_text.split('\n'):
        source_id_text.append([source_vocab_to_int[word] for word in line.split()])

    target_id_text = []
    for line in target_text.split('\n'):
        target_id_text.append([target_vocab_to_int[word] for word in line.split()] + [target_vocab_to_int['<EOS>']])
    
    return (source_id_text, target_id_text)

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


Tests Passed

Preprocess all the data and save it

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


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

Check Point

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


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

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

Check the Version of TensorFlow and Access to GPU

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


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

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

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


TensorFlow Version: 1.1.0
/Users/mira/anaconda/envs/py36/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 [28]:
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)
    """
    inputs = tf.placeholder(tf.int32, shape=(None, None), name="input")
    targets = tf.placeholder(tf.int32, shape=(None, None))
    learning_rate = tf.placeholder(tf.float32, shape=(), name="learning_rate")
    keep_prob = tf.placeholder(tf.float32, shape=(), name="keep_prob")
    target_sequence_length = tf.placeholder(tf.int32, shape=(None,), name="target_sequence_length")
    max_target_length = tf.reduce_max(target_sequence_length, name="max_target_len")
    source_sequence_length= tf.placeholder(tf.int32, shape=(None,), name="source_sequence_length")
    
    return (inputs, targets, learning_rate, keep_prob, target_sequence_length,
    max_target_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 [29]:
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
    """
    sliced = tf.strided_slice(target_data, [0,0], [batch_size, -1], strides=[1,1])
    return tf.concat([tf.fill([batch_size, 1], target_vocab_to_int['<GO>']), sliced], 1)


"""
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 [30]:
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)
    """
    
    embedding = tf.contrib.layers.embed_sequence(
        rnn_inputs, vocab_size=source_vocab_size, embed_dim=encoding_embedding_size
    )
    stacked_lstm = tf.contrib.rnn.MultiRNNCell(
        [tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(rnn_size), keep_prob) for _ in range(num_layers)]
    )
    
    output, state = tf.nn.dynamic_rnn(
        stacked_lstm,
        embedding,
        sequence_length=source_sequence_length,
        dtype=tf.float32
    )
    return output, state

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


Tests Passed

Decoding - Training

Create a training decoding layer:


In [31]:
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
    """
    
    helper = tf.contrib.seq2seq.TrainingHelper(dec_embed_input, target_sequence_length)
    decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, helper, initial_state=encoder_state, output_layer=output_layer)
    return tf.contrib.seq2seq.dynamic_decode(decoder, maximum_iterations=max_summary_length)[0]

"""
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 [48]:
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')
    helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings, start_tokens, end_of_sequence_id)
    decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, helper, encoder_state, output_layer=output_layer)
    return tf.contrib.seq2seq.dynamic_decode(decoder, maximum_iterations=max_target_sequence_length)[0]

"""
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 [49]:
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)
    """
    dec_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))
    dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input)
    
    dec_cells = tf.contrib.rnn.MultiRNNCell(
        [tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(rnn_size), keep_prob) for _ in range(num_layers)]
    )
    
    output_layer = Dense(target_vocab_size, kernel_initializer=tf.truncated_normal_initializer(stddev=0.1))
    
    with tf.variable_scope('decode'):
        training_decoder_logits = decoding_layer_train(
            encoder_state,
            dec_cells,
            dec_embed_input,
            target_sequence_length,
            max_target_sequence_length,
            output_layer,
            keep_prob
        )
    with tf.variable_scope('decode', reuse=True):
        infer_decoder_logits = decoding_layer_infer(
            encoder_state,
            dec_cells,
            dec_embeddings,
            target_vocab_to_int['<GO>'],
            target_vocab_to_int['<EOS>'],
            max_target_sequence_length,
            target_vocab_size,
            output_layer,
            batch_size,
            keep_prob
        )
    
    return (training_decoder_logits, infer_decoder_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 [51]:
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_layer = 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)
    
    return decoding_layer(
        dec_input,
        enc_layer[1],
        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
    )


"""
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 [110]:
# Number of Epochs
epochs = 2
# Batch Size
batch_size = 128
# RNN Size
rnn_size = 128
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 128
decoding_embedding_size = 128
# Learning Rate
learning_rate = 0.01
# Dropout Keep Probability
keep_probability = 0.7
display_step = 10

Build the Graph

Build the graph using the neural network you implemented.


In [111]:
"""
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 [112]:
"""
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 [113]:
"""
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   10/1077 - Train Accuracy: 0.2911, Validation Accuracy: 0.3800, Loss: 3.3299
Epoch   0 Batch   20/1077 - Train Accuracy: 0.3672, Validation Accuracy: 0.4226, Loss: 2.7903
Epoch   0 Batch   30/1077 - Train Accuracy: 0.4199, Validation Accuracy: 0.4755, Loss: 2.5050
Epoch   0 Batch   40/1077 - Train Accuracy: 0.3777, Validation Accuracy: 0.4222, Loss: 2.2436
Epoch   0 Batch   50/1077 - Train Accuracy: 0.4227, Validation Accuracy: 0.4936, Loss: 2.0978
Epoch   0 Batch   60/1077 - Train Accuracy: 0.4509, Validation Accuracy: 0.5075, Loss: 1.8893
Epoch   0 Batch   70/1077 - Train Accuracy: 0.3898, Validation Accuracy: 0.4347, Loss: 1.7124
Epoch   0 Batch   80/1077 - Train Accuracy: 0.3305, Validation Accuracy: 0.4144, Loss: 1.4166
Epoch   0 Batch   90/1077 - Train Accuracy: 0.4152, Validation Accuracy: 0.4901, Loss: 1.2875
Epoch   0 Batch  100/1077 - Train Accuracy: 0.4883, Validation Accuracy: 0.5163, Loss: 1.0790
Epoch   0 Batch  110/1077 - Train Accuracy: 0.5199, Validation Accuracy: 0.5426, Loss: 0.9638
Epoch   0 Batch  120/1077 - Train Accuracy: 0.4695, Validation Accuracy: 0.5330, Loss: 0.9490
Epoch   0 Batch  130/1077 - Train Accuracy: 0.4833, Validation Accuracy: 0.5000, Loss: 0.8066
Epoch   0 Batch  140/1077 - Train Accuracy: 0.4893, Validation Accuracy: 0.5423, Loss: 0.8772
Epoch   0 Batch  150/1077 - Train Accuracy: 0.5681, Validation Accuracy: 0.5579, Loss: 0.7701
Epoch   0 Batch  160/1077 - Train Accuracy: 0.5484, Validation Accuracy: 0.5415, Loss: 0.7459
Epoch   0 Batch  170/1077 - Train Accuracy: 0.4973, Validation Accuracy: 0.5607, Loss: 0.7755
Epoch   0 Batch  180/1077 - Train Accuracy: 0.5316, Validation Accuracy: 0.5497, Loss: 0.7169
Epoch   0 Batch  190/1077 - Train Accuracy: 0.5902, Validation Accuracy: 0.5810, Loss: 0.6778
Epoch   0 Batch  200/1077 - Train Accuracy: 0.5441, Validation Accuracy: 0.5955, Loss: 0.6918
Epoch   0 Batch  210/1077 - Train Accuracy: 0.5714, Validation Accuracy: 0.5732, Loss: 0.6465
Epoch   0 Batch  220/1077 - Train Accuracy: 0.5732, Validation Accuracy: 0.6005, Loss: 0.6448
Epoch   0 Batch  230/1077 - Train Accuracy: 0.6097, Validation Accuracy: 0.5923, Loss: 0.6340
Epoch   0 Batch  240/1077 - Train Accuracy: 0.6375, Validation Accuracy: 0.6204, Loss: 0.5892
Epoch   0 Batch  250/1077 - Train Accuracy: 0.6104, Validation Accuracy: 0.6165, Loss: 0.5616
Epoch   0 Batch  260/1077 - Train Accuracy: 0.6168, Validation Accuracy: 0.5991, Loss: 0.5479
Epoch   0 Batch  270/1077 - Train Accuracy: 0.5941, Validation Accuracy: 0.6300, Loss: 0.5909
Epoch   0 Batch  280/1077 - Train Accuracy: 0.6398, Validation Accuracy: 0.6385, Loss: 0.5717
Epoch   0 Batch  290/1077 - Train Accuracy: 0.6184, Validation Accuracy: 0.6474, Loss: 0.5647
Epoch   0 Batch  300/1077 - Train Accuracy: 0.6024, Validation Accuracy: 0.6072, Loss: 0.5397
Epoch   0 Batch  310/1077 - Train Accuracy: 0.6395, Validation Accuracy: 0.6254, Loss: 0.5334
Epoch   0 Batch  320/1077 - Train Accuracy: 0.6469, Validation Accuracy: 0.6303, Loss: 0.5056
Epoch   0 Batch  330/1077 - Train Accuracy: 0.6578, Validation Accuracy: 0.6420, Loss: 0.5100
Epoch   0 Batch  340/1077 - Train Accuracy: 0.6106, Validation Accuracy: 0.6374, Loss: 0.5042
Epoch   0 Batch  350/1077 - Train Accuracy: 0.6145, Validation Accuracy: 0.6186, Loss: 0.5020
Epoch   0 Batch  360/1077 - Train Accuracy: 0.5914, Validation Accuracy: 0.6516, Loss: 0.4670
Epoch   0 Batch  370/1077 - Train Accuracy: 0.6734, Validation Accuracy: 0.6584, Loss: 0.4459
Epoch   0 Batch  380/1077 - Train Accuracy: 0.6582, Validation Accuracy: 0.6612, Loss: 0.4397
Epoch   0 Batch  390/1077 - Train Accuracy: 0.6266, Validation Accuracy: 0.6616, Loss: 0.4504
Epoch   0 Batch  400/1077 - Train Accuracy: 0.6992, Validation Accuracy: 0.6488, Loss: 0.4462
Epoch   0 Batch  410/1077 - Train Accuracy: 0.6382, Validation Accuracy: 0.6641, Loss: 0.4461
Epoch   0 Batch  420/1077 - Train Accuracy: 0.6875, Validation Accuracy: 0.6871, Loss: 0.3906
Epoch   0 Batch  430/1077 - Train Accuracy: 0.6551, Validation Accuracy: 0.6630, Loss: 0.4004
Epoch   0 Batch  440/1077 - Train Accuracy: 0.6930, Validation Accuracy: 0.6850, Loss: 0.4171
Epoch   0 Batch  450/1077 - Train Accuracy: 0.6711, Validation Accuracy: 0.6839, Loss: 0.3811
Epoch   0 Batch  460/1077 - Train Accuracy: 0.6844, Validation Accuracy: 0.7273, Loss: 0.3914
Epoch   0 Batch  470/1077 - Train Accuracy: 0.6711, Validation Accuracy: 0.6928, Loss: 0.3895
Epoch   0 Batch  480/1077 - Train Accuracy: 0.7336, Validation Accuracy: 0.6921, Loss: 0.3624
Epoch   0 Batch  490/1077 - Train Accuracy: 0.7035, Validation Accuracy: 0.7077, Loss: 0.3459
Epoch   0 Batch  500/1077 - Train Accuracy: 0.7691, Validation Accuracy: 0.6921, Loss: 0.3256
Epoch   0 Batch  510/1077 - Train Accuracy: 0.6992, Validation Accuracy: 0.6939, Loss: 0.3272
Epoch   0 Batch  520/1077 - Train Accuracy: 0.7247, Validation Accuracy: 0.7056, Loss: 0.2955
Epoch   0 Batch  530/1077 - Train Accuracy: 0.6781, Validation Accuracy: 0.7099, Loss: 0.3102
Epoch   0 Batch  540/1077 - Train Accuracy: 0.7383, Validation Accuracy: 0.7045, Loss: 0.2754
Epoch   0 Batch  550/1077 - Train Accuracy: 0.6926, Validation Accuracy: 0.7362, Loss: 0.3045
Epoch   0 Batch  560/1077 - Train Accuracy: 0.7617, Validation Accuracy: 0.7248, Loss: 0.2849
Epoch   0 Batch  570/1077 - Train Accuracy: 0.7064, Validation Accuracy: 0.7173, Loss: 0.2932
Epoch   0 Batch  580/1077 - Train Accuracy: 0.8051, Validation Accuracy: 0.7525, Loss: 0.2471
Epoch   0 Batch  590/1077 - Train Accuracy: 0.6797, Validation Accuracy: 0.7077, Loss: 0.2932
Epoch   0 Batch  600/1077 - Train Accuracy: 0.7422, Validation Accuracy: 0.7330, Loss: 0.2526
Epoch   0 Batch  610/1077 - Train Accuracy: 0.7430, Validation Accuracy: 0.7319, Loss: 0.2639
Epoch   0 Batch  620/1077 - Train Accuracy: 0.7496, Validation Accuracy: 0.7699, Loss: 0.2411
Epoch   0 Batch  630/1077 - Train Accuracy: 0.8000, Validation Accuracy: 0.7731, Loss: 0.2425
Epoch   0 Batch  640/1077 - Train Accuracy: 0.7608, Validation Accuracy: 0.7582, Loss: 0.2314
Epoch   0 Batch  650/1077 - Train Accuracy: 0.7375, Validation Accuracy: 0.7866, Loss: 0.2441
Epoch   0 Batch  660/1077 - Train Accuracy: 0.7695, Validation Accuracy: 0.7724, Loss: 0.2335
Epoch   0 Batch  670/1077 - Train Accuracy: 0.8072, Validation Accuracy: 0.7940, Loss: 0.2177
Epoch   0 Batch  680/1077 - Train Accuracy: 0.7783, Validation Accuracy: 0.7891, Loss: 0.2156
Epoch   0 Batch  690/1077 - Train Accuracy: 0.8305, Validation Accuracy: 0.7827, Loss: 0.2038
Epoch   0 Batch  700/1077 - Train Accuracy: 0.8313, Validation Accuracy: 0.7987, Loss: 0.1921
Epoch   0 Batch  710/1077 - Train Accuracy: 0.8223, Validation Accuracy: 0.8004, Loss: 0.1858
Epoch   0 Batch  720/1077 - Train Accuracy: 0.7932, Validation Accuracy: 0.7940, Loss: 0.2022
Epoch   0 Batch  730/1077 - Train Accuracy: 0.8195, Validation Accuracy: 0.7660, Loss: 0.1879
Epoch   0 Batch  740/1077 - Train Accuracy: 0.8293, Validation Accuracy: 0.8132, Loss: 0.1666
Epoch   0 Batch  750/1077 - Train Accuracy: 0.8238, Validation Accuracy: 0.7891, Loss: 0.1710
Epoch   0 Batch  760/1077 - Train Accuracy: 0.8355, Validation Accuracy: 0.7820, Loss: 0.1924
Epoch   0 Batch  770/1077 - Train Accuracy: 0.8192, Validation Accuracy: 0.7962, Loss: 0.1738
Epoch   0 Batch  780/1077 - Train Accuracy: 0.8277, Validation Accuracy: 0.7955, Loss: 0.2047
Epoch   0 Batch  790/1077 - Train Accuracy: 0.7684, Validation Accuracy: 0.8015, Loss: 0.1824
Epoch   0 Batch  800/1077 - Train Accuracy: 0.8340, Validation Accuracy: 0.8033, Loss: 0.1672
Epoch   0 Batch  810/1077 - Train Accuracy: 0.8609, Validation Accuracy: 0.7915, Loss: 0.1470
Epoch   0 Batch  820/1077 - Train Accuracy: 0.8117, Validation Accuracy: 0.8054, Loss: 0.1685
Epoch   0 Batch  830/1077 - Train Accuracy: 0.8242, Validation Accuracy: 0.8491, Loss: 0.1543
Epoch   0 Batch  840/1077 - Train Accuracy: 0.8629, Validation Accuracy: 0.8278, Loss: 0.1496
Epoch   0 Batch  850/1077 - Train Accuracy: 0.8136, Validation Accuracy: 0.8228, Loss: 0.1670
Epoch   0 Batch  860/1077 - Train Accuracy: 0.8605, Validation Accuracy: 0.8338, Loss: 0.1563
Epoch   0 Batch  870/1077 - Train Accuracy: 0.8191, Validation Accuracy: 0.8089, Loss: 0.1523
Epoch   0 Batch  880/1077 - Train Accuracy: 0.8969, Validation Accuracy: 0.8441, Loss: 0.1443
Epoch   0 Batch  890/1077 - Train Accuracy: 0.8821, Validation Accuracy: 0.8285, Loss: 0.1362
Epoch   0 Batch  900/1077 - Train Accuracy: 0.8723, Validation Accuracy: 0.8423, Loss: 0.1382
Epoch   0 Batch  910/1077 - Train Accuracy: 0.8568, Validation Accuracy: 0.8097, Loss: 0.1375
Epoch   0 Batch  920/1077 - Train Accuracy: 0.8336, Validation Accuracy: 0.8342, Loss: 0.1457
Epoch   0 Batch  930/1077 - Train Accuracy: 0.8422, Validation Accuracy: 0.8327, Loss: 0.1170
Epoch   0 Batch  940/1077 - Train Accuracy: 0.8539, Validation Accuracy: 0.8104, Loss: 0.1216
Epoch   0 Batch  950/1077 - Train Accuracy: 0.8806, Validation Accuracy: 0.8185, Loss: 0.1231
Epoch   0 Batch  960/1077 - Train Accuracy: 0.8694, Validation Accuracy: 0.8164, Loss: 0.1218
Epoch   0 Batch  970/1077 - Train Accuracy: 0.8738, Validation Accuracy: 0.8555, Loss: 0.1218
Epoch   0 Batch  980/1077 - Train Accuracy: 0.8508, Validation Accuracy: 0.8413, Loss: 0.1228
Epoch   0 Batch  990/1077 - Train Accuracy: 0.8565, Validation Accuracy: 0.8572, Loss: 0.1318
Epoch   0 Batch 1000/1077 - Train Accuracy: 0.8642, Validation Accuracy: 0.8299, Loss: 0.1048
Epoch   0 Batch 1010/1077 - Train Accuracy: 0.9184, Validation Accuracy: 0.8398, Loss: 0.1039
Epoch   0 Batch 1020/1077 - Train Accuracy: 0.8820, Validation Accuracy: 0.8150, Loss: 0.0988
Epoch   0 Batch 1030/1077 - Train Accuracy: 0.8797, Validation Accuracy: 0.8256, Loss: 0.1089
Epoch   0 Batch 1040/1077 - Train Accuracy: 0.8931, Validation Accuracy: 0.8001, Loss: 0.1173
Epoch   0 Batch 1050/1077 - Train Accuracy: 0.8426, Validation Accuracy: 0.8221, Loss: 0.1045
Epoch   0 Batch 1060/1077 - Train Accuracy: 0.8945, Validation Accuracy: 0.8558, Loss: 0.0981
Epoch   0 Batch 1070/1077 - Train Accuracy: 0.8695, Validation Accuracy: 0.8469, Loss: 0.1046
Epoch   1 Batch   10/1077 - Train Accuracy: 0.8964, Validation Accuracy: 0.8370, Loss: 0.1008
Epoch   1 Batch   20/1077 - Train Accuracy: 0.8684, Validation Accuracy: 0.8232, Loss: 0.0811
Epoch   1 Batch   30/1077 - Train Accuracy: 0.9148, Validation Accuracy: 0.8413, Loss: 0.0889
Epoch   1 Batch   40/1077 - Train Accuracy: 0.8918, Validation Accuracy: 0.8484, Loss: 0.0873
Epoch   1 Batch   50/1077 - Train Accuracy: 0.9285, Validation Accuracy: 0.8697, Loss: 0.0891
Epoch   1 Batch   60/1077 - Train Accuracy: 0.8996, Validation Accuracy: 0.8235, Loss: 0.0890
Epoch   1 Batch   70/1077 - Train Accuracy: 0.8799, Validation Accuracy: 0.8494, Loss: 0.1046
Epoch   1 Batch   80/1077 - Train Accuracy: 0.8836, Validation Accuracy: 0.8597, Loss: 0.0917
Epoch   1 Batch   90/1077 - Train Accuracy: 0.8727, Validation Accuracy: 0.8562, Loss: 0.0972
Epoch   1 Batch  100/1077 - Train Accuracy: 0.8930, Validation Accuracy: 0.8832, Loss: 0.0950
Epoch   1 Batch  110/1077 - Train Accuracy: 0.9293, Validation Accuracy: 0.8505, Loss: 0.0712
Epoch   1 Batch  120/1077 - Train Accuracy: 0.8746, Validation Accuracy: 0.8643, Loss: 0.0942
Epoch   1 Batch  130/1077 - Train Accuracy: 0.8962, Validation Accuracy: 0.8455, Loss: 0.0756
Epoch   1 Batch  140/1077 - Train Accuracy: 0.9091, Validation Accuracy: 0.8590, Loss: 0.0818
Epoch   1 Batch  150/1077 - Train Accuracy: 0.9003, Validation Accuracy: 0.8501, Loss: 0.0832
Epoch   1 Batch  160/1077 - Train Accuracy: 0.9141, Validation Accuracy: 0.8363, Loss: 0.0708
Epoch   1 Batch  170/1077 - Train Accuracy: 0.8863, Validation Accuracy: 0.8494, Loss: 0.0789
Epoch   1 Batch  180/1077 - Train Accuracy: 0.8992, Validation Accuracy: 0.8640, Loss: 0.0720
Epoch   1 Batch  190/1077 - Train Accuracy: 0.9293, Validation Accuracy: 0.8736, Loss: 0.0859
Epoch   1 Batch  200/1077 - Train Accuracy: 0.8941, Validation Accuracy: 0.8558, Loss: 0.0791
Epoch   1 Batch  210/1077 - Train Accuracy: 0.9107, Validation Accuracy: 0.8718, Loss: 0.0910
Epoch   1 Batch  220/1077 - Train Accuracy: 0.9309, Validation Accuracy: 0.8711, Loss: 0.0707
Epoch   1 Batch  230/1077 - Train Accuracy: 0.8888, Validation Accuracy: 0.8587, Loss: 0.0773
Epoch   1 Batch  240/1077 - Train Accuracy: 0.9488, Validation Accuracy: 0.8604, Loss: 0.0721
Epoch   1 Batch  250/1077 - Train Accuracy: 0.9073, Validation Accuracy: 0.8335, Loss: 0.0789
Epoch   1 Batch  260/1077 - Train Accuracy: 0.9077, Validation Accuracy: 0.8580, Loss: 0.0663
Epoch   1 Batch  270/1077 - Train Accuracy: 0.8562, Validation Accuracy: 0.8743, Loss: 0.0858
Epoch   1 Batch  280/1077 - Train Accuracy: 0.8855, Validation Accuracy: 0.8849, Loss: 0.0815
Epoch   1 Batch  290/1077 - Train Accuracy: 0.9129, Validation Accuracy: 0.8601, Loss: 0.0963
Epoch   1 Batch  300/1077 - Train Accuracy: 0.9153, Validation Accuracy: 0.8700, Loss: 0.0702
Epoch   1 Batch  310/1077 - Train Accuracy: 0.9102, Validation Accuracy: 0.9006, Loss: 0.0750
Epoch   1 Batch  320/1077 - Train Accuracy: 0.9270, Validation Accuracy: 0.8693, Loss: 0.0830
Epoch   1 Batch  330/1077 - Train Accuracy: 0.8895, Validation Accuracy: 0.8871, Loss: 0.0766
Epoch   1 Batch  340/1077 - Train Accuracy: 0.9009, Validation Accuracy: 0.8764, Loss: 0.0705
Epoch   1 Batch  350/1077 - Train Accuracy: 0.8973, Validation Accuracy: 0.8647, Loss: 0.0797
Epoch   1 Batch  360/1077 - Train Accuracy: 0.9395, Validation Accuracy: 0.8832, Loss: 0.0655
Epoch   1 Batch  370/1077 - Train Accuracy: 0.9401, Validation Accuracy: 0.8469, Loss: 0.0679
Epoch   1 Batch  380/1077 - Train Accuracy: 0.9230, Validation Accuracy: 0.8821, Loss: 0.0634
Epoch   1 Batch  390/1077 - Train Accuracy: 0.8742, Validation Accuracy: 0.8864, Loss: 0.0850
Epoch   1 Batch  400/1077 - Train Accuracy: 0.8941, Validation Accuracy: 0.8647, Loss: 0.0826
Epoch   1 Batch  410/1077 - Train Accuracy: 0.9083, Validation Accuracy: 0.8881, Loss: 0.0771
Epoch   1 Batch  420/1077 - Train Accuracy: 0.9473, Validation Accuracy: 0.9009, Loss: 0.0560
Epoch   1 Batch  430/1077 - Train Accuracy: 0.9039, Validation Accuracy: 0.8722, Loss: 0.0601
Epoch   1 Batch  440/1077 - Train Accuracy: 0.8848, Validation Accuracy: 0.8647, Loss: 0.0874
Epoch   1 Batch  450/1077 - Train Accuracy: 0.9180, Validation Accuracy: 0.8629, Loss: 0.0694
Epoch   1 Batch  460/1077 - Train Accuracy: 0.9172, Validation Accuracy: 0.9084, Loss: 0.0723
Epoch   1 Batch  470/1077 - Train Accuracy: 0.9260, Validation Accuracy: 0.8974, Loss: 0.0670
Epoch   1 Batch  480/1077 - Train Accuracy: 0.9194, Validation Accuracy: 0.8764, Loss: 0.0652
Epoch   1 Batch  490/1077 - Train Accuracy: 0.9195, Validation Accuracy: 0.8849, Loss: 0.0672
Epoch   1 Batch  500/1077 - Train Accuracy: 0.9375, Validation Accuracy: 0.8963, Loss: 0.0526
Epoch   1 Batch  510/1077 - Train Accuracy: 0.8793, Validation Accuracy: 0.8778, Loss: 0.0726
Epoch   1 Batch  520/1077 - Train Accuracy: 0.9468, Validation Accuracy: 0.8896, Loss: 0.0586
Epoch   1 Batch  530/1077 - Train Accuracy: 0.9059, Validation Accuracy: 0.8803, Loss: 0.0701
Epoch   1 Batch  540/1077 - Train Accuracy: 0.9160, Validation Accuracy: 0.8793, Loss: 0.0590
Epoch   1 Batch  550/1077 - Train Accuracy: 0.8922, Validation Accuracy: 0.8885, Loss: 0.0643
Epoch   1 Batch  560/1077 - Train Accuracy: 0.9148, Validation Accuracy: 0.8920, Loss: 0.0679
Epoch   1 Batch  570/1077 - Train Accuracy: 0.8976, Validation Accuracy: 0.8846, Loss: 0.0731
Epoch   1 Batch  580/1077 - Train Accuracy: 0.9263, Validation Accuracy: 0.8960, Loss: 0.0573
Epoch   1 Batch  590/1077 - Train Accuracy: 0.9112, Validation Accuracy: 0.8839, Loss: 0.0660
Epoch   1 Batch  600/1077 - Train Accuracy: 0.9282, Validation Accuracy: 0.9165, Loss: 0.0695
Epoch   1 Batch  610/1077 - Train Accuracy: 0.9194, Validation Accuracy: 0.9112, Loss: 0.0677
Epoch   1 Batch  620/1077 - Train Accuracy: 0.9441, Validation Accuracy: 0.9009, Loss: 0.0572
Epoch   1 Batch  630/1077 - Train Accuracy: 0.9242, Validation Accuracy: 0.8988, Loss: 0.0553
Epoch   1 Batch  640/1077 - Train Accuracy: 0.9118, Validation Accuracy: 0.8917, Loss: 0.0549
Epoch   1 Batch  650/1077 - Train Accuracy: 0.9398, Validation Accuracy: 0.9279, Loss: 0.0590
Epoch   1 Batch  660/1077 - Train Accuracy: 0.9340, Validation Accuracy: 0.9105, Loss: 0.0561
Epoch   1 Batch  670/1077 - Train Accuracy: 0.9304, Validation Accuracy: 0.9180, Loss: 0.0619
Epoch   1 Batch  680/1077 - Train Accuracy: 0.9167, Validation Accuracy: 0.9187, Loss: 0.0634
Epoch   1 Batch  690/1077 - Train Accuracy: 0.9320, Validation Accuracy: 0.8995, Loss: 0.0572
Epoch   1 Batch  700/1077 - Train Accuracy: 0.9344, Validation Accuracy: 0.8935, Loss: 0.0486
Epoch   1 Batch  710/1077 - Train Accuracy: 0.9234, Validation Accuracy: 0.9134, Loss: 0.0525
Epoch   1 Batch  720/1077 - Train Accuracy: 0.9174, Validation Accuracy: 0.9048, Loss: 0.0577
Epoch   1 Batch  730/1077 - Train Accuracy: 0.9180, Validation Accuracy: 0.8864, Loss: 0.0687
Epoch   1 Batch  740/1077 - Train Accuracy: 0.9187, Validation Accuracy: 0.9094, Loss: 0.0556
Epoch   1 Batch  750/1077 - Train Accuracy: 0.9305, Validation Accuracy: 0.9059, Loss: 0.0514
Epoch   1 Batch  760/1077 - Train Accuracy: 0.9203, Validation Accuracy: 0.9254, Loss: 0.0671
Epoch   1 Batch  770/1077 - Train Accuracy: 0.9204, Validation Accuracy: 0.9016, Loss: 0.0566
Epoch   1 Batch  780/1077 - Train Accuracy: 0.9008, Validation Accuracy: 0.9038, Loss: 0.0743
Epoch   1 Batch  790/1077 - Train Accuracy: 0.8684, Validation Accuracy: 0.8867, Loss: 0.0654
Epoch   1 Batch  800/1077 - Train Accuracy: 0.9301, Validation Accuracy: 0.9002, Loss: 0.0578
Epoch   1 Batch  810/1077 - Train Accuracy: 0.9148, Validation Accuracy: 0.9194, Loss: 0.0517
Epoch   1 Batch  820/1077 - Train Accuracy: 0.9086, Validation Accuracy: 0.8991, Loss: 0.0649
Epoch   1 Batch  830/1077 - Train Accuracy: 0.8832, Validation Accuracy: 0.9002, Loss: 0.0647
Epoch   1 Batch  840/1077 - Train Accuracy: 0.9258, Validation Accuracy: 0.8878, Loss: 0.0482
Epoch   1 Batch  850/1077 - Train Accuracy: 0.8817, Validation Accuracy: 0.8960, Loss: 0.0848
Epoch   1 Batch  860/1077 - Train Accuracy: 0.9282, Validation Accuracy: 0.9116, Loss: 0.0601
Epoch   1 Batch  870/1077 - Train Accuracy: 0.9062, Validation Accuracy: 0.9066, Loss: 0.0576
Epoch   1 Batch  880/1077 - Train Accuracy: 0.9309, Validation Accuracy: 0.9290, Loss: 0.0612
Epoch   1 Batch  890/1077 - Train Accuracy: 0.9148, Validation Accuracy: 0.8821, Loss: 0.0581
Epoch   1 Batch  900/1077 - Train Accuracy: 0.9410, Validation Accuracy: 0.9322, Loss: 0.0640
Epoch   1 Batch  910/1077 - Train Accuracy: 0.9152, Validation Accuracy: 0.9222, Loss: 0.0538
Epoch   1 Batch  920/1077 - Train Accuracy: 0.9262, Validation Accuracy: 0.9141, Loss: 0.0483
Epoch   1 Batch  930/1077 - Train Accuracy: 0.9152, Validation Accuracy: 0.9190, Loss: 0.0466
Epoch   1 Batch  940/1077 - Train Accuracy: 0.9266, Validation Accuracy: 0.9091, Loss: 0.0483
Epoch   1 Batch  950/1077 - Train Accuracy: 0.9360, Validation Accuracy: 0.9212, Loss: 0.0521
Epoch   1 Batch  960/1077 - Train Accuracy: 0.9408, Validation Accuracy: 0.8828, Loss: 0.0572
Epoch   1 Batch  970/1077 - Train Accuracy: 0.9215, Validation Accuracy: 0.8984, Loss: 0.0625
Epoch   1 Batch  980/1077 - Train Accuracy: 0.8918, Validation Accuracy: 0.8970, Loss: 0.0585
Epoch   1 Batch  990/1077 - Train Accuracy: 0.9112, Validation Accuracy: 0.9219, Loss: 0.0686
Epoch   1 Batch 1000/1077 - Train Accuracy: 0.9096, Validation Accuracy: 0.9155, Loss: 0.0477
Epoch   1 Batch 1010/1077 - Train Accuracy: 0.9543, Validation Accuracy: 0.9151, Loss: 0.0472
Epoch   1 Batch 1020/1077 - Train Accuracy: 0.9383, Validation Accuracy: 0.8956, Loss: 0.0511
Epoch   1 Batch 1030/1077 - Train Accuracy: 0.9219, Validation Accuracy: 0.8995, Loss: 0.0624
Epoch   1 Batch 1040/1077 - Train Accuracy: 0.9211, Validation Accuracy: 0.9034, Loss: 0.0598
Epoch   1 Batch 1050/1077 - Train Accuracy: 0.9160, Validation Accuracy: 0.9034, Loss: 0.0450
Epoch   1 Batch 1060/1077 - Train Accuracy: 0.9070, Validation Accuracy: 0.8920, Loss: 0.0502
Epoch   1 Batch 1070/1077 - Train Accuracy: 0.9359, Validation Accuracy: 0.9031, Loss: 0.0572
Model Trained and Saved

Save Parameters

Save the batch_size and save_path parameters for inference.


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

Checkpoint


In [115]:
"""
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 [116]:
def sentence_to_seq(sentence, vocab_to_int):
    """
    Convert a sentence to a sequence of ids
    :param sentence: String
    :param vocab_to_int: Dictionary to go from the words to an id
    :return: List of word ids
    """
    sentence = sentence.lower()
    word_ids = []
    for word in sentence.split():
        if word in vocab_to_int:
            word_ids.append(vocab_to_int[word])
        else:
            word_ids.append(vocab_to_int["<UNK>"])
    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 [118]:
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:      [191, 161, 125, 77, 42, 219, 7]
  English Words: ['he', 'saw', 'a', 'old', 'yellow', 'truck', '.']

Prediction
  Word Ids:      [238, 130, 7, 45, 237, 172, 227, 166, 1]
  French Words: il a vu un vieux camion noir . <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.