1. Home
  2. Explore
  3. Computer Science
  4. Natural Language Processing

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Natural Language Processing

Natural Language Processing and Modern Language Models

Natural Language Processing

Natural language processing (NLP) is the area of artificial intelligence concerned with enabling computers to work with human language, such as English. Unlike problems that can be directly expressed as search, constraint satisfaction, or optimization problems, natural language contains ambiguity, context, nuance, and complicated rules.

NLP systems may need to both understand language and generate language.

Major NLP Tasks

  • Automatic summarization: Producing a shorter representation of a longer text while preserving its important information.

  • Information extraction: Identifying and retrieving relevant facts, entities, or details from a text.

  • Machine translation: Translating text from one language into another, such as translating English into French.

  • Question answering: Interpreting a question and generating an appropriate answer.

  • Text classification: Assigning a category or label to a text. Examples include:

    • Positive or negative sentiment

    • Inbox or spam

    • Relevant or irrelevant

    • Topic categories

  • Text generation: Producing new text that is grammatically appropriate, contextually relevant, or statistically similar to a training corpus.

Two central concerns affect nearly every NLP task:

  1. Syntax: The structure and arrangement of words.

  2. Semantics: The meaning of words and sentences.


Syntax and Sentence Structure

Syntax concerns the structure of language: how words are arranged and combined into phrases and sentences.

A computer cannot reliably understand a sentence merely by recognizing each individual word. It must also determine how those words relate to one another.

Syntactic Validity

Consider the sentence:

“Just before nine o’clock Sherlock Holmes stepped briskly into the room.”

The words form a syntactically valid sentence because they are arranged according to a meaningful structure.

Rearranging the same words produces:

“Just before Sherlock Holmes nine o’clock stepped briskly the room.”

Although every individual word is valid, the arrangement does not form a well-structured English sentence. This illustrates that word order is essential to syntax.

Syntactic Ambiguity

Some sentences have more than one valid syntactic structure. For example:

“I saw the man on the mountain with a telescope.”

This sentence can be interpreted in at least two ways:

  • The speaker used a telescope to see the man.

  • The man on the mountain had the telescope.

The words themselves have not changed, but their grammatical relationships can be organized differently. This creates syntactic ambiguity, in which a sentence has multiple possible parse structures.

A language-processing system must often determine which structure is most likely in context.


Semantics and Meaning

Semantics concerns the meaning of words, phrases, and sentences. Correct syntax does not guarantee meaningful content.

Different Sentences with Similar Meanings

The following sentences have different wording but approximately the same meaning:

  • “Just before nine o’clock Sherlock Holmes stepped briskly into the room.”

  • “A few minutes before nine, Sherlock Holmes walked quickly into the room.”

A capable NLP system should recognize that:

  • “just before nine o’clock” and “a few minutes before nine” express similar ideas.

  • “stepped briskly” and “walked quickly” have similar meanings.

  • Both sentences describe Sherlock Holmes entering a room shortly before nine.

Thus, semantic understanding requires more than matching identical words.

Grammatically Correct but Meaningless Sentences

A sentence can be syntactically well-formed while having little or no coherent meaning:

“Colorless green ideas sleep furiously.”

This sentence has recognizable grammatical components:

  • “Colorless” and “green” are adjectives.

  • “Ideas” is a noun.

  • “Sleep” is a verb.

  • “Furiously” is an adverb.

However, the complete sentence is semantically strange and does not express an ordinary coherent idea. This demonstrates that syntax and semantics are separate properties:

  • A sentence may have valid syntax but poor meaning.

  • A meaningful sentence generally requires both appropriate structure and appropriate interpretation.


Rule-Based Language Processing

Formal Grammars

One possible way to teach a computer language structure is to specify the rules of the language explicitly.

A formal grammar is a system of rules for generating valid sentences in a language. A grammar can describe:

  • Which types of words may appear

  • Which categories can be combined

  • The order in which phrases may occur

  • How larger structures are built from smaller ones

This is a rule-based approach to NLP. The computer applies predefined rules to determine whether a sentence is valid and how it is structured.

Context-Free Grammars

A context-free grammar (CFG) is a formal grammar in which rewriting rules describe how nonterminal symbols can be replaced by other symbols.

Terminal and Nonterminal Symbols

A terminal symbol is a final word or token that appears in the generated sentence. Once a terminal symbol has been produced, no further grammatical expansion is needed for it.

