AI News, Recurrent Neural Networks Tutorial, Part 1 – Introduction to RNNs

Recurrent Neural Networks Tutorial, Part 1 – Introduction to RNNs

Recurrent Neural Networks (RNNs) are popular models that have shown great promise in many NLP tasks.

It’s a multi-part series in which I’m planning to cover the following: As part of the tutorial we will implement a recurrent neural network based language model.

The applications of language models are two-fold: First, it allows us to score arbitrary sentences based on how likely they are to occur in the real world.

If you want to predict the next word in a sentence you better know which words came before it. RNNs are called recurrent because they perform the same task for every element of a sequence, with the output being depended on the previous computations.

By unrolling we simply mean that we write out the network for the complete sequence. For example, if the sequence we care about is a sentence of 5 words, the network would be unrolled into a 5-layer neural network, one layer for each word. The formulas that govern the computation happening in a RNN are as follows: There are a few things to note here: RNNs have shown great success in many NLP tasks.

A side-effect of being able to predict the next word is that we get a generative model, which allows us to generate new text by sampling from the output probabilities.

In Language Modeling our input is typically a sequence of words (encoded as one-hot vectors for example), and our output is the sequence of predicted words.

A key difference is that our output only starts after we have seen the complete input, because the first word of our translated sentences may require information captured from the complete input sequence.

Research papers about Machine Translation: Given an input sequence of acoustic signals from a sound wave, we can predict a sequence of phonetic segments together with their probabilities.

Because the parameters are shared by all time steps in the network, the gradient at each output depends not only on the calculations of the current time step, but also the previous time steps.

The memory in LSTMs are called cells and you can think of them as black boxes that take as input the previous state and current input .

I hope you’ve gotten a basic understanding of what RNNs are and what they can do. In the next post we’ll implement a first version of our language model RNN using Python and Theano. Please leave questions in the comments!

The Unreasonable Effectiveness of Recurrent Neural Networks

Within a few dozen minutes of training my first baby model (with rather arbitrarily-chosen hyperparameters) started to generate very nice looking descriptions of images that were on the edge of making sense.

We’ll train RNNs to generate text character by character and ponder the question “how is that even possible?” By the way, together with this post I am also releasing code on Github that allows you to train character-level language models based on multi-layer LSTMs.

A few examples may make this more concrete: As you might expect, the sequence regime of operation is much more powerful compared to fixed networks that are doomed from the get-go by a fixed number of computational steps, and hence also much more appealing for those of us who aspire to build more intelligent systems.

You might be thinking that having sequences as inputs or outputs could be relatively rare, but an important point to realize is that even if your inputs/outputs are fixed vectors, it is still possible to use this powerful formalism to process them in a sequential manner.

On the right, a recurrent network generates images of digits by learning to sequentially add color to a canvas (Gregor et al.): The takeaway is that even if your data is not in form of sequences, you can still formulate and train powerful models that learn to process it sequentially.

If you’re more comfortable with math notation, we can also write the hidden state update as \( h_t = \tanh ( W_{hh} h_{t-1} + W_{xh} x_t ) \), where tanh is applied elementwise.

We initialize the matrices of the RNN with random numbers and the bulk of work during training goes into finding the matrices that give rise to desirable behavior, as measured with some loss function that expresses your preference to what kinds of outputs y you’d like to see in response to your input sequences x.

Here’s a diagram: For example, we see that in the first time step when the RNN saw the character “h” it assigned confidence of 1.0 to the next letter being “h”, 2.2 to letter “e”, -3.0 to “l”, and 4.1 to “o”.

Since the RNN consists entirely of differentiable operations we can run the backpropagation algorithm (this is just a recursive application of the chain rule from calculus) to figure out in what direction we should adjust every one of its weights to increase the scores of the correct targets (green bold numbers).

If you have a different physical investment are become in people who reduced in a startup with the way to argument the acquirer could see them just that you’re also the founders will part of users’ affords that and an alternation to the idea.

And if you have to act the big company too.” Okay, clearly the above is unfortunately not going to replace Paul Graham anytime soon, but remember that the RNN had to learn English completely from scratch and with a small dataset (including where you put commas, apostrophes and spaces).

In particular, setting temperature very near zero will give the most likely thing that Paul Graham might say: “is that they were all the same thing that was a startup is that they were all the same thing that was a startup is that they were all the same thing that was a startup is that they were all the same” looks like we’ve reached an infinite loop about startups.

