From 567931f271367685a0725d9b7a348b1a900f6256 Mon Sep 17 00:00:00 2001 From: Susan Li Date: Mon, 18 Jun 2018 18:47:48 -0400 Subject: [PATCH] Add files --- machine_translation.html | 13061 ++++++++++++++++++++++++++++++++++++ machine_translation.ipynb | 1066 +++ 2 files changed, 14127 insertions(+) create mode 100644 machine_translation.html create mode 100644 machine_translation.ipynb diff --git a/machine_translation.html b/machine_translation.html new file mode 100644 index 0000000..695f441 --- /dev/null +++ b/machine_translation.html @@ -0,0 +1,13061 @@ + + + +machine_translation + + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+
+

Artificial Intelligence Nanodegree

Machine Translation Project

In this notebook, sections that end with '(IMPLEMENTATION)' in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully!

+

Introduction

In this notebook, you will build a deep neural network that functions as part of an end-to-end machine translation pipeline. Your completed pipeline will accept English text as input and return the French translation.

+
    +
  • Preprocess - You'll convert text to sequence of integers.
  • +
  • Models Create models which accepts a sequence of integers as input and returns a probability distribution over possible translations. After learning about the basic types of neural networks that are often used for machine translation, you will engage in your own investigations, to design your own model!
  • +
  • Prediction Run the model on English text.
  • +
+ +
+
+
+
+
+
In [1]:
+
+
+
%load_ext autoreload
+%aimport helper, tests
+%autoreload 1
+
+ +
+
+
+ +
+
+
+
In [2]:
+
+
+
import collections
+
+import helper
+import numpy as np
+import project_tests as tests
+
+from keras.preprocessing.text import Tokenizer
+from keras.preprocessing.sequence import pad_sequences
+from keras.models import Model
+from keras.layers import GRU, Input, Dense, TimeDistributed, Activation, RepeatVector, Bidirectional
+from keras.layers.embeddings import Embedding
+from keras.optimizers import Adam
+from keras.losses import sparse_categorical_crossentropy
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Using TensorFlow backend.
+
+
+
+ +
+
+ +
+
+
+
+
+

Verify access to the GPU

The following test applies only if you expect to be using a GPU, e.g., while running in a Udacity Workspace or using an AWS instance with GPU support. Run the next cell, and verify that the device_type is "GPU".

+
    +
  • If the device is not GPU & you are running from a Udacity Workspace, then save your workspace with the icon at the top, then click "enable" at the bottom of the workspace.
  • +
  • If the device is not GPU & you are running from an AWS instance, then refer to the cloud computing instructions in the classroom to verify your setup steps.
  • +
+ +
+
+
+
+
+
In [3]:
+
+
+
from tensorflow.python.client import device_lib
+print(device_lib.list_local_devices())
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
[name: "/cpu:0"
+device_type: "CPU"
+memory_limit: 268435456
+locality {
+}
+incarnation: 18284655791200566811
+, name: "/gpu:0"
+device_type: "GPU"
+memory_limit: 357302272
+locality {
+  bus_id: 1
+}
+incarnation: 15968138399554932129
+physical_device_desc: "device: 0, name: Tesla K80, pci bus id: 0000:00:04.0"
+]
+
+
+
+ +
+
+ +
+
+
+
+
+

Dataset

We begin by investigating the dataset that will be used to train and evaluate your pipeline. The most common datasets used for machine translation are from WMT. However, that will take a long time to train a neural network on. We'll be using a dataset we created for this project that contains a small vocabulary. You'll be able to train your model in a reasonable time with this dataset.

+

Load Data

The data is located in data/small_vocab_en and data/small_vocab_fr. The small_vocab_en file contains English sentences with their French translations in the small_vocab_fr file. Load the English and French data from these files from running the cell below.

+ +
+
+
+
+
+
In [4]:
+
+
+
# Load English data
+english_sentences = helper.load_data('data/small_vocab_en')
+# Load French data
+french_sentences = helper.load_data('data/small_vocab_fr')
+
+print('Dataset Loaded')
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Dataset Loaded
+
+
+
+ +
+
+ +
+
+
+
+
+

Files

Each line in small_vocab_en contains an English sentence with the respective translation in each line of small_vocab_fr. View the first two lines from each file.

+ +
+
+
+
+
+
In [5]:
+
+
+
for sample_i in range(2):
+    print('small_vocab_en Line {}:  {}'.format(sample_i + 1, english_sentences[sample_i]))
+    print('small_vocab_fr Line {}:  {}'.format(sample_i + 1, french_sentences[sample_i]))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
small_vocab_en Line 1:  new jersey is sometimes quiet during autumn , and it is snowy in april .
+small_vocab_fr Line 1:  new jersey est parfois calme pendant l' automne , et il est neigeux en avril .
+small_vocab_en Line 2:  the united states is usually chilly during july , and it is usually freezing in november .
+small_vocab_fr Line 2:  les états-unis est généralement froid en juillet , et il gèle habituellement en novembre .
+
+
+
+ +
+
+ +
+
+
+
+
+

From looking at the sentences, you can see they have been preprocessed already. The puncuations have been delimited using spaces. All the text have been converted to lowercase. This should save you some time, but the text requires more preprocessing.

+

Vocabulary

The complexity of the problem is determined by the complexity of the vocabulary. A more complex vocabulary is a more complex problem. Let's look at the complexity of the dataset we'll be working with.

+ +
+
+
+
+
+
In [6]:
+
+
+
english_words_counter = collections.Counter([word for sentence in english_sentences for word in sentence.split()])
+french_words_counter = collections.Counter([word for sentence in french_sentences for word in sentence.split()])
+
+print('{} English words.'.format(len([word for sentence in english_sentences for word in sentence.split()])))
+print('{} unique English words.'.format(len(english_words_counter)))
+print('10 Most common words in the English dataset:')
+print('"' + '" "'.join(list(zip(*english_words_counter.most_common(10)))[0]) + '"')
+print()
+print('{} French words.'.format(len([word for sentence in french_sentences for word in sentence.split()])))
+print('{} unique French words.'.format(len(french_words_counter)))
+print('10 Most common words in the French dataset:')
+print('"' + '" "'.join(list(zip(*french_words_counter.most_common(10)))[0]) + '"')
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
1823250 English words.
+227 unique English words.
+10 Most common words in the English dataset:
+"is" "," "." "in" "it" "during" "the" "but" "and" "sometimes"
+
+1961295 French words.
+355 unique French words.
+10 Most common words in the French dataset:
+"est" "." "," "en" "il" "les" "mais" "et" "la" "parfois"
+
+
+
+ +
+
+ +
+
+
+
+
+

For comparison, Alice's Adventures in Wonderland contains 2,766 unique words of a total of 15,500 words.

+

Preprocess

For this project, you won't use text data as input to your model. Instead, you'll convert the text into sequences of integers using the following preprocess methods:

+
    +
  1. Tokenize the words into ids
  2. +
  3. Add padding to make all the sequences the same length.
  4. +
+

Time to start preprocessing the data...

+

Tokenize (IMPLEMENTATION)

For a neural network to predict on text data, it first has to be turned into data it can understand. Text data like "dog" is a sequence of ASCII character encodings. Since a neural network is a series of multiplication and addition operations, the input data needs to be number(s).

+

We can turn each character into a number or each word into a number. These are called character and word ids, respectively. Character ids are used for character level models that generate text predictions for each character. A word level model uses word ids that generate text predictions for each word. Word level models tend to learn better, since they are lower in complexity, so we'll use those.

+

Turn each sentence into a sequence of words ids using Keras's Tokenizer function. Use this function to tokenize english_sentences and french_sentences in the cell below.

+

Running the cell will run tokenize on sample data and show output for debugging.

+ +
+
+
+
+
+
In [7]:
+
+
+
def tokenize(x):
+    """
+    Tokenize x
+    :param x: List of sentences/strings to be tokenized
+    :return: Tuple of (tokenized x data, tokenizer used to tokenize x)
+    """
+    # TODO: Implement
+    x_tk = Tokenizer(char_level = False)
+    x_tk.fit_on_texts(x)
+    return x_tk.texts_to_sequences(x), x_tk
+
+# Tokenize Example output
+text_sentences = [
+    'The quick brown fox jumps over the lazy dog .',
+    'By Jove , my quick study of lexicography won a prize .',
+    'This is a short sentence .']
+text_tokenized, text_tokenizer = tokenize(text_sentences)
+print(text_tokenizer.word_index)
+print()
+for sample_i, (sent, token_sent) in enumerate(zip(text_sentences, text_tokenized)):
+    print('Sequence {} in x'.format(sample_i + 1))
+    print('  Input:  {}'.format(sent))
+    print('  Output: {}'.format(token_sent))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
{'the': 1, 'quick': 2, 'a': 3, 'brown': 4, 'fox': 5, 'jumps': 6, 'over': 7, 'lazy': 8, 'dog': 9, 'by': 10, 'jove': 11, 'my': 12, 'study': 13, 'of': 14, 'lexicography': 15, 'won': 16, 'prize': 17, 'this': 18, 'is': 19, 'short': 20, 'sentence': 21}
+
+Sequence 1 in x
+  Input:  The quick brown fox jumps over the lazy dog .
+  Output: [1, 2, 4, 5, 6, 7, 1, 8, 9]
+Sequence 2 in x
+  Input:  By Jove , my quick study of lexicography won a prize .
+  Output: [10, 11, 12, 2, 13, 14, 15, 16, 3, 17]
+Sequence 3 in x
+  Input:  This is a short sentence .
+  Output: [18, 19, 3, 20, 21]
+
+
+
+ +
+
+ +
+
+
+
+
+

Padding (IMPLEMENTATION)

When batching the sequence of word ids together, each sequence needs to be the same length. Since sentences are dynamic in length, we can add padding to the end of the sequences to make them the same length.

+

