Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Deep Learning (3): Sequence Learning with RNN and LSTM

This article explains the core techniques of sequence learning, including recurrent neural networks (RNNs) and long short-term memory (LSTM) units. It shows how LSTM input, forget, and output gates mitigate the vanishing gradient problem, retain key information in long sequences, and support applications such as natural language processing and speech recognition.

sequence learningrecurrent neural networksRNNLSTMlong short-term memory

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

Deep Learning in a Nutshell: Sequence Learning

https://developer.nvidia.com/blog/parallelforall/deep-learning-nutshell-sequence-learning/

Translator: WaytoAGI (Way to AGI); Co-builder: dorothy

This series of blog posts aims to provide an intuitive introduction to deep learning that does not rely heavily on mathematics or theoretical constructs. The first part of this series provides an overview of the field of deep learning, covering the fundamentals and core concepts. In the second part, we outline methods for effectively training neural networks and introduce the historical background of the field. In this article, we focus on sequence learning for natural language processing. Part 4 of this series introduces reinforcement learning.

Figure 1: A long short-term memory (LSTM) unit. An LSTM unit has four input weights (from the data to the input and the three gates (i.e., the input gate, output gate, and forget gate)) and four recurrent weights (from the output to the input and the three gates (i.e., the input gate, output gate, and forget gate)). Peepholes are extra connections between the memory cell and the gates, but they do not significantly improve performance and are usually omitted for simplicity. Image by Klaus Greff and colleagues, published in “LSTM: A Search Space Odyssey”.

Sequence Learning

Everything in life depends on time and therefore represents a sequence. To perform machine learning with sequential data (text, speech, video, etc.), we can use a regular neural network and feed it the entire sequence, but the input size of our data would be fixed, which is quite limiting. This approach also has other problems if important events in a sequence happen to fall outside the input window. What we need is (1) a network into which we can feed sequences of arbitrary length, one sequence element per time step (e.g., a video is just a sequence of images; we feed the network one image at a time); and (2) a network with some kind of memory that can remember important events that occurred many time steps in the past. These problems and requirements gave rise to a variety of different recurrent neural networks.

Recurrent Neural Networks

If we want a conventional neural network to solve the problem of adding two numbers, we can simply input the two numbers and train the network to predict their sum. If we now want to add three numbers instead of two, we can (1) expand our network with additional inputs and weights and retrain it, or (2) feed the output (i.e., the sum of the first two numbers plus the third number) back into the network. Method (2) is clearly better, because we can hope that the network will perform well without retraining the entire network (the network already “knows” how to add two numbers, so it should know how to add the sum of two numbers to another number).

Conversely, if our task is to first add two numbers and then subtract two different numbers, this approach will no longer work. Even if we use additional weights on the output, we cannot guarantee the correct output: this amounts to trying to approximate the subtraction of two numbers using addition and multiplication, which generally does not work! Instead, we can try to change the “program” in the network from “addition” to “subtraction.” We can do this by weighting the output of the hidden layer and feeding it back into the hidden layer—a recurrent weight (see Figure 2)! With this approach, we can change the network’s internal dynamics with each new input (that is, with each new number). The network will learn to change the program from “addition” to “subtraction” after the first two numbers, thereby solving the problem (albeit with some error in accuracy).

Figure 2: Comparison of the basic computational architectures of a conventional neural network and a recurrent neural network. A recurrent neural network has an input for each time step, whereas a conventional neural network takes all inputs at once.

We can even generalize this approach by feeding two numbers into the network one at a time, and then feeding in a “special” number representing a mathematical operation such as “addition,” “subtraction,” or “multiplication.” Although this is not perfect in practice, we can obtain roughly correct results. However, the point here is not to get the correct result, but that we can train a recurrent neural network to learn very specific outputs for arbitrary input sequences, which is extremely powerful.

As an example, we can teach a recurrent network to learn sequences of words. Soumith Chintala and Wojciech Zaremba wrote an excellent Parallel Forall blog post about natural language understanding using RNNs. RNNs can also be used to generate sequences. Andrej Karpathy wrote a fascinating and entertaining blog post in which he demonstrates a character-level RNN that can generate everything from Shakespeare to Linux source code to baby names.

Long Short-Term Memory (LSTM)

The Long Short-Term Memory (LSTM) unit uses a linear unit with a self-connection whose constant weight is 1.0. This allows the value (forward pass) or gradient (backward pass) flowing into this self-recurrent unit to be retained indefinitely (multiplying the input or error by 1.0 still yields the same value; therefore, the output or error at the previous time step is the same as the output at the next time step), so that the value or gradient can be retrieved exactly when it is most needed. This self-recurrent unit, namely the memory cell, provides a memory that can store information over dozens of past time steps. This is very powerful for many tasks; for example, with text data, an LSTM unit can store information contained in the previous paragraph and apply that information to sentences in the current paragraph.

In addition, a common problem in deep networks is the “vanishing gradient” problem, where gradients become smaller layer by layer until they are too small to affect the deepest layers. With memory cells in LSTM, we have a continuous gradient flow (the error retains its value), thereby eliminating the vanishing gradient problem and enabling learning from sequences of hundreds of time steps.

However, sometimes we want to discard information in the memory cell and replace it with newer, more relevant information. At the same time, we do not want to confuse other parts of the network by releasing unnecessary information to the network. To solve this problem, the LSTM unit has a forget gate, which deletes information in the self-recurrent unit without releasing the information to the network (see Figure 1). In this way, we can discard information that would cause confusion and make room for new memories. The forget gate achieves this by multiplying the value of the memory cell by a number between 0 (delete) and 1 (keep everything). The exact value (of the memory cell) is determined by the current input and the output of the LSTM unit at the previous time step.

