Sequence Models for Text

NLP

Chapter 6 · Sequence Models for Text

nlp1-5 fixed meaning. This chapter fixes the other half of nlp1-4's own diagnosis — word order — by finally putting nn1-8's own RNN/LSTM material to real, concrete use on real text.

The Real Pipeline, End to End

  • Raw text → nlp1-1's own preprocessing (tokenize, clean).
  • Each token → nlp1-5's own word embedding.
  • The sequence of embeddings, in order, fed one at a time into an RNN/LSTM (nn1-8).
  • The LSTM's own final hidden state — a compressed summary of the whole sequence — fed into a small classifier head.
  • Resolving nlp1-4's Own Cliffhanger, Concretely

    nn1-8's own hidden-state update at every step depends on both the current input and the previous hidden state — order-dependent by construction. Feed the embeddings for "dog", "bites", "man" into the LSTM in that exact order, and the resulting final hidden state is genuinely, mathematically different from feeding "man", "bites", "dog" — because at every intermediate step, the hidden state carries forward a different history depending on what came before it.

    Something bag-of-words and plain embeddings alone could never do
    nlp1-2/nlp1-3's own bag-of-words vectors were provably identical for both sentences (nlp1-4). Averaging nlp1-5's own embeddings together, with no sequence model, would also produce identical results for both — averaging, like counting, has no notion of position either. Only combining meaning-aware embeddings with an order-preserving sequence model — exactly this chapter's own pipeline — genuinely distinguishes the two sentences.

    A Real Worked Task — Sentiment Classification

    import torch.nn as nn
    
    class TextClassifier(nn.Module):
        def __init__(self, vocab_size, embed_dim, hidden_dim):
            super().__init__()
            self.embedding = nn.Embedding(vocab_size, embed_dim)   # nlp1-5's own embeddings
            self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True)   # nn1-8
            self.output = nn.Linear(hidden_dim, 1)                  # nn1-1's own closing callback, again
    
        def forward(self, x):
            embedded = self.embedding(x)              # one embedding per token, in order
            _, (hidden, _) = self.lstm(embedded)        # the final hidden state — nn1-8's own "memory" of the whole sequence
            return torch.sigmoid(self.output(hidden[-1]))   # ml1-5's own logistic regression, one more time
    Pretrained embeddings slot right in
    nn.Embedding's own weight matrix can be initialized directly from nlp1-5's own pretrained word2vec vectors rather than learned from scratch — a direct preview of nlp1-9's own transfer-learning material.

    Both Problems, Genuinely Solved Together

    nlp1-4 diagnosed two independent problems — meaning and order — and insisted neither fix alone solves both. This chapter's own pipeline is the actual combination: nlp1-5's embeddings supply meaning, this chapter's own sequence model supplies order. Only together do they produce a representation that genuinely distinguishes "dog bites man" from "man bites dog" and recognizes "excellent" as similar to "great."

    What's Next

    This chapter's own model produces exactly one output for an entire sequence — a single sentiment label per document. nlp1-7 extends the identical underlying idea to produce one output per token instead — real, practical tasks like recognizing names and grammatical roles word by word.

    Hands-On Exercises

    Exercise 1

    Explain, using nn1-8's own hidden-state mechanism, why feeding "dog," "bites," "man" into an LSTM in that order produces a genuinely different final hidden state than feeding "man," "bites," "dog."

    📄 View solution
    Exercise 2

    Using this chapter's own finding-box, explain why simply averaging nlp1-5's own word embeddings together, without a sequence model, would still fail to distinguish "dog bites man" from "man bites dog."

    📄 View solution
    Exercise 3

    Explain why this chapter says nlp1-4's two diagnosed problems are only genuinely solved by combining nlp1-5's own embeddings with this chapter's own sequence model, rather than by either technique alone.

    📄 View solution

    Chapter 6 Quick Reference

    • Real pipeline: preprocessing (nlp1-1) → embeddings (nlp1-5) → LSTM in sequence order (nn1-8) → classifier head (nn1-1/ml1-5)
    • Order-dependence follows directly from nn1-8's own hidden-state update depending on both current input and prior state
    • Genuinely resolves nlp1-4's "dog bites man" cliffhanger — bag-of-words and averaged embeddings both provably couldn't
    • Both of nlp1-4's problems (meaning + order) are only solved by this combined pipeline, not by either fix alone
    • Pretrained embeddings slot directly into nn.Embedding — previewing nlp1-9
    • Next chapter: Named Entity Recognition & Part-of-Speech Tagging