Make sure all the English sequences have the same length and all the French sequences have the same length by adding padding to the end of each sequence using Keras's pad_sequences function.

+ +
+
+
+
+
+
In [8]:
+
+
+
def pad(x, length=None):
+    """
+    Pad x
+    :param x: List of sequences.
+    :param length: Length to pad the sequence to.  If None, use length of longest sequence in x.
+    :return: Padded numpy array of sequences
+    """
+    # TODO: Implement
+    if length is None:
+        length = max([len(sentence) for sentence in x])
+    return pad_sequences(x, maxlen = length, padding = 'post')
+
+tests.test_pad(pad)
+
+# Pad Tokenized output
+test_pad = pad(text_tokenized)
+for sample_i, (token_sent, pad_sent) in enumerate(zip(text_tokenized, test_pad)):
+    print('Sequence {} in x'.format(sample_i + 1))
+    print('  Input:  {}'.format(np.array(token_sent)))
+    print('  Output: {}'.format(pad_sent))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Sequence 1 in x
+  Input:  [1 2 4 5 6 7 1 8 9]
+  Output: [1 2 4 5 6 7 1 8 9 0]
+Sequence 2 in x
+  Input:  [10 11 12  2 13 14 15 16  3 17]
+  Output: [10 11 12  2 13 14 15 16  3 17]
+Sequence 3 in x
+  Input:  [18 19  3 20 21]
+  Output: [18 19  3 20 21  0  0  0  0  0]
+
+
+
+ +
+
+ +
+
+
+
+
+

Preprocess Pipeline

Your focus for this project is to build neural network architecture, so we won't ask you to create a preprocess pipeline. Instead, we've provided you with the implementation of the preprocess function.

+ +
+
+
+
+
+
In [9]:
+
+
+
def preprocess(x, y):
+    """
+    Preprocess x and y
+    :param x: Feature List of sentences
+    :param y: Label List of sentences
+    :return: Tuple of (Preprocessed x, Preprocessed y, x tokenizer, y tokenizer)
+    """
+    preprocess_x, x_tk = tokenize(x)
+    preprocess_y, y_tk = tokenize(y)
+
+    preprocess_x = pad(preprocess_x)
+    preprocess_y = pad(preprocess_y)
+
+    # Keras's sparse_categorical_crossentropy function requires the labels to be in 3 dimensions
+    preprocess_y = preprocess_y.reshape(*preprocess_y.shape, 1)
+
+    return preprocess_x, preprocess_y, x_tk, y_tk
+
+preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer =\
+    preprocess(english_sentences, french_sentences)
+    
+max_english_sequence_length = preproc_english_sentences.shape[1]
+max_french_sequence_length = preproc_french_sentences.shape[1]
+english_vocab_size = len(english_tokenizer.word_index)
+french_vocab_size = len(french_tokenizer.word_index)
+
+print('Data Preprocessed')
+print("Max English sentence length:", max_english_sequence_length)
+print("Max French sentence length:", max_french_sequence_length)
+print("English vocabulary size:", english_vocab_size)
+print("French vocabulary size:", french_vocab_size)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Data Preprocessed
+Max English sentence length: 15
+Max French sentence length: 21
+English vocabulary size: 199
+French vocabulary size: 344
+
+
+
+ +
+
+ +
+
+
+
+
+

Models

In this section, you will experiment with various neural network architectures. +You will begin by training four relatively simple architectures.

+
    +
  • Model 1 is a simple RNN
  • +
  • Model 2 is a RNN with Embedding
  • +
  • Model 3 is a Bidirectional RNN
  • +
  • Model 4 is an optional Encoder-Decoder RNN
  • +
+

After experimenting with the four simple architectures, you will construct a deeper architecture that is designed to outperform all four models.

+

Ids Back to Text

The neural network will be translating the input to words ids, which isn't the final form we want. We want the French translation. The function logits_to_text will bridge the gab between the logits from the neural network to the French translation. You'll be using this function to better understand the output of the neural network.

+ +
+
+
+
+
+
In [10]:
+
+
+
def logits_to_text(logits, tokenizer):
+    """
+    Turn logits from a neural network into text using the tokenizer
+    :param logits: Logits from a neural network
+    :param tokenizer: Keras Tokenizer fit on the labels
+    :return: String that represents the text of the logits
+    """
+    index_to_words = {id: word for word, id in tokenizer.word_index.items()}
+    index_to_words[0] = '<PAD>'
+
+    return ' '.join([index_to_words[prediction] for prediction in np.argmax(logits, 1)])
+
+print('`logits_to_text` function loaded.')
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
`logits_to_text` function loaded.
+
+
+
+ +
+
+ +
+
+
+
+
+

Model 1: RNN (IMPLEMENTATION)

RNN +A basic RNN model is a good baseline for sequence data. In this model, you'll build a RNN that translates English to French.

+ +
+
+
+
+
+
In [11]:
+
+
+
def simple_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
+    """
+    Build and train a basic RNN on x and y
+    :param input_shape: Tuple of input shape
+    :param output_sequence_length: Length of output sequence
+    :param english_vocab_size: Number of unique English words in the dataset
+    :param french_vocab_size: Number of unique French words in the dataset
+    :return: Keras model built, but not trained
+    """
+    # TODO: Build the layers
+    learning_rate = 1e-3
+    input_seq = Input(input_shape[1:])
+    rnn = GRU(64, return_sequences = True)(input_seq)
+    logits = TimeDistributed(Dense(french_vocab_size))(rnn)
+    model = Model(input_seq, Activation('softmax')(logits))
+    model.compile(loss = sparse_categorical_crossentropy, 
+                 optimizer = Adam(learning_rate), 
+                 metrics = ['accuracy'])
+    
+    return model
+tests.test_simple_model(simple_model)
+
+# Reshaping the input to work with a basic RNN
+tmp_x = pad(preproc_english_sentences, max_french_sequence_length)
+tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))
+
+# Train the neural network
+simple_rnn_model = simple_model(
+    tmp_x.shape,
+    max_french_sequence_length,
+    english_vocab_size,
+    french_vocab_size)
+simple_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)
+
+# Print prediction(s)
+print(logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Train on 110288 samples, validate on 27573 samples
+Epoch 1/10
+110288/110288 [==============================] - 9s 82us/step - loss: 3.5162 - acc: 0.4027 - val_loss: nan - val_acc: 0.4516
+Epoch 2/10
+110288/110288 [==============================] - 7s 64us/step - loss: 2.4823 - acc: 0.4655 - val_loss: nan - val_acc: 0.4838
+Epoch 3/10
+110288/110288 [==============================] - 7s 63us/step - loss: 2.2427 - acc: 0.5016 - val_loss: nan - val_acc: 0.5082
+Epoch 4/10
+110288/110288 [==============================] - 7s 64us/step - loss: 2.0188 - acc: 0.5230 - val_loss: nan - val_acc: 0.5428
+Epoch 5/10
+110288/110288 [==============================] - 7s 64us/step - loss: 1.8418 - acc: 0.5542 - val_loss: nan - val_acc: 0.5685
+Epoch 6/10
+110288/110288 [==============================] - 7s 64us/step - loss: 1.7258 - acc: 0.5731 - val_loss: nan - val_acc: 0.5811
+Epoch 7/10
+110288/110288 [==============================] - 7s 64us/step - loss: 1.6478 - acc: 0.5871 - val_loss: nan - val_acc: 0.5890
+Epoch 8/10
+110288/110288 [==============================] - 7s 64us/step - loss: 1.5850 - acc: 0.5940 - val_loss: nan - val_acc: 0.5977
+Epoch 9/10
+110288/110288 [==============================] - 7s 64us/step - loss: 1.5320 - acc: 0.5996 - val_loss: nan - val_acc: 0.6027
+Epoch 10/10
+110288/110288 [==============================] - 7s 64us/step - loss: 1.4874 - acc: 0.6037 - val_loss: nan - val_acc: 0.6039
+new jersey est parfois parfois en en et il est est en en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>
+
+
+
+ +
+
+ +
+
+
+
+
+

Model 2: Embedding (IMPLEMENTATION)

RNN +You've turned the words into ids, but there's a better representation of a word. This is called word embeddings. An embedding is a vector representation of the word that is close to similar words in n-dimensional space, where the n represents the size of the embedding vectors.

+

In this model, you'll create a RNN model using embedding.

+ +
+
+
+
+
+
In [12]:
+
+
+
from keras.models import Sequential
+def embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
+    """
+    Build and train a RNN model using word embedding on x and y
+    :param input_shape: Tuple of input shape
+    :param output_sequence_length: Length of output sequence
+    :param english_vocab_size: Number of unique English words in the dataset
+    :param french_vocab_size: Number of unique French words in the dataset
+    :return: Keras model built, but not trained
+    """
+    # TODO: Implement
+    learning_rate = 1e-3
+    rnn = GRU(64, return_sequences=True, activation="tanh")
+    
+    embedding = Embedding(french_vocab_size, 64, input_length=input_shape[1]) 
+    logits = TimeDistributed(Dense(french_vocab_size, activation="softmax"))
+    
+    model = Sequential()
+    #em can only be used in first layer --> Keras Documentation
+    model.add(embedding)
+    model.add(rnn)
+    model.add(logits)
+    model.compile(loss=sparse_categorical_crossentropy,
+                  optimizer=Adam(learning_rate),
+                  metrics=['accuracy'])
+    
+    return model
+tests.test_embed_model(embed_model)
+
+
+# TODO: Reshape the input
+tmp_x = pad(preproc_english_sentences, max_french_sequence_length)
+tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2]))
+
+# TODO: Train the neural network
+
+embeded_model = embed_model(
+    tmp_x.shape,
+    max_french_sequence_length,
+    english_vocab_size,
+    french_vocab_size)
+
+embeded_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)
+
+
+# TODO: Print prediction(s)
+print(logits_to_text(embeded_model.predict(tmp_x[:1])[0], french_tokenizer))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Train on 110288 samples, validate on 27573 samples
+Epoch 1/10
+110288/110288 [==============================] - 8s 68us/step - loss: 3.7877 - acc: 0.4018 - val_loss: nan - val_acc: 0.4093
+Epoch 2/10
+110288/110288 [==============================] - 7s 65us/step - loss: 2.7258 - acc: 0.4382 - val_loss: nan - val_acc: 0.5152
+Epoch 3/10
+110288/110288 [==============================] - 7s 65us/step - loss: 2.0359 - acc: 0.5453 - val_loss: nan - val_acc: 0.6068
+Epoch 4/10
+110288/110288 [==============================] - 7s 65us/step - loss: 1.4586 - acc: 0.6558 - val_loss: nan - val_acc: 0.6967
+Epoch 5/10
+110288/110288 [==============================] - 7s 65us/step - loss: 1.1346 - acc: 0.7308 - val_loss: nan - val_acc: 0.7561
+Epoch 6/10
+110288/110288 [==============================] - 7s 65us/step - loss: 0.9358 - acc: 0.7681 - val_loss: nan - val_acc: 0.7825
+Epoch 7/10
+110288/110288 [==============================] - 7s 65us/step - loss: 0.8057 - acc: 0.7917 - val_loss: nan - val_acc: 0.7993
+Epoch 8/10
+110288/110288 [==============================] - 7s 65us/step - loss: 0.7132 - acc: 0.8095 - val_loss: nan - val_acc: 0.8173
+Epoch 9/10
+110288/110288 [==============================] - 7s 65us/step - loss: 0.6453 - acc: 0.8229 - val_loss: nan - val_acc: 0.8313
+Epoch 10/10
+110288/110288 [==============================] - 7s 64us/step - loss: 0.5893 - acc: 0.8355 - val_loss: nan - val_acc: 0.8401
+new jersey est parfois calme au l'automne et il il est neigeux en en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>
+
+
+
+ +
+
+ +
+
+
+
+
+