Examples of terminal symbols include:

  • she

  • saw

  • the

  • city

  • walked

A nonterminal symbol represents a grammatical category that can be expanded into terminals or other nonterminals.

Common nonterminals include:

  • N: noun

  • V: verb

  • D: determiner

  • NP: noun phrase

  • VP: verb phrase

  • AP: adjective phrase

  • PP: prepositional phrase

  • S: sentence

Rewriting Rules

A rewriting rule specifies how a nonterminal can be replaced. The vertical bar means “or.”

For example:

N→she∣city∣car∣HarryN \rightarrow \text{she} \mid \text{city} \mid \text{car} \mid \text{Harry}N→she∣city∣car∣Harry

This rule states that a noun may be replaced by any of the listed words.

A determiner rule might be:

D→the∣a∣anD \rightarrow \text{the} \mid \text{a} \mid \text{an}D→the∣a∣an

A verb rule might include:

V→saw∣walkedV \rightarrow \text{saw} \mid \text{walked}V→saw∣walked

Phrase-Level Rules

A noun phrase can consist of either a noun alone or a determiner followed by a noun:

NP→N∣D NNP \rightarrow N \mid D\ NNP→N∣D N

This allows both:

  • “she,” consisting of a single noun

  • “the city,” consisting of a determiner and a noun

A verb phrase can consist of a verb alone or a verb followed by a noun phrase:

VP→V∣V NPVP \rightarrow V \mid V\ NPVP→V∣V NP

This allows:

  • “walked”

  • “saw the city”

A sentence can be defined as a noun phrase followed by a verb phrase:

S→NP VPS \rightarrow NP\ VPS→NP VP

Using these rules, the sentence “she saw the city” can be derived as follows:

  1. The sentence becomes a noun phrase followed by a verb phrase.

  2. The noun phrase becomes “she.”

  3. The verb phrase becomes a verb followed by a noun phrase.

  4. The verb becomes “saw.”

  5. The second noun phrase becomes “the city.”

The complete structure is:

  • S

    • NP: she

    • VP

      • V: saw

      • NP

        • D: the

        • N: city

Parsing with a Context-Free Grammar

Parsing is the process of determining the grammatical structure of a sentence according to a grammar.

The Natural Language Toolkit, or NLTK, provides tools for defining CFGs and parsing sentences. A CFG parser can:

  • Read a sentence

  • Match its words to terminal symbols

  • Apply grammar rules

  • Construct a syntax tree

  • Determine whether the sentence is valid according to the grammar

For example, a simple grammar may recognize:

  • “she walked”

  • “she saw the city”

A more complex grammar can include adjective phrases and prepositional phrases.

Ambiguous Parse Trees

Consider:

“She saw the dog with the binoculars.”

A CFG parser may produce two valid parse trees:

  1. The dog had the binoculars

    • “the dog with the binoculars” is one noun phrase.

  2. She used the binoculars

    • “with the binoculars” is a prepositional phrase modifying the act of seeing.

This demonstrates that a grammar may identify multiple syntactically valid interpretations. A CFG can expose possible structures, but additional information may be required to determine which interpretation is intended.

Limits of Handwritten Grammars

Rule-based grammars have important limitations:

  • English contains a very large number of grammatical constructions.

  • Rules can become complicated and difficult to maintain.

  • A grammar written for one set of sentences may fail on unfamiliar sentences.

  • Ambiguous sentences may produce multiple parse trees.

  • Syntax rules alone do not guarantee semantic understanding.

  • Writing every rule manually requires substantial effort.

These limitations motivate statistical and machine-learning approaches.


Statistical Language Models

N-Grams

Rather than explicitly writing every language rule, a computer can learn statistical patterns from a large collection of existing text.

An n-gram is a contiguous sequence of nnn items from a text. The items may be:

  • Characters

  • Words

  • Other tokens

When words are used, an n-gram represents nnn consecutive words.

Types of Word N-Grams

  • Unigram: One word

  • Bigram: Two consecutive words

  • Trigram: Three consecutive words

For example, the text:

“How often have I said to you that...”

contains the following trigrams:

  • “how often have”

  • “often have I”

  • “have I said”

  • “I said to”

  • “said to you”

  • “to you that”

Each trigram consists of three adjacent words.

Learning from a Corpus

A corpus is a collection of text used for analysis or training. By examining a large corpus, a computer can count how frequently different n-grams appear.