There’s also quite a lot of structured markdown that the model learns, for example sometimes it creates headings, lists, etc.: Sometimes the model snaps into a mode of generating random but valid XML: The model completely makes up the timestamp, id, and so on.

We had to step in and fix a few issues manually but then you get plausible looking math, it’s quite astonishing: Here’s another sample: As you can see above, sometimes the model tries to generate latex diagrams, but clearly it hasn’t really figured them out.

This is an example of a problem we’d have to fix manually, and is likely due to the fact that the dependency is too long-term: By the time the model is done with the proof it has forgotten whether it was doing a proof or a lemma.

In particular, I took all the source and header files found in the Linux repo on Github, concatenated all of them in a single giant file (474MB of C code) (I was originally going to train only on the kernel but that by itself is only ~16MB).

This is usually a very amusing part: The model first recites the GNU license character by character, samples a few includes, generates some macros and then dives into the code: There are too many fun parts to cover- I could probably write an entire blog post on just this part.

Of course, you can imagine this being quite useful inspiration when writing a novel, or naming a new startup :) We saw that the results at the end of training can be impressive, but how does any of this work?

At 300 iterations we see that the model starts to get an idea about quotes and periods: The words are now also separated with spaces and the model starts to get the idea about periods at the end of a sentence.

Longer words have now been learned as well: Until at last we start to get properly spelled words, quotations, names, and so on by about iteration 2000: The picture that emerges is that the model first discovers the general word-space structure and then rapidly starts to learn the words;

In the visualizations below we feed a Wikipedia RNN model character data from the validation set (shown along the blue/green rows) and under every character we visualize (in red) the top 5 guesses that the model assigns for the next character.

Think about it as green = very excited and blue = not very excited (for those familiar with details of LSTMs, these are values between [-1,1] in the hidden state vector, which is just the gated and tanh’d LSTM cell state).

Below we’ll look at 4 different ones that I found and thought were interesting or interpretable (many also aren’t): Of course, a lot of these conclusions are slightly hand-wavy as the hidden state of the RNN is a huge, high-dimensional and largely distributed representation.

We can see that in addition to a large portion of cells that do not do anything interpretible, about 5% of them turn out to have learned quite interesting and interpretible algorithms: Again, what is beautiful about this is that we didn’t have to hardcode at any point that if you’re trying to predict the next character it might, for example, be useful to keep track of whether or not you are currently inside or outside of quote.

I’ve only started working with Torch/LUA over the last few months and it hasn’t been easy (I spent a good amount of time digging through the raw Torch code on Github and asking questions on their gitter to get things done), but once you get a hang of things it offers a lot of flexibility and speed.

Here’s a brief sketch of a few recent developments (definitely not complete list, and a lot of this work draws from research back to 1990s, see related work sections): In the domain of NLP/Speech, RNNs transcribe speech to text, perform machine translation, generate handwritten text, and of course, they have been used as powerful language models (Sutskever et al.) (Graves) (Mikolov et al.) (both on the level of characters and words).

For example, we’re seeing RNNs in frame-level video classification, image captioning (also including my own work and many others), video captioning and very recently visual question answering.

My personal favorite RNNs in Computer Vision paper is Recurrent Models of Visual Attention, both due to its high-level direction (sequential processing of images with glances) and the low-level modeling (REINFORCE learning rule that is a special case of policy gradient methods in Reinforcement Learning, which allows one to train models that perform non-differentiable computation (taking glances around the image in this case)).

I’m confident that this type of hybrid model that consists of a blend of CNN for raw perception coupled with an RNN glance policy on top will become pervasive in perception, especially for more complex tasks that go beyond classifying some objects in plain view.

One problem is that RNNs are not inductive: They memorize sequences extremely well, but they don’t necessarily always show convincing signs of generalizing in the correct way (I’ll provide pointers in a bit that make this more concrete).

This paper sketched a path towards models that can perform read/write operations between large, external memory arrays and a smaller set of memory registers (think of these as our working memory) where the computation happens.

Now, I don’t want to dive into too many details but a soft attention scheme for memory addressing is convenient because it keeps the model fully-differentiable, but unfortunately one sacrifices efficiency because everything that can be attended to is attended to (but softly).

Think of this as declaring a pointer in C that doesn’t point to a specific address but instead defines an entire distribution over all addresses in the entire memory, and dereferencing the pointer returns a weighted sum of the pointed content (that would be an expensive operation!).