At other times, the memory cell contains information that needs to remain intact for many time steps. To this end, LSTM adds another gate, the input gate or write gate, which can be closed so that no new information flows into the memory cell (see Figure 1). In this way, data in the memory cell can be protected until it is needed.

Another gate controls the output of the memory cell by multiplying the memory cell’s output by a number between 0 (no output) and 1 (keep output) (see Figure 1). If multiple memories compete with one another, this gate can be useful: one memory cell might say, “My memory is very important right now! So I am releasing it now!” But the network might say: “Your memory is important, that is true, but the memories of other memory cells are much more important than yours! Therefore, I send a small value to your output gate, which will shut you off, and large values to the other output gates so that the more important memories win!”

The connections of an LSTM unit may look a little complicated at first glance, and it may take some time to understand them. However, if you isolate all the parts, you will find that the structure is essentially the same as that of an ordinary recurrent neural network, in which the input and recurrent weights flow to all gates, and these gates in turn connect to the self-recurrent memory cell.

To study LSTM in more depth and understand the entire architecture, I recommend reading LSTM: A Search Space Odyssey and the original LSTM paper.

Word Embeddings

Imagine the word “cat” and all the other words closely related to “cat.” You might think of words like “kitten” and “feline.” Now consider words that are somewhat different from “cat” but more similar to “cat” than to “car.” You might come up with nouns like “lion,” “tiger,” “dog,” and “animal,” or verbs like “purring,” “meowing,” and “sleeping.” Now imagine a three-dimensional space where we place the word “cat” in the middle. The words mentioned above that are more similar to “cat” map to positions closer to the location of “cat” in the space; for example, “kitten” and “feline” are close; “tiger” and “lion” are a little farther away; “dog” is farther still; and “car” is very, very far away. See Figure 3 for an example of words from cooking recipes and their two-dimensional word embedding space. Figure 3: A two-dimensional word embedding space for cooking recipes. Here we zoom in on the “Southern Europe” cluster.

If we use vectors pointing to each word in this space, then each vector will consist of 3 coordinates that give its position in this space; for example, if “cat” is (0,0,0), then “kitten” might have coordinates (0.1,0.2,-0.3), and “car” would have coordinates (10,0,-15).

This space is the word embedding space for our vocabulary (words) above, and each vector with 3 coordinates is a word embedding that we can use as input data for algorithms.

Usually, an embedding space contains thousands of words and more than a hundred dimensions. This space is difficult for humans to understand, but the property that similar words are closely connected in the embedding space still holds. For machines, this is an excellent word representation that can improve the results of language processing tasks.

If you want to learn more about word embeddings and how to apply them to create models that can “understand” language (at least to some extent), I recommend reading “Understanding Natural Language with Deep Neural Networks Using Torch” by Soumith Chintala and Wojciech Zaremba.

Encoder-Decoder

Stop and imagine a tomato. Now think of ingredients or dishes that go well with tomatoes. If your ideas are similar to the most common recipes you find online, you probably thought of ingredients such as cheese and salami (pizza); Parmesan, basil, and macaroni; and other ingredients such as olive oil, thyme, and parsley. Most of these ingredients are associated with Italian and Mediterranean cuisine.

Now think of the same tomato, but from the perspective of Mexican cuisine. You might associate tomatoes with beans, corn (maize), chili peppers, cilantro, or avocado.

What you just did was transform the representation of the word “tomato” into a new representation of “tomato” in “Mexican cuisine.”

You can imagine the encoder doing the same thing. It takes input word by word and converts it into a new “thought vector” by transforming the representations of all the words accordingly (just as it adds the context “Mexican cuisine” to “tomato”). This is the first step of the encoder-decoder architecture.

The second step of the encoder-decoder architecture exploits the fact that representations of two different languages have similar geometric shapes in word-embedding space, even if they use completely different words for something. For example, the German word for “cat” is “Katze,” and the word for “dog” is “Hund.” These are, of course, different words, but the underlying relationship between them is almost the same—that is, Katze relates to Hund just as “cat” relates to “dog”—so the difference in the “thought vectors” between Katze and Hund and between cat and dog will be very similar. In other words, although the words are different, they describe similar “thought vectors.” Some words cannot really be expressed in another language, but this is rare; in general, the relationships between words should be similar.

With these ideas in mind, we can now build a decoder network. We feed the “thought vectors” produced by the English encoder word by word into the German decoder. The German decoder takes these reinterpreted “thought vectors,” or “transformations of relationships,” as a “German word-vector space,” thereby generating sentences that express the same relationships in German as in English. So we have essentially built a network that can translate languages. In current research, this idea has become increasingly mature; although the results are not perfect, they are improving rapidly, and soon this approach may become the best way to translate languages.

If you would like to learn more about encoder-decoder architectures and neural machine translation, I recommend reading Kyunghyun Cho's article on encoder-decoder architectures—this comprehensive Parallel Forall blog post.

Conclusion

We have seen that we can use recurrent neural networks to solve difficult tasks involving sequences of arbitrary length. We have also seen that memory of past inputs is crucial for successful sequence learning and that, in this context, LSTMs can provide improved performance and alleviate the vanishing gradient problem. We took a deep dive into word embeddings and how to use them to train recurrent architectures to achieve a certain level of language understanding.

I hope you enjoyed this blog post. Stay tuned for the next post in this series, which will discuss reinforcement learning. If you have any questions, please leave them in the comments below, and I will do my best to answer them. Be sure to read Part 1, Part 2, and Part 4 of this series to learn about the foundations and core concepts of deep learning, its history, training algorithms, and reinforcement learning!