For example, in a collection of English text, common bigrams might include:

  • “of the”

  • “in the”

  • “it was”

Common trigrams might include:

  • “it was a”

  • “one of the”

  • “I think that”

Frequent n-grams provide information about which words commonly occur together and therefore give the computer a statistical sense of language structure.

Tokenization

Tokenization is the process of splitting a sequence of characters into smaller pieces called tokens.

In word-based NLP, tokenization usually divides text into individual words. For example:

“She saw the city.”

can be tokenized into:

  • “She”

  • “saw”

  • “the”

  • “city”

After tokenization, the system can examine sequences of tokens and count their frequencies.

Markov Chains for Text Generation

A Markov chain is a model in which the next value is predicted based on preceding values. Applied to language, a Markov chain can predict a likely next word based on the words that have already appeared.

A language model using n-gram statistics can:

  1. Read a large corpus.

  2. Count which words tend to follow other words.

  3. Begin with an initial word or sequence.

  4. Select a likely next word.

  5. Continue generating words according to the learned statistical patterns.

This can produce sentences that resemble the style of the original corpus. For example, a model trained on Shakespeare’s works may generate new sentences with Shakespeare-like word patterns.

However, such generated sentences are not necessarily present in the original text. They are newly assembled sequences that follow observed statistical relationships.

Limitations of Markov Text Generation

N-gram and Markov models have significant limitations:

  • They generally rely on a limited amount of preceding context.

  • They may lose relationships across long distances.

  • They can produce grammatically strange sentences.

  • They may generate text that follows local word patterns without expressing a coherent meaning.

  • Statistical similarity does not guarantee semantic accuracy.

A model may therefore generate language that looks plausible while failing to understand what it is saying.


Text Classification

Definition and Applications

Text classification is the task of assigning a category or label to a piece of text.

Common applications include:

  • Spam filtering

  • Sentiment analysis

  • Topic classification

  • Email routing

  • Content moderation

Sentiment Analysis

Sentiment analysis determines whether text expresses an attitude such as positive or negative sentiment.

Example product reviews:

  • “My grandson loved it! So much fun.”

  • “Product broke after a few days.”

  • “One of the best games I’ve played in a long time.”

  • “Kind of cheap and flimsy, not worth it.”

Likely classifications:

  • The first and third reviews are positive.

  • The second and fourth reviews are negative.

Humans often make this judgment by recognizing words associated with sentiment:

  • Positive indicators: “loved,” “fun,” “best”

  • Negative indicators: “broke,” “cheap,” “flimsy”

A computer can learn similar associations from labeled examples.


The Bag-of-Words Model

The bag-of-words model represents text as an unordered collection of words.

For example, the review:

“My grandson loved it”

is represented by the words:

  • “my”

  • “grandson”

  • “loved”

  • “it”

The model does not consider the order in which those words appear. It focuses on whether particular words are present and how often they occur.

Advantages

  • Simple to implement

  • Efficient to compute

  • Useful for identifying word associations

  • Effective for many basic classification tasks

Limitation

The model loses word-order information. These sentences contain the same words but have different meanings:

  • “The dog chased the cat.”

  • “The cat chased the dog.”

A bag-of-words representation may treat them as equivalent because it ignores sequence and grammatical relationships.


Naive Bayes Classification

Bayes’ Rule

A Naive Bayes classifier applies Bayes’ rule to classify text.

Bayes’ rule is:

P(B∣A)=P(A∣B)P(B)P(A)P(B \mid A) = \frac{P(A \mid B)P(B)}{P(A)}P(B∣A)=P(A)P(A∣B)P(B)​

where:

  • P(B∣A)P(B \mid A)P(B∣A) is the probability of BBB given AAA.

  • P(A∣B)P(A \mid B)P(A∣B) is the probability of AAA given BBB.

  • P(B)P(B)P(B) is the prior probability of BBB.

  • P(A)P(A)P(A) is the probability of AAA.

For sentiment analysis, the goal is to calculate the probability that a review is positive or negative given the words in that review.

For the review “my grandson loved it,” the classifier compares:

P(positive∣my, grandson, loved, it)P(\text{positive} \mid \text{my, grandson, loved, it})P(positive∣my, grandson, loved, it)

with:

P(negative∣my, grandson, loved, it)P(\text{negative} \mid \text{my, grandson, loved, it})P(negative∣my, grandson, loved, it)

Removing the Shared Denominator

Applying Bayes’ rule to the positive case gives:

P(positive∣words)=P(words∣positive)P(positive)P(words)P(\text{positive} \mid \text{words}) = \frac{ P(\text{words} \mid \text{positive})P(\text{positive}) }{ P(\text{words}) }P(positive∣words)=P(words)P(words∣positive)P(positive)​

The denominator P(words)P(\text{words})P(words) is the same regardless of whether the review is being evaluated as positive or negative. Therefore, classification can initially compare only the numerator:

P(words∣positive)P(positive)P(\text{words} \mid \text{positive})P(\text{positive})P(words∣positive)P(positive)

and

P(words∣negative)P(negative)P(\text{words} \mid \text{negative})P(\text{negative})P(words∣negative)P(negative)

The resulting values can later be normalized so that the final probabilities sum to 111.

The Naive Independence Assumption

The “naive” part of Naive Bayes is the assumption that the words are conditionally independent of one another given the sentiment category.

Under this assumption:

P(my, grandson, loved, it∣positive)P(\text{my, grandson, loved, it} \mid \text{positive})P(my, grandson, loved, it∣positive)

is approximated as:

P(my∣positive)P(grandson∣positive)P(loved∣positive)P(it∣positive)P(\text{my} \mid \text{positive}) P(\text{grandson} \mid \text{positive}) P(\text{loved} \mid \text{positive}) P(\text{it} \mid \text{positive})P(my∣positive)P(grandson∣positive)P(loved∣positive)P(it∣positive)

Therefore, the positive score is:

P(positive)∏w∈wordsP(w∣positive)P(\text{positive}) \prod_{w \in \text{words}} P(w \mid \text{positive})P(positive)∏w∈words​P(w∣positive)

The negative score is calculated similarly:

P(negative)∏w∈wordsP(w∣negative)P(\text{negative}) \prod_{w \in \text{words}} P(w \mid \text{negative})P(negative)∏w∈words​P(w∣negative)

The independence assumption is usually not literally true. Words influence one another through grammar and meaning. Nevertheless, the assumption simplifies computation and can still produce useful results.

Estimating Probabilities from Training Data

A Naive Bayes classifier requires labeled training data.

The prior probability of positive sentiment can be estimated as:

P(positive)=number of positive reviewstotal number of reviewsP(\text{positive}) = \frac{\text{number of positive reviews}} {\text{total number of reviews}}P(positive)=total number of reviewsnumber of positive reviews​

The conditional probability of a word given positive sentiment can be estimated as:

P(loved∣positive)=number of positive reviews containing “loved”number of positive reviewsP(\text{loved} \mid \text{positive}) = \frac{\text{number of positive reviews containing “loved”}} {\text{number of positive reviews}}P(loved∣positive)=number of positive reviewsnumber of positive reviews containing “loved”​

For example, if 49%49\%49% of training reviews are positive and 51%51\%51% are negative, then:

P(positive)=0.49P(\text{positive}) = 0.49P(positive)=0.49

and

P(negative)=0.51P(\text{negative}) = 0.51P(negative)=0.51

If “my” occurs in 30%30\%30% of positive reviews and 20%20\%20% of negative reviews, then:

P(my∣positive)=0.30P(\text{my} \mid \text{positive}) = 0.30P(my∣positive)=0.30

and

P(my∣negative)=0.20P(\text{my} \mid \text{negative}) = 0.20P(my∣negative)=0.20

The classifier multiplies the prior probability by the conditional probabilities of the words, producing one score for each possible class.

Normalization

The positive and negative scores do not necessarily sum to 111. To turn them into probabilities, they are normalized:

P(positive∣words)=positive scorepositive score+negative scoreP(\text{positive} \mid \text{words}) = \frac{\text{positive score}} {\text{positive score}+\text{negative score}}P(positive∣words)=positive score+negative scorepositive score​

and:

P(negative∣words)=negative scorepositive score+negative scoreP(\text{negative} \mid \text{words}) = \frac{\text{negative score}} {\text{positive score}+\text{negative score}}P(negative∣words)=positive score+negative scorenegative score​

In the example, the review “my grandson loved it” was estimated to have approximately:

  • A 0.680.680.68 probability of being positive

  • A 0.320.320.32 probability of being negative

The classifier would therefore predict positive sentiment.

Zero-Probability Problem

A major issue occurs when a word does not appear in any training example for a category.

For example, if “grandson” never appears in a positive review, then:

P(grandson∣positive)=0P(\text{grandson} \mid \text{positive}) = 0P(grandson∣positive)=0

Because the Naive Bayes calculation multiplies probabilities, the entire positive score becomes zero:

P(positive)⋅0⋅P(other words∣positive)=0P(\text{positive}) \cdot 0 \cdot P(\text{other words} \mid \text{positive}) = 0P(positive)⋅0⋅P(other words∣positive)=0

This would cause the classifier to conclude that the review cannot be positive, even though the missing word may simply be rare.

Laplace Smoothing

Additive smoothing prevents zero probabilities by adding a small value α\alphaα to counts.

A common form is Laplace smoothing, which adds 111 to every count. Conceptually, the classifier pretends that each possible word has appeared at least once in each category.

If a word has never appeared in a positive review, smoothing prevents its probability from being exactly zero. This makes the model less brittle when it encounters rare or previously unseen words.

Practical Performance

A Naive Bayes classifier trained on labeled positive and negative reviews can learn associations such as:

  • “great,” “fun,” and “enjoyed” being associated with positive reviews

  • “cheap,” “overpriced,” and “not worth it” being associated with negative reviews

For example:

  • “I enjoyed it” may receive a high positive probability, such as approximately 0.920.920.92.

  • “Kind of overpriced” may receive a high negative probability, such as approximately 0.960.960.96.

Naive Bayes is useful because it is relatively simple, efficient, and effective for many word-based classification problems, despite its simplifying assumptions.


Numerical Representations of Words

Why Words Must Become Numbers

Many machine-learning models, especially neural networks, operate on numerical inputs. A neural network receives vectors of numbers, transforms them through weighted computations, and produces numerical outputs.

Therefore, language must be converted into a numerical representation before it can be processed by such a model.

One-Hot Representation

A one-hot representation assigns each word a vector containing one 111 and zeros everywhere else.

For a vocabulary containing four words, a possible representation is:

  • “he” →(1,0,0,0)\rightarrow (1,0,0,0)→(1,0,0,0)

  • “wrote” →(0,1,0,0)\rightarrow (0,1,0,0)→(0,1,0,0)

  • “a” →(0,0,1,0)\rightarrow (0,0,1,0)→(0,0,1,0)

  • “book” →(0,0,0,1)\rightarrow (0,0,0,1)→(0,0,0,1)

Each word receives a unique position.

Problems with One-Hot Vectors

High dimensionality

If a vocabulary contains thousands of words, each vector must contain thousands of positions. These vectors become:

  • Long

  • Computationally expensive

  • Mostly filled with zeros

  • Difficult to use efficiently in large models

No semantic similarity

One-hot representations do not naturally express similarity. Words such as:

  • “wrote” and “authored”

  • “book” and “novel”

may have similar meanings, but their one-hot vectors are equally unrelated because their 111s occur in different positions.

A useful semantic representation should place words with related meanings near one another in a vector space.


Distributed Word Representations

A distributed representation represents the meaning of a word across multiple numerical values rather than assigning meaning to one unique position.

Each word is represented by a vector such as:

vword=(v1,v2,…,vd)\mathbf{v}_{\text{word}} = (v_1,v_2,\ldots,v_d)vword​=(v1​,v2​,…,vd​)

The individual dimensions may not have simple human-readable meanings. Meaning is distributed across the entire vector.

The goal is for semantically similar words to have similar vectors.

Distributional Semantics

The idea behind distributed word representations is summarized by the linguistic principle:

A word is understood partly by the company it keeps.

This means that a word’s meaning can be inferred from the words that commonly appear around it.

For example, the phrase:

“For blank he ate”

could reasonably contain:

  • “breakfast”

  • “lunch”

  • “dinner”

Because these words appear in similar contexts, a model may learn that they have related meanings and should have similar vector representations.

A computer can examine a large corpus and identify words that occur in similar contexts. This allows it to learn semantic relationships without requiring a human to define the meaning of every word manually.

Word2Vec

Word2Vec is a model that learns vector representations of words from their surrounding context.

The general process is:

  1. Begin with word vectors that may be random.

  2. Examine a large training corpus.

  3. Observe which words tend to appear in similar contexts.

  4. Adjust the vectors during training.

  5. Place words with similar contextual patterns near one another in vector space.

Examples of words that may become close include:

  • “breakfast,” “lunch,” and “dinner”

  • “book,” “novel,” and “memoir”

  • Singular and plural forms such as “book” and “books”

Measuring Vector Distance

The similarity of two words can be estimated by measuring the distance between their vectors.

For example:

  • “book” and “novel” may have a small distance, approximately 0.340.340.34.

  • “book” and “breakfast” may have a larger distance, approximately 0.640.640.64.

  • “lunch” and “breakfast” may have an even smaller distance, approximately 0.200.200.20.

A smaller distance indicates more similar vector representations and, typically, more similar contextual meanings.

The vector itself may not be directly interpretable, but comparisons between vectors reveal useful semantic information.

Finding Nearby Words

A model can identify the words whose vectors are closest to a given word.

Words close to “book” might include:

  • “books”

  • “essay”

  • “memoir”

  • “essays”

  • “novella”

  • “anthology”

This indicates that the learned representation captures meaningful relationships among words.

Vector Arithmetic and Relationships

Word vectors can encode relationships as well as individual meanings.

Suppose:

  • vking\mathbf{v}_{\text{king}}vking​ represents “king.”

  • vman\mathbf{v}_{\text{man}}vman​ represents “man.”

  • vwoman\mathbf{v}_{\text{woman}}vwoman​ represents “woman.”

The relationship from “man” to “king” can be approximated by:

vking−vman\mathbf{v}_{\text{king}}-\mathbf{v}_{\text{man}}vking​−vman​

Applying this relationship to “woman” gives:

vwoman+(vking−vman)\mathbf{v}_{\text{woman}} + \left( \mathbf{v}_{\text{king}}-\mathbf{v}_{\text{man}} \right)vwoman​+(vking​−vman​)

The closest word to the resulting vector may be “queen.”

This illustrates that word embeddings can capture analogical relationships, not merely word similarity.


Neural Networks for Sequences

Neural Networks and Language

Once words have numerical vector representations, they can be used as inputs to neural networks.

A neural network learns patterns by adjusting its internal weights based on training examples. In language applications, it may learn to:

  • Predict the next word

  • Classify a sentence

  • Translate between languages

  • Answer questions

  • Generate conversational responses

Many language tasks involve converting one sequence into another.

Examples include:

  • English sentence →\rightarrow→ French sentence

  • Question →\rightarrow→ Answer

  • User message →\rightarrow→ Chatbot response

The Variable-Length Problem

Neural networks traditionally expect inputs and outputs of fixed dimensions. Natural-language sequences, however, can have variable lengths:

  • One sentence may contain only a few words.

  • Another may contain many words.

  • The output may have a different length from the input.

A model must therefore support sequence-to-sequence processing, in which one variable-length sequence is transformed into another.


Recurrent Neural Networks

A recurrent neural network (RNN) processes a sequence one element at a time while maintaining a hidden state.

The hidden state stores information from earlier parts of the sequence and passes that information to later steps.

Conceptually:

ht=f(xt,ht−1)\mathbf{h}_t = f(\mathbf{x}_t,\mathbf{h}_{t-1})ht​=f(xt​,ht−1​)

where:

  • xt\mathbf{x}_txt​ is the current input token.

  • ht−1\mathbf{h}_{t-1}ht−1​ is the previous hidden state.

  • ht\mathbf{h}_tht​ is the updated hidden state.

  • fff is the neural-network computation.

Because the hidden state carries information forward, the network can account for word order and prior context.


Encoder–Decoder Architecture

An encoder–decoder architecture uses one neural network to encode an input sequence and another to generate an output sequence.

Encoder

The encoder reads the input one token at a time.

For the question:

“What is the capital of Massachusetts?”

the encoder processes:

  1. “what”

  2. “is”

  3. “the”

  4. “capital”

  5. “of”

  6. “Massachusetts”

At each step, it receives:

  • The current word

  • The hidden state from the previous step

After the final input word, the encoder produces a final hidden state intended to summarize the entire input sequence.

An end-of-input token signals that the encoder has finished reading.

Decoder

The decoder uses the encoded hidden state to generate the output sequence.

For the answer:

“The capital is Boston.”

the decoder may generate:

  1. “the”

  2. “capital”

  3. “is”

  4. “Boston”

  5. An end-of-sequence token

At each step, the decoder uses:

  • The previously generated output word

  • The decoder’s previous hidden state

  • The encoded representation of the input

The output generation stops when the decoder produces an end token.

Limitations of the Basic Encoder–Decoder RNN

The entire input sequence must be compressed into one final hidden state. This creates a bottleneck:

  • Short inputs may fit comfortably into the hidden state.

  • Long inputs contain more information than one vector can easily preserve.

  • Important details from early in the sequence may be lost.

  • Translation and question answering become more difficult for long sequences.

Another limitation is sequential processing. Each step depends on the previous step, so:

  • The next input cannot be processed until the previous hidden state exists.

  • Training is difficult to parallelize.

  • Long sequences require many sequential operations.

  • Training becomes increasingly slow as datasets and models grow.

These limitations motivated the development of attention mechanisms and Transformer architectures.


Attention Mechanisms

Core Idea

Attention allows a model to decide which parts of an input are most relevant when generating a particular output token.

Instead of relying only on one final hidden state, the decoder can examine all encoder hidden states and assign each one an attention score.

For a particular output step, the model might assign high scores to:

  • “capital”

  • “Massachusetts”

when generating the answer “Boston.”

Attention Scores

An attention score measures how relevant an input representation is to the current output-generation step.

Scores may be calculated using:

  • A vector dot product

  • Similarity between representations

  • A separately trained neural network

During training, the model learns which attention patterns lead to better predictions.

Weighted Context Vectors

Each input word has an associated hidden-state vector. Let:

  • hi\mathbf{h}_ihi​ be the hidden state for input word iii.

  • αi\alpha_iαi​ be the attention weight for that word.

The context vector can be calculated as a weighted combination:

c=∑iαihi\mathbf{c} = \sum_i \alpha_i \mathbf{h}_ic=∑i​αi​hi​

The context vector emphasizes the input representations that are most relevant to the current output word. It is then passed to the decoder to help generate the next token.

Attention in Translation

Attention was especially influential in machine translation.

When translating an English sentence into French, attention scores can show which English words the model uses when generating each French word.

A visualization may represent:

  • English words along one axis

  • French words along another axis

  • Brighter cells for higher attention scores

Often, a French word primarily attends to its English equivalent. In other cases, a word may attend to several input words. For example, a word representing “economic” may attend strongly to both “economic” and “European” if their combined context is relevant.

Attention visualizations help reveal what information a model is using to generate its output.

Benefits of Attention

Attention:

  • Reduces the single-vector bottleneck of basic encoder–decoder RNNs.

  • Allows the decoder to refer directly to all input positions.

  • Helps preserve relevant information from long inputs.

  • Makes relationships between input and output words easier to model.

  • Allows different input words to receive different levels of importance at different output steps.


Transformer Architecture

Motivation for Transformers

Although attention improves sequence processing, recurrent neural networks still process tokens sequentially. This prevents efficient parallelization.

A Transformer addresses this problem by processing input tokens in parallel rather than requiring each token to wait for the previous one.

This provides major advantages:

  • Faster training

  • Better use of parallel computing hardware

  • Improved scalability to large datasets

  • More effective training of large language models

Parallel Word Processing

In a Transformer encoder, each input word is processed through the same general network at the same time.

Each word is transformed into an encoded representation that captures information relevant to later processing. Because the words are handled in parallel, the system does not need to wait for a recurrent hidden state from the previous word.

However, processing every word independently creates a new problem: the model may lose word order.


Positional Encoding

Positional encoding adds information about a word’s location in the sequence.

For example, a positional encoding can indicate that a word is:

  • First

  • Second

  • Third

  • Later in the sentence

The input representation combines the word information and its position:

zi=wi+pi\mathbf{z}_i = \mathbf{w}_i+\mathbf{p}_izi​=wi​+pi​

where:

  • wi\mathbf{w}_iwi​ is the vector representation of the word.

  • pi\mathbf{p}_ipi​ is the positional encoding.

  • zi\mathbf{z}_izi​ is the combined representation.

This allows the Transformer to process words in parallel while still distinguishing between different word orders.

Word order is important because:

  • “Sherlock Holmes gave the book to Watson.”

  • “Watson gave the book to Sherlock Holmes.”

contain the same words but express different meanings.


Self-Attention

Self-attention allows each input word to examine the other words in the same input sequence.

This is important because a word’s meaning often depends on its context. A word may have different interpretations depending on the words surrounding it.

During self-attention, each word determines which other input words are important for constructing its encoded representation.

The process can be summarized as:

  1. Start with word and positional representations.

  2. Compare each word with other words in the sequence.

  3. Assign attention weights to relevant words.

  4. Combine information from those words.

  5. Produce a context-sensitive representation.

Multi-Headed Attention

A Transformer often uses multi-headed attention, in which several attention mechanisms operate at the same time.

Each attention head can learn to focus on a different aspect of the input, such as:

  • Grammatical relationships

  • Subject–verb relationships

  • Long-distance dependencies

  • Semantic associations

  • Word order or positional relationships

Multiple heads allow the model to examine several types of relationships simultaneously.

Repeated Transformer Layers

The self-attention and feed-forward neural-network operations can be repeated in multiple layers.

Repeated layers allow the model to learn:

  • More abstract patterns

  • Deeper relationships

  • Complex grammatical structures

  • Higher-level semantic information

The result is a set of encoded representations that contain both word-level and contextual information.


Transformer Decoders

A Transformer decoder generates an output sequence one token at a time, but its internal computations can be designed to take advantage of parallelism during training.

The decoder uses several types of information.

Output Positional Information

The decoder receives the previously generated output tokens along with positional encodings. This tells it:

  • What output words have already been generated

  • Where each word appears in the output sequence

Decoder Self-Attention

Decoder self-attention allows an output token to attend to other output tokens, especially previously generated ones.

This helps the decoder maintain:

  • Grammatical consistency

  • Coherent word order

  • Agreement between words

  • Continuity of meaning across the output

Attention to Encoder Representations

The decoder also attends to the encoded representations of the input sequence.

This lets it determine which input words are relevant when producing each output token.

For example, while generating “Boston” in response to “What is the capital of Massachusetts?”, the decoder can give greater attention to the encoded representations of “capital” and “Massachusetts.”

Overall Encoder–Decoder Transformer Process

A Transformer sequence-to-sequence system can be summarized as follows:

  1. Convert input words into numerical vectors.

  2. Add positional encodings.

  3. Apply self-attention and feed-forward layers to produce encoded input representations.

  4. Give the decoder the previous output tokens and their positions.

  5. Apply decoder self-attention.

  6. Allow the decoder to attend to encoded input representations.

  7. Predict the next output token.

  8. Continue until an end-of-sequence token is produced.

This architecture supports applications such as:

  • Machine translation

  • Question answering

  • Conversational agents

  • Text generation

  • Summarization

Transformer Variants

Not every Transformer uses the same complete structure. Variants may:

  • Use only an encoder

  • Use only a decoder

  • Use both an encoder and a decoder

  • Combine attention and feed-forward layers in different ways

Despite these differences, the central principle remains the use of attention to identify the information most relevant to the current computation.


The Broader Development of Artificial Intelligence

The study of NLP builds on several major areas of artificial intelligence.

Search

Search-based AI explores possible actions or states to find solutions.

Applications include:

  • Finding paths

  • Playing games

  • Selecting optimal decisions

Knowledge Representation

Knowledge-based AI stores facts and relationships and uses them to derive new information.

The system can represent what it knows and reason from that knowledge.

Probability

Probability allows AI systems to reason under uncertainty.

Instead of treating information as definitely true or false, a system can assign degrees of belief to possible outcomes.

Optimization

Optimization frames a problem as maximizing or minimizing an objective function.

AI systems can search for parameter values or decisions that produce the best result according to a defined measure.

Machine Learning

Machine learning enables systems to infer patterns from training data rather than relying entirely on manually written rules.

A model learns how inputs relate to outputs by examining examples.

Neural Networks

Neural networks consist of interconnected computational units with adjustable weights.

During training, the weights are updated so that the network becomes better at mapping inputs to desired outputs. Neural networks are particularly powerful for learning complex patterns in images, language, and other data.

Natural Language Processing

NLP applies these ideas to human language. It must address:

  • Complex structure

  • Ambiguous syntax

  • Variable meanings

  • Word order

  • Context dependence

  • The difference between grammatical form and meaningful content

Modern systems combine numerical word representations, neural networks, attention, and large-scale training data to process and generate language.

Natural language remains difficult because it is highly context-dependent: the same word can have different meanings in different settings, and the same sentence can support multiple interpretations. Attention-based and Transformer models improve the ability to use relevant context, but language understanding remains an active area of artificial intelligence research.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent