Natural Language Processing · Advanced level

Advanced level · Module 2: Recurrent Neural Networks for Language · Lesson 1 of 3

How Recurrent Networks Read Text

Learners trace an RNN reading a sentence one token at a time, updating a hidden state that summarises what it has seen.

In this lesson you will

  • Explain the RNN hidden state and recurrence
  • Use nn.RNN and interpret its outputs

Key concepts

recurrencehidden statenn.RNN(batch_first=True)outputs vs final hidden stateorder sensitivity

The lesson

Bag-of-words models ignore order. A recurrent neural network reads tokens in order and keeps a hidden state h_t = tanh(W_x x_t + W_h h_{t-1} + b), so 'fees not paid' and 'not fees paid' can produce different results.

In PyTorch, nn.RNN(input_size, hidden_size, batch_first=True) returns the outputs at every step and the final hidden state. For classification, the final hidden state (or a pooling of the outputs) feeds a linear layer.

Characters are a useful input for low-resource and misspelled text: there are few of them, and a misspelled word still shares most characters with the correct one.

Step by step

  1. Run nn.RNN on a random batch and print the output and hidden-state shapes.
  2. Trace the hidden state for a three-token input on paper.
  3. Encode names or words as character ids.
  4. Explain why order now matters.

Practice activity

Work through the RNN computation for a short sequence and verify the tensor shapes in code.

Expected result: Correct shapes and a clear explanation of how the hidden state carries information.

Check your understanding

  1. What does the hidden state represent?

    Show answer

    A summary of the tokens the RNN has read so far.

  2. Why are character inputs useful for misspelled text?

    Show answer

    Misspelled words still share most characters with the correct word.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.