Natural Language Processing · Advanced level

Advanced level · Module 3: Long Short-Term Memory Networks for Text · Lesson 2 of 3

Bidirectional LSTM Text Classifiers

Learners build a bidirectional LSTM classifier with packed sequences so that padding does not affect results, and initialise it with pretrained or Word2Vec embeddings.

In this lesson you will

  • Build a bidirectional LSTM classifier
  • Use packed sequences and pretrained embeddings

Key concepts

bidirectional=Truepack_padded_sequenceconcatenated final statespretrained embedding initialisationfreezing layers

The lesson

A bidirectional LSTM reads the text forwards and backwards and concatenates both final states, so each decision uses context from both sides.

torch.nn.utils.rnn.pack_padded_sequence(embedded, lengths, batch_first=True, enforce_sorted=False) tells the LSTM where each text really ends, so padding tokens do not change the final state.

Initialising nn.Embedding with vectors from the Word2Vec model trained in the Intermediate level (nn.Embedding.from_pretrained) can help when labelled data is small. Freezing the embeddings at first and unfreezing later is a common strategy.

Step by step

  1. Build the BiLSTM model with packing.
  2. Train it on the news task with random and with Word2Vec embeddings.
  3. Compare validation F1 for both.
  4. Check that results do not change when extra padding is added.

Practice activity

Train and compare BiLSTM classifiers with random and pretrained embeddings.

Expected result: Working models, a padding-invariance check and a comparison of embedding initialisations.

Check your understanding

  1. Why use pack_padded_sequence?

    Show answer

    So that padding tokens do not affect the LSTM's final states.

  2. What does a bidirectional LSTM add?

    Show answer

    Context from both the left and the right of each position.

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.