If you’d like to play with training RNNs I hear good things about keras or passage for Theano, the code released with this post for Torch, or this gist for raw numpy code I wrote a while ago that implements an efficient, batched LSTM forward and backward pass.

Unfortunately, at about 46K characters I haven’t written enough data to properly feed the RNN, but the returned sample (generated with low temperature to get a more typical sample) is: Yes, the post was about RNN and how well it works, so clearly this works :).

Neural Machine Translation (seq2seq) Tutorial

Authors: Thang Luong, Eugene Brevdo, Rui Zhao (Google Research Blogpost, Github) This version of the tutorial requires TensorFlow Nightly. For

using the stable TensorFlow versions, please consider other branches such as tf-1.4.

great success in a variety of tasks such as machine translation, speech recognition,

of seq2seq models and shows how to build a competitive seq2seq model

We achieve this goal by: We believe that it is important to provide benchmarks that people can easily replicate.

As a result, we have provided full experimental results and pretrained

on models on the following publicly available datasets: We first build up some basic knowledge about seq2seq models for NMT, explaining how

and tricks to build the best possible NMT models (both in speed and translation

RNNs, beam search, as well as scaling up to multiple GPUs using GNMT attention.

Back in the old days, traditional phrase-based translation systems performed their

task by breaking up source sentences into multiple chunks and then translated

An encoder converts a source sentence into a 'meaning' vector which is passed

Specifically, an NMT system first reads the source sentence using an encoder to

manner, NMT addresses the local translation problem in the traditional phrase-based

differ in terms of: (a) directionality – unidirectional or bidirectional;

In this tutorial, we consider as examples a deep multi-layer RNN which is unidirectional

simply consumes the input source words without making any prediction;

on the other hand, processes the target sentence while predicting the next

Neural machine translation – example of a deep recurrent architecture

running: Let's first dive into the heart of building an NMT model with concrete code snippets

At the bottom layer, the encoder and decoder RNNs receive as input the following:

are in time-major format and contain word indices: Here for efficiency, we train with multiple sentences (batch_size) at once.

The embedding weights, one set per language, are usually

choose to initialize embedding weights with pretrained word representations such

Once retrieved, the word embeddings are then fed as input into the main network, which

consists of two multi-layer RNNs – an encoder for the source language and a

models do a better job when fitting large training datasets).

RNN uses zero vectors as its starting states and is built as follows: Note that sentences have different lengths to avoid wasting computation, we tell dynamic_rnn

describe how to build multi-layer LSTMs, add dropout, and use attention in a

Given the logits above, we are now ready to compute our training loss: Here, target_weights is a zero-one matrix of the same size as decoder_outputs.

SGD with a learning of 1.0, the latter approach effectively uses a much smaller

pass is just a matter of a few lines of code: One of the important steps in training RNNs is gradient clipping.

a decreasing learning rate schedule, which yields better performance.

nmt/scripts/ /tmp/nmt_data Run the following command to start the training: The above command trains a 2-layer LSTM seq2seq model with 128-dim hidden units and

We can start Tensorboard to view the summary of the model during training: Training the reverse direction from English and Vietnamese can be done simply by changing:

--src=en --tgt=vi While you're training your NMT models (and once you have trained models), you can

obtain translations given previously unseen source sentences.

Greedy decoding – example of how a trained NMT model produces a translation

for a source sentence 'Je suis étudiant' using greedy search.

the correct target words as an input, inference uses words predicted by the

know the target sequence lengths in advance, we use maximum_iterations to limit

Having trained a model, we can now create an inference file and translate some sentences:

Remember that in the vanilla seq2seq model, we pass the last source state from the

It consists of the following stages: Here, the function score is used to compared the target hidden state \( h_t \) with

each of the source hidden states \( \overline{h}_s \), and the result is normalized to produced

\( a_t \) is used to derive the softmax logit and loss.

and on whether the previous state \( h_{t-1} \) is used instead of \(

h_t \) in the scoring function as originally suggested in (Bahdanau et al., 2015).

of attention, i.e., direct connections between target and source, needs to be

mechanism, we happen to use the set of source hidden states (or their transformed

versions, e.g., \( W_1h_t \) in Bahdanau's scoring style) as "keys".

Thanks to the attention wrapper, extending our vanilla seq2seq code with attention First, we need to define an attention mechanism, e.g., from (Luong et al., 2015):

to create a new directory for the attention model, so we don't reuse the previously

Run the following command to start the training: After training, we can use the same inference command with the new out_dir for inference:

When building a machine learning model in TensorFlow, it's often best to build three

separate graphs: Building separate graphs has several benefits: The primary source of complexity becomes how to share Variables across the three graphs

Before: Three models in a single graph and sharing a single Session After: Three models in three graphs, with three Sessions sharing the same Variables Notice how the latter approach is "ready"

feed data at each call (and thereby performing our own batching,

training and eval pipelines: The first approach is easier for users who aren't familiar with TensorFlow or need

to do exotic input modification (i.e., their own minibatch queueing) that can

Some examples: All datasets can be treated similarly via input processing.

To convert each sentence into vectors of word strings, for example, we use the dataset

map transformation: We can then switch each sentence vector into a tuple containing both the vector and

object table, this map converts the first tuple elements from a vector of strings

containing the tuples of the zipped lines can be created via: Batching of variable-length sentences is straightforward.

Values emitted from this dataset will be nested tuples whose tensors have a leftmost

The structure will be: Finally, bucketing that batches similarly-sized source sentences together is also

Reading data from a Dataset requires three lines of code: create the iterator, get

Bidirectionality on the encoder side generally gives better performance (with some

of how to build an encoder with a single bidirectional layer: The variables encoder_outputs and encoder_state can be used in the same way as

While greedy decoding can give us quite reasonable translation quality, a beam search

explore the search space of all possible translations by keeping around a small

a minimal beam width of, say size 10, is generally sufficient.

You may notice the speed improvement of the attention based NMT model is very small

(i.e., 1 bidirectional layers for the encoder), embedding dim is

measure the translation quality in terms of BLEU scores (Papineni et al., 2002).

step-time means the time taken to run one mini-batch (of size 128).

(i.e., 2 bidirectional layers for the encoder), embedding dim is

These results show that our code builds strong baseline systems for NMT. (Note

that WMT systems generally utilize a huge amount monolingual data which we currently do not.) Training Speed: (2.1s step-time, 3.4K wps) on Nvidia K40m &

see the speed-ups with GNMT attention, we benchmark on K40m only: These results show that without GNMT attention, the gains from using multiple gpus are minimal. With

The above results show our models are very competitive among models of similar architectures. [Note

that OpenNMT uses smaller models and the current best result (as of this writing) is 28.4 obtained by the Transformer network (Vaswani et al., 2017) which has a significantly different architecture.] We have provided a

There's a wide variety of tools for building seq2seq models, so we pick one per language: Stanford [PyTorch] We would like to thank Denny Britz, Anna Goldie, Derek Murray, and Cinjon Resnick for their work bringing new features to TensorFlow and the seq2seq library.

Language model and sequence generation

This course will teach you how to build models for natural language, audio, and other sequence data.

Thanks to deep learning, sequence algorithms are working far better than just two years ago, and this is enabling numerous exciting applications in speech recognition, music synthesis, chatbots, machine translation, natural language understanding, and many others.

Lecture 8: Recurrent Neural Networks and Language Models

Lecture 8 covers traditional language models, RNNs, and RNN language models. Also reviewed are important training problems and tricks, RNNs for other ...

Recurrent Neural Networks - Ep. 9 (Deep Learning SIMPLIFIED)

Our previous discussions of deep net applications were limited to static patterns, but how can a net decipher and label patterns that change with time?

Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorflow Tutorial | Edureka

TensorFlow Training - ) This Edureka Recurrent Neural Networks tutorial video (Blog: ..

Recurrent Neural Networks (RNN / LSTM )with Keras - Python

In this tutorial, we learn about Recurrent Neural Networks (LSTM and RNN). Recurrent neural Networks or RNNs have been very successful and popular in time ...

Deep Learning with Tensorflow - Applying Recurrent Networks to Language Modelling

Enroll in the course for free at: Deep Learning with TensorFlow Introduction The majority of data ..

Lecture 10 | Recurrent Neural Networks

In Lecture 10 we discuss the use of recurrent neural networks for modeling sequence data. We show how recurrent neural networks can be used for language ...

Sequential Model - Keras

Here we go over the sequential model, the basic building block of doing anything that's related to Deep Learning in Keras. (this is super important to understand ...

How to Make a Text Summarizer - Intro to Deep Learning #10

I'll show you how you can turn an article into a one-sentence summary in Python with the Keras machine learning library. We'll go over word embeddings, ...

How to Use Tensorflow for Seq2seq Models (LIVE)

Let's build a Sequence to Sequence model in Tensorflow to learn exactly how they work. You can use this model to make chatbots, language translators, text ...