Model 3: Bidirectional RNNs (IMPLEMENTATION)

RNN +One restriction of a RNN is that it can't see the future input, only the past. This is where bidirectional recurrent neural networks come in. They are able to see the future data.

+ +
+
+
+
+
+
In [13]:
+
+
+
def bd_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
+    """
+    Build and train a bidirectional RNN model on x and y
+    :param input_shape: Tuple of input shape
+    :param output_sequence_length: Length of output sequence
+    :param english_vocab_size: Number of unique English words in the dataset
+    :param french_vocab_size: Number of unique French words in the dataset
+    :return: Keras model built, but not trained
+    """
+    # TODO: Implement
+    learning_rate = 1e-3
+    model = Sequential()
+    model.add(Bidirectional(GRU(128, return_sequences = True, dropout = 0.1), 
+                           input_shape = input_shape[1:]))
+    model.add(TimeDistributed(Dense(french_vocab_size, activation = 'softmax')))
+    model.compile(loss = sparse_categorical_crossentropy, 
+                 optimizer = Adam(learning_rate), 
+                 metrics = ['accuracy'])
+    return model
+tests.test_bd_model(bd_model)
+
+
+# TODO: Train and Print prediction(s)
+tmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1])
+tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))
+
+bidi_model = bd_model(
+    tmp_x.shape,
+    preproc_french_sentences.shape[1],
+    len(english_tokenizer.word_index)+1,
+    len(french_tokenizer.word_index)+1)
+
+
+bidi_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=20, validation_split=0.2)
+
+# Print prediction(s)
+print(logits_to_text(bidi_model.predict(tmp_x[:1])[0], french_tokenizer))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Train on 110288 samples, validate on 27573 samples
+Epoch 1/20
+110288/110288 [==============================] - 12s 110us/step - loss: 2.6981 - acc: 0.5009 - val_loss: 1.7832 - val_acc: 0.5699
+Epoch 2/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.6524 - acc: 0.5878 - val_loss: 1.4746 - val_acc: 0.6116
+Epoch 3/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.4406 - acc: 0.6161 - val_loss: 1.3488 - val_acc: 0.6278
+Epoch 4/20
+110288/110288 [==============================] - 12s 104us/step - loss: 1.3333 - acc: 0.6338 - val_loss: 1.2889 - val_acc: 0.6334
+Epoch 5/20
+110288/110288 [==============================] - 12s 104us/step - loss: 1.2650 - acc: 0.6462 - val_loss: 1.2543 - val_acc: 0.6357
+Epoch 6/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.2147 - acc: 0.6547 - val_loss: 1.2293 - val_acc: 0.6395
+Epoch 7/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.1708 - acc: 0.6627 - val_loss: 1.2233 - val_acc: 0.6406
+Epoch 8/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.1352 - acc: 0.6690 - val_loss: 1.2247 - val_acc: 0.6384
+Epoch 9/20
+110288/110288 [==============================] - 12s 104us/step - loss: 1.1049 - acc: 0.6745 - val_loss: 1.2287 - val_acc: 0.6352
+Epoch 10/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.0781 - acc: 0.6787 - val_loss: 1.2482 - val_acc: 0.6312
+Epoch 11/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.0539 - acc: 0.6821 - val_loss: 1.2580 - val_acc: 0.6327
+Epoch 12/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.0312 - acc: 0.6852 - val_loss: 1.3185 - val_acc: 0.6224
+Epoch 13/20
+110288/110288 [==============================] - 12s 105us/step - loss: 1.0115 - acc: 0.6885 - val_loss: 1.3248 - val_acc: 0.6220
+Epoch 14/20
+110288/110288 [==============================] - 12s 105us/step - loss: 0.9941 - acc: 0.6912 - val_loss: 1.3559 - val_acc: 0.6180
+Epoch 15/20
+110288/110288 [==============================] - 12s 105us/step - loss: 0.9789 - acc: 0.6940 - val_loss: 1.4108 - val_acc: 0.6121
+Epoch 16/20
+110288/110288 [==============================] - 12s 105us/step - loss: 0.9639 - acc: 0.6969 - val_loss: 1.4177 - val_acc: 0.6146
+Epoch 17/20
+110288/110288 [==============================] - 12s 105us/step - loss: 0.9506 - acc: 0.6990 - val_loss: 1.4739 - val_acc: 0.6099
+Epoch 18/20
+110288/110288 [==============================] - 12s 105us/step - loss: 0.9400 - acc: 0.7006 - val_loss: 1.4941 - val_acc: 0.6058
+Epoch 19/20
+110288/110288 [==============================] - 12s 104us/step - loss: 0.9287 - acc: 0.7028 - val_loss: 1.4994 - val_acc: 0.6073
+Epoch 20/20
+110288/110288 [==============================] - 12s 105us/step - loss: 0.9179 - acc: 0.7048 - val_loss: 1.5697 - val_acc: 0.5992
+new jersey est parfois pluvieux en printemps mais il est agréable en en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>
+
+
+
+ +
+
+ +
+
+
+
+
+

Model 4: Encoder-Decoder (OPTIONAL)

Time to look at encoder-decoder models. This model is made up of an encoder and decoder. The encoder creates a matrix representation of the sentence. The decoder takes this matrix as input and predicts the translation as output.

+

Create an encoder-decoder model in the cell below.

+ +
+
+
+
+
+
In [14]:
+
+
+
def encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
+    """
+    Build and train an encoder-decoder model on x and y
+    :param input_shape: Tuple of input shape
+    :param output_sequence_length: Length of output sequence
+    :param english_vocab_size: Number of unique English words in the dataset
+    :param french_vocab_size: Number of unique French words in the dataset
+    :return: Keras model built, but not trained
+    """
+    # OPTIONAL: Implement
+    learning_rate = 1e-3
+    model = Sequential()
+    model.add(GRU(128, input_shape = input_shape[1:], return_sequences = False))
+    model.add(RepeatVector(output_sequence_length))
+    model.add(GRU(128, return_sequences = True))
+    model.add(TimeDistributed(Dense(french_vocab_size, activation = 'softmax')))
+    
+    model.compile(loss = sparse_categorical_crossentropy, 
+                 optimizer = Adam(learning_rate), 
+                 metrics = ['accuracy'])
+    return model
+tests.test_encdec_model(encdec_model)
+
+
+# OPTIONAL: Train and Print prediction(s)
+tmp_x = pad(preproc_english_sentences)
+tmp_x = tmp_x.reshape((-1, preproc_english_sentences.shape[1], 1))
+
+encodeco_model = encdec_model(
+    tmp_x.shape,
+    preproc_french_sentences.shape[1],
+    len(english_tokenizer.word_index)+1,
+    len(french_tokenizer.word_index)+1)
+
+encodeco_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=20, validation_split=0.2)
+
+print(logits_to_text(encodeco_model.predict(tmp_x[:1])[0], french_tokenizer))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Train on 110288 samples, validate on 27573 samples
+Epoch 1/20
+110288/110288 [==============================] - 12s 108us/step - loss: 3.0306 - acc: 0.4358 - val_loss: 2.4772 - val_acc: 0.4847
+Epoch 2/20
+110288/110288 [==============================] - 11s 101us/step - loss: 2.3169 - acc: 0.4962 - val_loss: 2.1665 - val_acc: 0.5040
+Epoch 3/20
+110288/110288 [==============================] - 11s 101us/step - loss: 2.0245 - acc: 0.5151 - val_loss: 1.9048 - val_acc: 0.5263
+Epoch 4/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.8242 - acc: 0.5483 - val_loss: 1.7443 - val_acc: 0.5647
+Epoch 5/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.6933 - acc: 0.5688 - val_loss: 1.6505 - val_acc: 0.5677
+Epoch 6/20
+110288/110288 [==============================] - 11s 100us/step - loss: 1.6080 - acc: 0.5786 - val_loss: 1.5712 - val_acc: 0.5836
+Epoch 7/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.5392 - acc: 0.5912 - val_loss: 1.5067 - val_acc: 0.5966
+Epoch 8/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.4837 - acc: 0.5990 - val_loss: 1.4549 - val_acc: 0.6039
+Epoch 9/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.4381 - acc: 0.6079 - val_loss: 1.4158 - val_acc: 0.6130
+Epoch 10/20
+110288/110288 [==============================] - 11s 100us/step - loss: 1.4025 - acc: 0.6144 - val_loss: 1.3848 - val_acc: 0.6189
+Epoch 11/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.3762 - acc: 0.6179 - val_loss: 1.3630 - val_acc: 0.6207
+Epoch 12/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.3531 - acc: 0.6219 - val_loss: 1.3429 - val_acc: 0.6257
+Epoch 13/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.3341 - acc: 0.6257 - val_loss: 1.3219 - val_acc: 0.6274
+Epoch 14/20
+110288/110288 [==============================] - 11s 100us/step - loss: 1.3145 - acc: 0.6296 - val_loss: 1.3033 - val_acc: 0.6323
+Epoch 15/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.2973 - acc: 0.6316 - val_loss: 1.2879 - val_acc: 0.6326
+Epoch 16/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.2844 - acc: 0.6323 - val_loss: 1.2735 - val_acc: 0.6340
+Epoch 17/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.2691 - acc: 0.6337 - val_loss: 1.2587 - val_acc: 0.6352
+Epoch 18/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.2550 - acc: 0.6353 - val_loss: 1.2463 - val_acc: 0.6363
+Epoch 19/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.2429 - acc: 0.6373 - val_loss: 1.2313 - val_acc: 0.6388
+Epoch 20/20
+110288/110288 [==============================] - 11s 101us/step - loss: 1.2287 - acc: 0.6393 - val_loss: 1.2208 - val_acc: 0.6406
+new jersey est généralement agréable en mois et il est est en en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>
+
+
+
+ +
+
+ +
+
+
+
+
+

Model 5: Custom (IMPLEMENTATION)

Use everything you learned from the previous models to create a model that incorporates embedding and a bidirectional rnn into one model.

+ +
+
+
+
+
+
In [15]:
+
+
+
def model_final(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
+    """
+    Build and train a model that incorporates embedding, encoder-decoder, and bidirectional RNN on x and y
+    :param input_shape: Tuple of input shape
+    :param output_sequence_length: Length of output sequence
+    :param english_vocab_size: Number of unique English words in the dataset
+    :param french_vocab_size: Number of unique French words in the dataset
+    :return: Keras model built, but not trained
+    """
+    # TODO: Implement
+    model = Sequential()
+    model.add(Embedding(input_dim=english_vocab_size,output_dim=128,input_length=input_shape[1]))
+    model.add(Bidirectional(GRU(256,return_sequences=False)))
+    model.add(RepeatVector(output_sequence_length))
+    model.add(Bidirectional(GRU(256,return_sequences=True)))
+    model.add(TimeDistributed(Dense(french_vocab_size,activation='softmax')))
+    learning_rate = 0.005
+    
+    model.compile(loss = sparse_categorical_crossentropy, 
+                 optimizer = Adam(learning_rate), 
+                 metrics = ['accuracy'])
+    
+    return model
+tests.test_model_final(model_final)
+
+
+print('Final Model Loaded')
+# TODO: Train the final model
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Final Model Loaded
+
+
+
+ +
+
+ +
+
+
+
+
+

Prediction (IMPLEMENTATION)

+
+
+
+
+
+
In [17]:
+
+
+
def final_predictions(x, y, x_tk, y_tk):
+    """
+    Gets predictions using the final model
+    :param x: Preprocessed English data
+    :param y: Preprocessed French data
+    :param x_tk: English tokenizer
+    :param y_tk: French tokenizer
+    """
+    # TODO: Train neural network using model_final
+    tmp_X = pad(preproc_english_sentences)
+    model = model_final(tmp_X.shape,
+                        preproc_french_sentences.shape[1],
+                        len(english_tokenizer.word_index)+1,
+                        len(french_tokenizer.word_index)+1)
+    
+    model.fit(tmp_X, preproc_french_sentences, batch_size = 1024, epochs = 17, validation_split = 0.2)
+ 
+    ## DON'T EDIT ANYTHING BELOW THIS LINE
+    y_id_to_word = {value: key for key, value in y_tk.word_index.items()}
+    y_id_to_word[0] = '<PAD>'
+
+    sentence = 'he saw a old yellow truck'
+    sentence = [x_tk.word_index[word] for word in sentence.split()]
+    sentence = pad_sequences([sentence], maxlen=x.shape[-1], padding='post')
+    sentences = np.array([sentence[0], x[0]])
+    predictions = model.predict(sentences, len(sentences))
+
+    print('Sample 1:')
+    print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[0]]))
+    print('Il a vu un vieux camion jaune')
+    print('Sample 2:')
+    print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[1]]))
+    print(' '.join([y_id_to_word[np.max(x)] for x in y[0]]))
+
+
+final_predictions(preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Train on 110288 samples, validate on 27573 samples
+Epoch 1/17
+110288/110288 [==============================] - 41s 368us/step - loss: 1.9803 - acc: 0.5433 - val_loss: 1.2438 - val_acc: 0.6632
+Epoch 2/17
+110288/110288 [==============================] - 39s 354us/step - loss: 0.9968 - acc: 0.7186 - val_loss: 0.7820 - val_acc: 0.7716
+Epoch 3/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.6376 - acc: 0.8093 - val_loss: 0.4586 - val_acc: 0.8657
+Epoch 4/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.3872 - acc: 0.8854 - val_loss: 0.2809 - val_acc: 0.9183
+Epoch 5/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.2181 - acc: 0.9373 - val_loss: 0.1824 - val_acc: 0.9483
+Epoch 6/17
+110288/110288 [==============================] - 39s 354us/step - loss: 0.1565 - acc: 0.9553 - val_loss: 0.1671 - val_acc: 0.9513
+Epoch 7/17
+110288/110288 [==============================] - 39s 354us/step - loss: 0.1268 - acc: 0.9633 - val_loss: 0.1232 - val_acc: 0.9643
+Epoch 8/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.1011 - acc: 0.9707 - val_loss: 0.1061 - val_acc: 0.9688
+Epoch 9/17
+110288/110288 [==============================] - 39s 354us/step - loss: 0.0843 - acc: 0.9755 - val_loss: 0.0963 - val_acc: 0.9721
+Epoch 10/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0842 - acc: 0.9750 - val_loss: 0.0932 - val_acc: 0.9728
+Epoch 11/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0669 - acc: 0.9803 - val_loss: 0.0944 - val_acc: 0.9734
+Epoch 12/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0642 - acc: 0.9809 - val_loss: 0.0738 - val_acc: 0.9787
+Epoch 13/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0605 - acc: 0.9822 - val_loss: 0.0903 - val_acc: 0.9742
+Epoch 14/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0562 - acc: 0.9831 - val_loss: 0.0769 - val_acc: 0.9783
+Epoch 15/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0407 - acc: 0.9878 - val_loss: 0.0713 - val_acc: 0.9807
+Epoch 16/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0405 - acc: 0.9881 - val_loss: 0.0765 - val_acc: 0.9787
+Epoch 17/17
+110288/110288 [==============================] - 39s 355us/step - loss: 0.0514 - acc: 0.9847 - val_loss: 0.0811 - val_acc: 0.9776
+Sample 1:
+il a vu un vieux camion jaune <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>
+Il a vu un vieux camion jaune
+Sample 2:
+new jersey est parfois calme pendant l' automne et il est neigeux en avril <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>
+new jersey est parfois calme pendant l' automne et il est neigeux en avril <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>
+
+
+
+ +
+
+ +
+
+
+
+
+

Submission

When you're ready to submit, complete the following steps:

+
    +
  1. Review the rubric to ensure your submission meets all requirements to pass
  2. +
  3. Generate an HTML version of this notebook

    +
      +
    • Run the next cell to attempt automatic generation (this is the recommended method in Workspaces)
    • +
    • Navigate to FILE -> Download as -> HTML (.html)
    • +
    • Manually generate a copy using nbconvert from your shell terminal +
      $ pip install nbconvert
      +$ python -m nbconvert machine_translation.ipynb
      +
    • +
    +
  4. +
  5. Submit the project

    +
      +
    • If you are in a Workspace, simply click the "Submit Project" button (bottom towards the right)

      +
    • +
    • Otherwise, add the following files into a zip archive and submit them

      +
    • +
    • helper.py
    • +
    • machine_translation.ipynb
    • +
    • machine_translation.html
        +
      • You can export the notebook by navigating to File -> Download as -> HTML (.html).
      • +
      +
    • +
    +
  6. +
+ +
+
+
+
+
+
+
+

Generate the html

Save your notebook before running the next cell to generate the HTML output. Then submit your project.

+ +
+
+
+
+
+
In [18]:
+
+
+
# Save before you run this cell!
+!!jupyter nbconvert *.ipynb
+
+ +
+
+
+ +
+
+ + +
+ +
Out[18]:
+ + + + +
+
['[NbConvertApp] Converting notebook machine_translation.ipynb to html',
+ '[NbConvertApp] Writing 345566 bytes to machine_translation.html']
+
+ +
+ +
+
+ +
+
+
+
+
+

Optional Enhancements

This project focuses on learning various network architectures for machine translation, but we don't evaluate the models according to best practices by splitting the data into separate test & training sets -- so the model accuracy is overstated. Use the sklearn.model_selection.train_test_split() function to create separate training & test datasets, then retrain each of the models using only the training set and evaluate the prediction accuracy using the hold out test set. Does the "best" model change?

+ +
+
+
+
+
+ + + + + + diff --git a/machine_translation.ipynb b/machine_translation.ipynb new file mode 100644 index 0000000..a6e329e --- /dev/null +++ b/machine_translation.ipynb @@ -0,0 +1,1066 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Artificial Intelligence Nanodegree\n", + "## Machine Translation Project\n", + "In this notebook, sections that end with **'(IMPLEMENTATION)'** in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully!\n", + "\n", + "## Introduction\n", + "In this notebook, you will build a deep neural network that functions as part of an end-to-end machine translation pipeline. Your completed pipeline will accept English text as input and return the French translation.\n", + "\n", + "- **Preprocess** - You'll convert text to sequence of integers.\n", + "- **Models** Create models which accepts a sequence of integers as input and returns a probability distribution over possible translations. After learning about the basic types of neural networks that are often used for machine translation, you will engage in your own investigations, to design your own model!\n", + "- **Prediction** Run the model on English text." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "%load_ext autoreload\n", + "%aimport helper, tests\n", + "%autoreload 1" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Using TensorFlow backend.\n" + ] + } + ], + "source": [ + "import collections\n", + "\n", + "import helper\n", + "import numpy as np\n", + "import project_tests as tests\n", + "\n", + "from keras.preprocessing.text import Tokenizer\n", + "from keras.preprocessing.sequence import pad_sequences\n", + "from keras.models import Model\n", + "from keras.layers import GRU, Input, Dense, TimeDistributed, Activation, RepeatVector, Bidirectional\n", + "from keras.layers.embeddings import Embedding\n", + "from keras.optimizers import Adam\n", + "from keras.losses import sparse_categorical_crossentropy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Verify access to the GPU\n", + "The following test applies only if you expect to be using a GPU, e.g., while running in a Udacity Workspace or using an AWS instance with GPU support. Run the next cell, and verify that the device_type is \"GPU\".\n", + "- If the device is not GPU & you are running from a Udacity Workspace, then save your workspace with the icon at the top, then click \"enable\" at the bottom of the workspace.\n", + "- If the device is not GPU & you are running from an AWS instance, then refer to the cloud computing instructions in the classroom to verify your setup steps." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[name: \"/cpu:0\"\n", + "device_type: \"CPU\"\n", + "memory_limit: 268435456\n", + "locality {\n", + "}\n", + "incarnation: 18284655791200566811\n", + ", name: \"/gpu:0\"\n", + "device_type: \"GPU\"\n", + "memory_limit: 357302272\n", + "locality {\n", + " bus_id: 1\n", + "}\n", + "incarnation: 15968138399554932129\n", + "physical_device_desc: \"device: 0, name: Tesla K80, pci bus id: 0000:00:04.0\"\n", + "]\n" + ] + } + ], + "source": [ + "from tensorflow.python.client import device_lib\n", + "print(device_lib.list_local_devices())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dataset\n", + "We begin by investigating the dataset that will be used to train and evaluate your pipeline. The most common datasets used for machine translation are from [WMT](http://www.statmt.org/). However, that will take a long time to train a neural network on. We'll be using a dataset we created for this project that contains a small vocabulary. You'll be able to train your model in a reasonable time with this dataset.\n", + "### Load Data\n", + "The data is located in `data/small_vocab_en` and `data/small_vocab_fr`. The `small_vocab_en` file contains English sentences with their French translations in the `small_vocab_fr` file. Load the English and French data from these files from running the cell below." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dataset Loaded\n" + ] + } + ], + "source": [ + "# Load English data\n", + "english_sentences = helper.load_data('data/small_vocab_en')\n", + "# Load French data\n", + "french_sentences = helper.load_data('data/small_vocab_fr')\n", + "\n", + "print('Dataset Loaded')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Files\n", + "Each line in `small_vocab_en` contains an English sentence with the respective translation in each line of `small_vocab_fr`. View the first two lines from each file." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "small_vocab_en Line 1: new jersey is sometimes quiet during autumn , and it is snowy in april .\n", + "small_vocab_fr Line 1: new jersey est parfois calme pendant l' automne , et il est neigeux en avril .\n", + "small_vocab_en Line 2: the united states is usually chilly during july , and it is usually freezing in november .\n", + "small_vocab_fr Line 2: les états-unis est généralement froid en juillet , et il gèle habituellement en novembre .\n" + ] + } + ], + "source": [ + "for sample_i in range(2):\n", + " print('small_vocab_en Line {}: {}'.format(sample_i + 1, english_sentences[sample_i]))\n", + " print('small_vocab_fr Line {}: {}'.format(sample_i + 1, french_sentences[sample_i]))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "From looking at the sentences, you can see they have been preprocessed already. The puncuations have been delimited using spaces. All the text have been converted to lowercase. This should save you some time, but the text requires more preprocessing.\n", + "### Vocabulary\n", + "The complexity of the problem is determined by the complexity of the vocabulary. A more complex vocabulary is a more complex problem. Let's look at the complexity of the dataset we'll be working with." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1823250 English words.\n", + "227 unique English words.\n", + "10 Most common words in the English dataset:\n", + "\"is\" \",\" \".\" \"in\" \"it\" \"during\" \"the\" \"but\" \"and\" \"sometimes\"\n", + "\n", + "1961295 French words.\n", + "355 unique French words.\n", + "10 Most common words in the French dataset:\n", + "\"est\" \".\" \",\" \"en\" \"il\" \"les\" \"mais\" \"et\" \"la\" \"parfois\"\n" + ] + } + ], + "source": [ + "english_words_counter = collections.Counter([word for sentence in english_sentences for word in sentence.split()])\n", + "french_words_counter = collections.Counter([word for sentence in french_sentences for word in sentence.split()])\n", + "\n", + "print('{} English words.'.format(len([word for sentence in english_sentences for word in sentence.split()])))\n", + "print('{} unique English words.'.format(len(english_words_counter)))\n", + "print('10 Most common words in the English dataset:')\n", + "print('\"' + '\" \"'.join(list(zip(*english_words_counter.most_common(10)))[0]) + '\"')\n", + "print()\n", + "print('{} French words.'.format(len([word for sentence in french_sentences for word in sentence.split()])))\n", + "print('{} unique French words.'.format(len(french_words_counter)))\n", + "print('10 Most common words in the French dataset:')\n", + "print('\"' + '\" \"'.join(list(zip(*french_words_counter.most_common(10)))[0]) + '\"')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For comparison, _Alice's Adventures in Wonderland_ contains 2,766 unique words of a total of 15,500 words.\n", + "## Preprocess\n", + "For this project, you won't use text data as input to your model. Instead, you'll convert the text into sequences of integers using the following preprocess methods:\n", + "1. Tokenize the words into ids\n", + "2. Add padding to make all the sequences the same length.\n", + "\n", + "Time to start preprocessing the data...\n", + "### Tokenize (IMPLEMENTATION)\n", + "For a neural network to predict on text data, it first has to be turned into data it can understand. Text data like \"dog\" is a sequence of ASCII character encodings. Since a neural network is a series of multiplication and addition operations, the input data needs to be number(s).\n", + "\n", + "We can turn each character into a number or each word into a number. These are called character and word ids, respectively. Character ids are used for character level models that generate text predictions for each character. A word level model uses word ids that generate text predictions for each word. Word level models tend to learn better, since they are lower in complexity, so we'll use those.\n", + "\n", + "Turn each sentence into a sequence of words ids using Keras's [`Tokenizer`](https://keras.io/preprocessing/text/#tokenizer) function. Use this function to tokenize `english_sentences` and `french_sentences` in the cell below.\n", + "\n", + "Running the cell will run `tokenize` on sample data and show output for debugging." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'the': 1, 'quick': 2, 'a': 3, 'brown': 4, 'fox': 5, 'jumps': 6, 'over': 7, 'lazy': 8, 'dog': 9, 'by': 10, 'jove': 11, 'my': 12, 'study': 13, 'of': 14, 'lexicography': 15, 'won': 16, 'prize': 17, 'this': 18, 'is': 19, 'short': 20, 'sentence': 21}\n", + "\n", + "Sequence 1 in x\n", + " Input: The quick brown fox jumps over the lazy dog .\n", + " Output: [1, 2, 4, 5, 6, 7, 1, 8, 9]\n", + "Sequence 2 in x\n", + " Input: By Jove , my quick study of lexicography won a prize .\n", + " Output: [10, 11, 12, 2, 13, 14, 15, 16, 3, 17]\n", + "Sequence 3 in x\n", + " Input: This is a short sentence .\n", + " Output: [18, 19, 3, 20, 21]\n" + ] + } + ], + "source": [ + "def tokenize(x):\n", + " \"\"\"\n", + " Tokenize x\n", + " :param x: List of sentences/strings to be tokenized\n", + " :return: Tuple of (tokenized x data, tokenizer used to tokenize x)\n", + " \"\"\"\n", + " # TODO: Implement\n", + " x_tk = Tokenizer(char_level = False)\n", + " x_tk.fit_on_texts(x)\n", + " return x_tk.texts_to_sequences(x), x_tk\n", + "\n", + "# Tokenize Example output\n", + "text_sentences = [\n", + " 'The quick brown fox jumps over the lazy dog .',\n", + " 'By Jove , my quick study of lexicography won a prize .',\n", + " 'This is a short sentence .']\n", + "text_tokenized, text_tokenizer = tokenize(text_sentences)\n", + "print(text_tokenizer.word_index)\n", + "print()\n", + "for sample_i, (sent, token_sent) in enumerate(zip(text_sentences, text_tokenized)):\n", + " print('Sequence {} in x'.format(sample_i + 1))\n", + " print(' Input: {}'.format(sent))\n", + " print(' Output: {}'.format(token_sent))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Padding (IMPLEMENTATION)\n", + "When batching the sequence of word ids together, each sequence needs to be the same length. Since sentences are dynamic in length, we can add padding to the end of the sequences to make them the same length.\n", + "\n", + "Make sure all the English sequences have the same length and all the French sequences have the same length by adding padding to the **end** of each sequence using Keras's [`pad_sequences`](https://keras.io/preprocessing/sequence/#pad_sequences) function." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Sequence 1 in x\n", + " Input: [1 2 4 5 6 7 1 8 9]\n", + " Output: [1 2 4 5 6 7 1 8 9 0]\n", + "Sequence 2 in x\n", + " Input: [10 11 12 2 13 14 15 16 3 17]\n", + " Output: [10 11 12 2 13 14 15 16 3 17]\n", + "Sequence 3 in x\n", + " Input: [18 19 3 20 21]\n", + " Output: [18 19 3 20 21 0 0 0 0 0]\n" + ] + } + ], + "source": [ + "def pad(x, length=None):\n", + " \"\"\"\n", + " Pad x\n", + " :param x: List of sequences.\n", + " :param length: Length to pad the sequence to. If None, use length of longest sequence in x.\n", + " :return: Padded numpy array of sequences\n", + " \"\"\"\n", + " # TODO: Implement\n", + " if length is None:\n", + " length = max([len(sentence) for sentence in x])\n", + " return pad_sequences(x, maxlen = length, padding = 'post')\n", + "\n", + "tests.test_pad(pad)\n", + "\n", + "# Pad Tokenized output\n", + "test_pad = pad(text_tokenized)\n", + "for sample_i, (token_sent, pad_sent) in enumerate(zip(text_tokenized, test_pad)):\n", + " print('Sequence {} in x'.format(sample_i + 1))\n", + " print(' Input: {}'.format(np.array(token_sent)))\n", + " print(' Output: {}'.format(pad_sent))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Preprocess Pipeline\n", + "Your focus for this project is to build neural network architecture, so we won't ask you to create a preprocess pipeline. Instead, we've provided you with the implementation of the `preprocess` function." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Data Preprocessed\n", + "Max English sentence length: 15\n", + "Max French sentence length: 21\n", + "English vocabulary size: 199\n", + "French vocabulary size: 344\n" + ] + } + ], + "source": [ + "def preprocess(x, y):\n", + " \"\"\"\n", + " Preprocess x and y\n", + " :param x: Feature List of sentences\n", + " :param y: Label List of sentences\n", + " :return: Tuple of (Preprocessed x, Preprocessed y, x tokenizer, y tokenizer)\n", + " \"\"\"\n", + " preprocess_x, x_tk = tokenize(x)\n", + " preprocess_y, y_tk = tokenize(y)\n", + "\n", + " preprocess_x = pad(preprocess_x)\n", + " preprocess_y = pad(preprocess_y)\n", + "\n", + " # Keras's sparse_categorical_crossentropy function requires the labels to be in 3 dimensions\n", + " preprocess_y = preprocess_y.reshape(*preprocess_y.shape, 1)\n", + "\n", + " return preprocess_x, preprocess_y, x_tk, y_tk\n", + "\n", + "preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer =\\\n", + " preprocess(english_sentences, french_sentences)\n", + " \n", + "max_english_sequence_length = preproc_english_sentences.shape[1]\n", + "max_french_sequence_length = preproc_french_sentences.shape[1]\n", + "english_vocab_size = len(english_tokenizer.word_index)\n", + "french_vocab_size = len(french_tokenizer.word_index)\n", + "\n", + "print('Data Preprocessed')\n", + "print(\"Max English sentence length:\", max_english_sequence_length)\n", + "print(\"Max French sentence length:\", max_french_sequence_length)\n", + "print(\"English vocabulary size:\", english_vocab_size)\n", + "print(\"French vocabulary size:\", french_vocab_size)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Models\n", + "In this section, you will experiment with various neural network architectures.\n", + "You will begin by training four relatively simple architectures.\n", + "- Model 1 is a simple RNN\n", + "- Model 2 is a RNN with Embedding\n", + "- Model 3 is a Bidirectional RNN\n", + "- Model 4 is an optional Encoder-Decoder RNN\n", + "\n", + "After experimenting with the four simple architectures, you will construct a deeper architecture that is designed to outperform all four models.\n", + "### Ids Back to Text\n", + "The neural network will be translating the input to words ids, which isn't the final form we want. We want the French translation. The function `logits_to_text` will bridge the gab between the logits from the neural network to the French translation. You'll be using this function to better understand the output of the neural network." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "`logits_to_text` function loaded.\n" + ] + } + ], + "source": [ + "def logits_to_text(logits, tokenizer):\n", + " \"\"\"\n", + " Turn logits from a neural network into text using the tokenizer\n", + " :param logits: Logits from a neural network\n", + " :param tokenizer: Keras Tokenizer fit on the labels\n", + " :return: String that represents the text of the logits\n", + " \"\"\"\n", + " index_to_words = {id: word for word, id in tokenizer.word_index.items()}\n", + " index_to_words[0] = ''\n", + "\n", + " return ' '.join([index_to_words[prediction] for prediction in np.argmax(logits, 1)])\n", + "\n", + "print('`logits_to_text` function loaded.')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model 1: RNN (IMPLEMENTATION)\n", + "![RNN](images/rnn.png)\n", + "A basic RNN model is a good baseline for sequence data. In this model, you'll build a RNN that translates English to French." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Train on 110288 samples, validate on 27573 samples\n", + "Epoch 1/10\n", + "110288/110288 [==============================] - 9s 82us/step - loss: 3.5162 - acc: 0.4027 - val_loss: nan - val_acc: 0.4516\n", + "Epoch 2/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 2.4823 - acc: 0.4655 - val_loss: nan - val_acc: 0.4838\n", + "Epoch 3/10\n", + "110288/110288 [==============================] - 7s 63us/step - loss: 2.2427 - acc: 0.5016 - val_loss: nan - val_acc: 0.5082\n", + "Epoch 4/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 2.0188 - acc: 0.5230 - val_loss: nan - val_acc: 0.5428\n", + "Epoch 5/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 1.8418 - acc: 0.5542 - val_loss: nan - val_acc: 0.5685\n", + "Epoch 6/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 1.7258 - acc: 0.5731 - val_loss: nan - val_acc: 0.5811\n", + "Epoch 7/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 1.6478 - acc: 0.5871 - val_loss: nan - val_acc: 0.5890\n", + "Epoch 8/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 1.5850 - acc: 0.5940 - val_loss: nan - val_acc: 0.5977\n", + "Epoch 9/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 1.5320 - acc: 0.5996 - val_loss: nan - val_acc: 0.6027\n", + "Epoch 10/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 1.4874 - acc: 0.6037 - val_loss: nan - val_acc: 0.6039\n", + "new jersey est parfois parfois en en et il est est en en \n" + ] + } + ], + "source": [ + "def simple_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n", + " \"\"\"\n", + " Build and train a basic RNN on x and y\n", + " :param input_shape: Tuple of input shape\n", + " :param output_sequence_length: Length of output sequence\n", + " :param english_vocab_size: Number of unique English words in the dataset\n", + " :param french_vocab_size: Number of unique French words in the dataset\n", + " :return: Keras model built, but not trained\n", + " \"\"\"\n", + " # TODO: Build the layers\n", + " learning_rate = 1e-3\n", + " input_seq = Input(input_shape[1:])\n", + " rnn = GRU(64, return_sequences = True)(input_seq)\n", + " logits = TimeDistributed(Dense(french_vocab_size))(rnn)\n", + " model = Model(input_seq, Activation('softmax')(logits))\n", + " model.compile(loss = sparse_categorical_crossentropy, \n", + " optimizer = Adam(learning_rate), \n", + " metrics = ['accuracy'])\n", + " \n", + " return model\n", + "tests.test_simple_model(simple_model)\n", + "\n", + "# Reshaping the input to work with a basic RNN\n", + "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n", + "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n", + "\n", + "# Train the neural network\n", + "simple_rnn_model = simple_model(\n", + " tmp_x.shape,\n", + " max_french_sequence_length,\n", + " english_vocab_size,\n", + " french_vocab_size)\n", + "simple_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)\n", + "\n", + "# Print prediction(s)\n", + "print(logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model 2: Embedding (IMPLEMENTATION)\n", + "![RNN](images/embedding.png)\n", + "You've turned the words into ids, but there's a better representation of a word. This is called word embeddings. An embedding is a vector representation of the word that is close to similar words in n-dimensional space, where the n represents the size of the embedding vectors.\n", + "\n", + "In this model, you'll create a RNN model using embedding." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Train on 110288 samples, validate on 27573 samples\n", + "Epoch 1/10\n", + "110288/110288 [==============================] - 8s 68us/step - loss: 3.7877 - acc: 0.4018 - val_loss: nan - val_acc: 0.4093\n", + "Epoch 2/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 2.7258 - acc: 0.4382 - val_loss: nan - val_acc: 0.5152\n", + "Epoch 3/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 2.0359 - acc: 0.5453 - val_loss: nan - val_acc: 0.6068\n", + "Epoch 4/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 1.4586 - acc: 0.6558 - val_loss: nan - val_acc: 0.6967\n", + "Epoch 5/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 1.1346 - acc: 0.7308 - val_loss: nan - val_acc: 0.7561\n", + "Epoch 6/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 0.9358 - acc: 0.7681 - val_loss: nan - val_acc: 0.7825\n", + "Epoch 7/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 0.8057 - acc: 0.7917 - val_loss: nan - val_acc: 0.7993\n", + "Epoch 8/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 0.7132 - acc: 0.8095 - val_loss: nan - val_acc: 0.8173\n", + "Epoch 9/10\n", + "110288/110288 [==============================] - 7s 65us/step - loss: 0.6453 - acc: 0.8229 - val_loss: nan - val_acc: 0.8313\n", + "Epoch 10/10\n", + "110288/110288 [==============================] - 7s 64us/step - loss: 0.5893 - acc: 0.8355 - val_loss: nan - val_acc: 0.8401\n", + "new jersey est parfois calme au l'automne et il il est neigeux en en \n" + ] + } + ], + "source": [ + "from keras.models import Sequential\n", + "def embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n", + " \"\"\"\n", + " Build and train a RNN model using word embedding on x and y\n", + " :param input_shape: Tuple of input shape\n", + " :param output_sequence_length: Length of output sequence\n", + " :param english_vocab_size: Number of unique English words in the dataset\n", + " :param french_vocab_size: Number of unique French words in the dataset\n", + " :return: Keras model built, but not trained\n", + " \"\"\"\n", + " # TODO: Implement\n", + " learning_rate = 1e-3\n", + " rnn = GRU(64, return_sequences=True, activation=\"tanh\")\n", + " \n", + " embedding = Embedding(french_vocab_size, 64, input_length=input_shape[1]) \n", + " logits = TimeDistributed(Dense(french_vocab_size, activation=\"softmax\"))\n", + " \n", + " model = Sequential()\n", + " #em can only be used in first layer --> Keras Documentation\n", + " model.add(embedding)\n", + " model.add(rnn)\n", + " model.add(logits)\n", + " model.compile(loss=sparse_categorical_crossentropy,\n", + " optimizer=Adam(learning_rate),\n", + " metrics=['accuracy'])\n", + " \n", + " return model\n", + "tests.test_embed_model(embed_model)\n", + "\n", + "\n", + "# TODO: Reshape the input\n", + "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n", + "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2]))\n", + "\n", + "# TODO: Train the neural network\n", + "\n", + "embeded_model = embed_model(\n", + " tmp_x.shape,\n", + " max_french_sequence_length,\n", + " english_vocab_size,\n", + " french_vocab_size)\n", + "\n", + "embeded_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)\n", + "\n", + "\n", + "# TODO: Print prediction(s)\n", + "print(logits_to_text(embeded_model.predict(tmp_x[:1])[0], french_tokenizer))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model 3: Bidirectional RNNs (IMPLEMENTATION)\n", + "![RNN](images/bidirectional.png)\n", + "One restriction of a RNN is that it can't see the future input, only the past. This is where bidirectional recurrent neural networks come in. They are able to see the future data." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Train on 110288 samples, validate on 27573 samples\n", + "Epoch 1/20\n", + "110288/110288 [==============================] - 12s 110us/step - loss: 2.6981 - acc: 0.5009 - val_loss: 1.7832 - val_acc: 0.5699\n", + "Epoch 2/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.6524 - acc: 0.5878 - val_loss: 1.4746 - val_acc: 0.6116\n", + "Epoch 3/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.4406 - acc: 0.6161 - val_loss: 1.3488 - val_acc: 0.6278\n", + "Epoch 4/20\n", + "110288/110288 [==============================] - 12s 104us/step - loss: 1.3333 - acc: 0.6338 - val_loss: 1.2889 - val_acc: 0.6334\n", + "Epoch 5/20\n", + "110288/110288 [==============================] - 12s 104us/step - loss: 1.2650 - acc: 0.6462 - val_loss: 1.2543 - val_acc: 0.6357\n", + "Epoch 6/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.2147 - acc: 0.6547 - val_loss: 1.2293 - val_acc: 0.6395\n", + "Epoch 7/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.1708 - acc: 0.6627 - val_loss: 1.2233 - val_acc: 0.6406\n", + "Epoch 8/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.1352 - acc: 0.6690 - val_loss: 1.2247 - val_acc: 0.6384\n", + "Epoch 9/20\n", + "110288/110288 [==============================] - 12s 104us/step - loss: 1.1049 - acc: 0.6745 - val_loss: 1.2287 - val_acc: 0.6352\n", + "Epoch 10/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.0781 - acc: 0.6787 - val_loss: 1.2482 - val_acc: 0.6312\n", + "Epoch 11/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.0539 - acc: 0.6821 - val_loss: 1.2580 - val_acc: 0.6327\n", + "Epoch 12/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.0312 - acc: 0.6852 - val_loss: 1.3185 - val_acc: 0.6224\n", + "Epoch 13/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 1.0115 - acc: 0.6885 - val_loss: 1.3248 - val_acc: 0.6220\n", + "Epoch 14/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 0.9941 - acc: 0.6912 - val_loss: 1.3559 - val_acc: 0.6180\n", + "Epoch 15/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 0.9789 - acc: 0.6940 - val_loss: 1.4108 - val_acc: 0.6121\n", + "Epoch 16/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 0.9639 - acc: 0.6969 - val_loss: 1.4177 - val_acc: 0.6146\n", + "Epoch 17/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 0.9506 - acc: 0.6990 - val_loss: 1.4739 - val_acc: 0.6099\n", + "Epoch 18/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 0.9400 - acc: 0.7006 - val_loss: 1.4941 - val_acc: 0.6058\n", + "Epoch 19/20\n", + "110288/110288 [==============================] - 12s 104us/step - loss: 0.9287 - acc: 0.7028 - val_loss: 1.4994 - val_acc: 0.6073\n", + "Epoch 20/20\n", + "110288/110288 [==============================] - 12s 105us/step - loss: 0.9179 - acc: 0.7048 - val_loss: 1.5697 - val_acc: 0.5992\n", + "new jersey est parfois pluvieux en printemps mais il est agréable en en \n" + ] + } + ], + "source": [ + "def bd_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n", + " \"\"\"\n", + " Build and train a bidirectional RNN model on x and y\n", + " :param input_shape: Tuple of input shape\n", + " :param output_sequence_length: Length of output sequence\n", + " :param english_vocab_size: Number of unique English words in the dataset\n", + " :param french_vocab_size: Number of unique French words in the dataset\n", + " :return: Keras model built, but not trained\n", + " \"\"\"\n", + " # TODO: Implement\n", + " learning_rate = 1e-3\n", + " model = Sequential()\n", + " model.add(Bidirectional(GRU(128, return_sequences = True, dropout = 0.1), \n", + " input_shape = input_shape[1:]))\n", + " model.add(TimeDistributed(Dense(french_vocab_size, activation = 'softmax')))\n", + " model.compile(loss = sparse_categorical_crossentropy, \n", + " optimizer = Adam(learning_rate), \n", + " metrics = ['accuracy'])\n", + " return model\n", + "tests.test_bd_model(bd_model)\n", + "\n", + "\n", + "# TODO: Train and Print prediction(s)\n", + "tmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1])\n", + "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n", + "\n", + "bidi_model = bd_model(\n", + " tmp_x.shape,\n", + " preproc_french_sentences.shape[1],\n", + " len(english_tokenizer.word_index)+1,\n", + " len(french_tokenizer.word_index)+1)\n", + "\n", + "\n", + "bidi_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=20, validation_split=0.2)\n", + "\n", + "# Print prediction(s)\n", + "print(logits_to_text(bidi_model.predict(tmp_x[:1])[0], french_tokenizer))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model 4: Encoder-Decoder (OPTIONAL)\n", + "Time to look at encoder-decoder models. This model is made up of an encoder and decoder. The encoder creates a matrix representation of the sentence. The decoder takes this matrix as input and predicts the translation as output.\n", + "\n", + "Create an encoder-decoder model in the cell below." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Train on 110288 samples, validate on 27573 samples\n", + "Epoch 1/20\n", + "110288/110288 [==============================] - 12s 108us/step - loss: 3.0306 - acc: 0.4358 - val_loss: 2.4772 - val_acc: 0.4847\n", + "Epoch 2/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 2.3169 - acc: 0.4962 - val_loss: 2.1665 - val_acc: 0.5040\n", + "Epoch 3/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 2.0245 - acc: 0.5151 - val_loss: 1.9048 - val_acc: 0.5263\n", + "Epoch 4/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.8242 - acc: 0.5483 - val_loss: 1.7443 - val_acc: 0.5647\n", + "Epoch 5/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.6933 - acc: 0.5688 - val_loss: 1.6505 - val_acc: 0.5677\n", + "Epoch 6/20\n", + "110288/110288 [==============================] - 11s 100us/step - loss: 1.6080 - acc: 0.5786 - val_loss: 1.5712 - val_acc: 0.5836\n", + "Epoch 7/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.5392 - acc: 0.5912 - val_loss: 1.5067 - val_acc: 0.5966\n", + "Epoch 8/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.4837 - acc: 0.5990 - val_loss: 1.4549 - val_acc: 0.6039\n", + "Epoch 9/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.4381 - acc: 0.6079 - val_loss: 1.4158 - val_acc: 0.6130\n", + "Epoch 10/20\n", + "110288/110288 [==============================] - 11s 100us/step - loss: 1.4025 - acc: 0.6144 - val_loss: 1.3848 - val_acc: 0.6189\n", + "Epoch 11/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.3762 - acc: 0.6179 - val_loss: 1.3630 - val_acc: 0.6207\n", + "Epoch 12/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.3531 - acc: 0.6219 - val_loss: 1.3429 - val_acc: 0.6257\n", + "Epoch 13/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.3341 - acc: 0.6257 - val_loss: 1.3219 - val_acc: 0.6274\n", + "Epoch 14/20\n", + "110288/110288 [==============================] - 11s 100us/step - loss: 1.3145 - acc: 0.6296 - val_loss: 1.3033 - val_acc: 0.6323\n", + "Epoch 15/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.2973 - acc: 0.6316 - val_loss: 1.2879 - val_acc: 0.6326\n", + "Epoch 16/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.2844 - acc: 0.6323 - val_loss: 1.2735 - val_acc: 0.6340\n", + "Epoch 17/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.2691 - acc: 0.6337 - val_loss: 1.2587 - val_acc: 0.6352\n", + "Epoch 18/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.2550 - acc: 0.6353 - val_loss: 1.2463 - val_acc: 0.6363\n", + "Epoch 19/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.2429 - acc: 0.6373 - val_loss: 1.2313 - val_acc: 0.6388\n", + "Epoch 20/20\n", + "110288/110288 [==============================] - 11s 101us/step - loss: 1.2287 - acc: 0.6393 - val_loss: 1.2208 - val_acc: 0.6406\n", + "new jersey est généralement agréable en mois et il est est en en \n" + ] + } + ], + "source": [ + "def encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n", + " \"\"\"\n", + " Build and train an encoder-decoder model on x and y\n", + " :param input_shape: Tuple of input shape\n", + " :param output_sequence_length: Length of output sequence\n", + " :param english_vocab_size: Number of unique English words in the dataset\n", + " :param french_vocab_size: Number of unique French words in the dataset\n", + " :return: Keras model built, but not trained\n", + " \"\"\"\n", + " # OPTIONAL: Implement\n", + " learning_rate = 1e-3\n", + " model = Sequential()\n", + " model.add(GRU(128, input_shape = input_shape[1:], return_sequences = False))\n", + " model.add(RepeatVector(output_sequence_length))\n", + " model.add(GRU(128, return_sequences = True))\n", + " model.add(TimeDistributed(Dense(french_vocab_size, activation = 'softmax')))\n", + " \n", + " model.compile(loss = sparse_categorical_crossentropy, \n", + " optimizer = Adam(learning_rate), \n", + " metrics = ['accuracy'])\n", + " return model\n", + "tests.test_encdec_model(encdec_model)\n", + "\n", + "\n", + "# OPTIONAL: Train and Print prediction(s)\n", + "tmp_x = pad(preproc_english_sentences)\n", + "tmp_x = tmp_x.reshape((-1, preproc_english_sentences.shape[1], 1))\n", + "\n", + "encodeco_model = encdec_model(\n", + " tmp_x.shape,\n", + " preproc_french_sentences.shape[1],\n", + " len(english_tokenizer.word_index)+1,\n", + " len(french_tokenizer.word_index)+1)\n", + "\n", + "encodeco_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=20, validation_split=0.2)\n", + "\n", + "print(logits_to_text(encodeco_model.predict(tmp_x[:1])[0], french_tokenizer))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model 5: Custom (IMPLEMENTATION)\n", + "Use everything you learned from the previous models to create a model that incorporates embedding and a bidirectional rnn into one model." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Final Model Loaded\n" + ] + } + ], + "source": [ + "def model_final(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n", + " \"\"\"\n", + " Build and train a model that incorporates embedding, encoder-decoder, and bidirectional RNN on x and y\n", + " :param input_shape: Tuple of input shape\n", + " :param output_sequence_length: Length of output sequence\n", + " :param english_vocab_size: Number of unique English words in the dataset\n", + " :param french_vocab_size: Number of unique French words in the dataset\n", + " :return: Keras model built, but not trained\n", + " \"\"\"\n", + " # TODO: Implement\n", + " model = Sequential()\n", + " model.add(Embedding(input_dim=english_vocab_size,output_dim=128,input_length=input_shape[1]))\n", + " model.add(Bidirectional(GRU(256,return_sequences=False)))\n", + " model.add(RepeatVector(output_sequence_length))\n", + " model.add(Bidirectional(GRU(256,return_sequences=True)))\n", + " model.add(TimeDistributed(Dense(french_vocab_size,activation='softmax')))\n", + " learning_rate = 0.005\n", + " \n", + " model.compile(loss = sparse_categorical_crossentropy, \n", + " optimizer = Adam(learning_rate), \n", + " metrics = ['accuracy'])\n", + " \n", + " return model\n", + "tests.test_model_final(model_final)\n", + "\n", + "\n", + "print('Final Model Loaded')\n", + "# TODO: Train the final model" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Prediction (IMPLEMENTATION)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Train on 110288 samples, validate on 27573 samples\n", + "Epoch 1/17\n", + "110288/110288 [==============================] - 41s 368us/step - loss: 1.9803 - acc: 0.5433 - val_loss: 1.2438 - val_acc: 0.6632\n", + "Epoch 2/17\n", + "110288/110288 [==============================] - 39s 354us/step - loss: 0.9968 - acc: 0.7186 - val_loss: 0.7820 - val_acc: 0.7716\n", + "Epoch 3/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.6376 - acc: 0.8093 - val_loss: 0.4586 - val_acc: 0.8657\n", + "Epoch 4/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.3872 - acc: 0.8854 - val_loss: 0.2809 - val_acc: 0.9183\n", + "Epoch 5/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.2181 - acc: 0.9373 - val_loss: 0.1824 - val_acc: 0.9483\n", + "Epoch 6/17\n", + "110288/110288 [==============================] - 39s 354us/step - loss: 0.1565 - acc: 0.9553 - val_loss: 0.1671 - val_acc: 0.9513\n", + "Epoch 7/17\n", + "110288/110288 [==============================] - 39s 354us/step - loss: 0.1268 - acc: 0.9633 - val_loss: 0.1232 - val_acc: 0.9643\n", + "Epoch 8/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.1011 - acc: 0.9707 - val_loss: 0.1061 - val_acc: 0.9688\n", + "Epoch 9/17\n", + "110288/110288 [==============================] - 39s 354us/step - loss: 0.0843 - acc: 0.9755 - val_loss: 0.0963 - val_acc: 0.9721\n", + "Epoch 10/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0842 - acc: 0.9750 - val_loss: 0.0932 - val_acc: 0.9728\n", + "Epoch 11/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0669 - acc: 0.9803 - val_loss: 0.0944 - val_acc: 0.9734\n", + "Epoch 12/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0642 - acc: 0.9809 - val_loss: 0.0738 - val_acc: 0.9787\n", + "Epoch 13/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0605 - acc: 0.9822 - val_loss: 0.0903 - val_acc: 0.9742\n", + "Epoch 14/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0562 - acc: 0.9831 - val_loss: 0.0769 - val_acc: 0.9783\n", + "Epoch 15/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0407 - acc: 0.9878 - val_loss: 0.0713 - val_acc: 0.9807\n", + "Epoch 16/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0405 - acc: 0.9881 - val_loss: 0.0765 - val_acc: 0.9787\n", + "Epoch 17/17\n", + "110288/110288 [==============================] - 39s 355us/step - loss: 0.0514 - acc: 0.9847 - val_loss: 0.0811 - val_acc: 0.9776\n", + "Sample 1:\n", + "il a vu un vieux camion jaune \n", + "Il a vu un vieux camion jaune\n", + "Sample 2:\n", + "new jersey est parfois calme pendant l' automne et il est neigeux en avril \n", + "new jersey est parfois calme pendant l' automne et il est neigeux en avril \n" + ] + } + ], + "source": [ + "def final_predictions(x, y, x_tk, y_tk):\n", + " \"\"\"\n", + " Gets predictions using the final model\n", + " :param x: Preprocessed English data\n", + " :param y: Preprocessed French data\n", + " :param x_tk: English tokenizer\n", + " :param y_tk: French tokenizer\n", + " \"\"\"\n", + " # TODO: Train neural network using model_final\n", + " tmp_X = pad(preproc_english_sentences)\n", + " model = model_final(tmp_X.shape,\n", + " preproc_french_sentences.shape[1],\n", + " len(english_tokenizer.word_index)+1,\n", + " len(french_tokenizer.word_index)+1)\n", + " \n", + " model.fit(tmp_X, preproc_french_sentences, batch_size = 1024, epochs = 17, validation_split = 0.2)\n", + " \n", + " ## DON'T EDIT ANYTHING BELOW THIS LINE\n", + " y_id_to_word = {value: key for key, value in y_tk.word_index.items()}\n", + " y_id_to_word[0] = ''\n", + "\n", + " sentence = 'he saw a old yellow truck'\n", + " sentence = [x_tk.word_index[word] for word in sentence.split()]\n", + " sentence = pad_sequences([sentence], maxlen=x.shape[-1], padding='post')\n", + " sentences = np.array([sentence[0], x[0]])\n", + " predictions = model.predict(sentences, len(sentences))\n", + "\n", + " print('Sample 1:')\n", + " print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[0]]))\n", + " print('Il a vu un vieux camion jaune')\n", + " print('Sample 2:')\n", + " print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[1]]))\n", + " print(' '.join([y_id_to_word[np.max(x)] for x in y[0]]))\n", + "\n", + "\n", + "final_predictions(preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Submission\n", + "When you're ready to submit, complete the following steps:\n", + "1. Review the [rubric](https://review.udacity.com/#!/rubrics/1004/view) to ensure your submission meets all requirements to pass\n", + "2. Generate an HTML version of this notebook\n", + "\n", + " - Run the next cell to attempt automatic generation (this is the recommended method in Workspaces)\n", + " - Navigate to **FILE -> Download as -> HTML (.html)**\n", + " - Manually generate a copy using `nbconvert` from your shell terminal\n", + "```\n", + "$ pip install nbconvert\n", + "$ python -m nbconvert machine_translation.ipynb\n", + "```\n", + " \n", + "3. Submit the project\n", + "\n", + " - If you are in a Workspace, simply click the \"Submit Project\" button (bottom towards the right)\n", + " \n", + " - Otherwise, add the following files into a zip archive and submit them \n", + " - `helper.py`\n", + " - `machine_translation.ipynb`\n", + " - `machine_translation.html`\n", + " - You can export the notebook by navigating to **File -> Download as -> HTML (.html)**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Generate the html\n", + "\n", + "**Save your notebook before running the next cell to generate the HTML output.** Then submit your project." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['[NbConvertApp] Converting notebook machine_translation.ipynb to html',\n", + " '[NbConvertApp] Writing 345566 bytes to machine_translation.html']" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Save before you run this cell!\n", + "!!jupyter nbconvert *.ipynb" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Optional Enhancements\n", + "\n", + "This project focuses on learning various network architectures for machine translation, but we don't evaluate the models according to best practices by splitting the data into separate test & training sets -- so the model accuracy is overstated. Use the [`sklearn.model_selection.train_test_split()`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function to create separate training & test datasets, then retrain each of the models using only the training set and evaluate the prediction accuracy using the hold out test set. Does the \"best\" model change?" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.3" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +}