Natural Language Processing


Natural Language Processing

Simon
Welcome back to our final episode on artificial intelligence with Python. Today we're focusing on natural language processing, or NLP: getting computers to work with the way people communicate naturally, using languages such as English.

Anna
That is a major shift from the problems we've discussed before. Earlier, we framed problems in forms computers handle more directly, such as search problems, constraint satisfaction problems, or optimization problems. Now the challenge is to take language, with all its nuance and complexity, and make it understandable to a computer.

Simon
NLP includes many different tasks. Automatic summarization creates a shorter version of a longer text. Information extraction pulls relevant facts from text. Machine translation converts text from one language to another. Question answering interprets a question and generates a response, while text classification assigns labels such as positive or negative, or inbox or spam.

Anna
Before building systems for those tasks, we need to understand what makes language difficult. Two especially important ideas are syntax and semantics. Syntax concerns the structure of language: how words are arranged into a well-formed sentence. Semantics concerns meaning: what words and sentences actually express.

Simon
Consider the sentence, "Just before nine o'clock Sherlock Holmes stepped briskly into the room." Its words form a syntactically valid structure. If we rearrange them into, "Just before Sherlock Holmes nine o'clock stepped briskly the room," we still have recognizable English words, but they no longer form a valid sentence.

Anna
And even a syntactically valid sentence can be ambiguous. Take, "I saw the man on the mountain with a telescope." One interpretation is that I used the telescope to see the man. Another is that the man on the mountain had the telescope. The same words and structure can support different interpretations.

Simon
Semantics also means recognizing when different sentences have essentially the same meaning. "Just before nine o'clock Sherlock Holmes stepped briskly into the room" and "A few minutes before nine, Sherlock Holmes walked quickly into the room" use different wording but communicate something very similar.

Anna
And syntax by itself is not enough. Noam Chomsky's famous example, "Colorless green ideas sleep furiously," is structurally well formed: adjectives modify a noun, and the verb and adverb appear in appropriate positions. Yet the sentence, taken as a whole, does not really convey a meaningful idea.

Simon
One way to teach a computer about structure is to formalize rules of language. A formal grammar is a system of rules for generating sentences. The lesson focuses on context-free grammars, or CFGs, which use rules to describe how larger language units can be built from smaller ones.

Anna
In a CFG, terminal symbols are the final words generated in a sentence. Nonterminal symbols are categories that can be replaced by other symbols or by terminal words. For example, N can represent a noun, V a verb, and D a determiner such as "the," "a," or "an."

Simon
A rewriting rule might say that N can become "she," "city," "car," or "Harry." Another rule could say D becomes "the," "a," or "an." The vertical bar means that any of the listed alternatives is allowed.

Anna
CFGs can also define phrases. An NP, or noun phrase, might be defined as either N or D followed by N. That means "she" can be a noun phrase, while "the city" is also a noun phrase made from a determiner and a noun.

Simon
Similarly, a VP, or verb phrase, might be either V or V followed by NP. So "walked" is a verb phrase, and "saw the city" is also a verb phrase because it contains a verb followed by a noun phrase. Finally, a sentence can be defined as NP followed by VP.

Anna
Those rules can generate and analyze a sentence such as "She saw the city." The noun phrase is "she," and the verb phrase is "saw the city." Inside that verb phrase, "the city" is itself a noun phrase.

Simon
The Natural Language Toolkit, or NLTK, provides tools for working with these grammars in Python. A simple NLTK CFG can parse "she walked" and show that "she" is a noun phrase and "walked" is a verb phrase. It can also parse the more complex sentence "she saw the city."

Anna
A richer grammar can include AP for adjective phrase and PP for prepositional phrase. With those additions, NLTK can parse a sentence such as "she saw the wide street," identifying the adjective inside the noun phrase.

Simon
It can also expose ambiguity. In "she saw the dog with the binoculars," one syntax tree treats "the dog with the binoculars" as a noun phrase, suggesting the dog has the binoculars. Another treats "with the binoculars" as a prepositional phrase modifying the act of seeing, suggesting she used the binoculars.

Anna
The weakness is that someone must write all those grammar rules. English has a huge number of complicated patterns, and manually specifying a rule for every possible sentence would require enormous effort. That motivates a statistical approach: learn patterns from existing text.

Simon
A useful starting point is the n-gram. An n-gram is a contiguous sequence of n items from text, such as characters or words. A bigram contains two words, while a trigram contains three.

Anna
For example, trigrams from a Sherlock Holmes passage might include "how often have," "often have I," "have I said," "I said to," and "said to you." By collecting many such sequences from a corpus, a computer can learn which groups of words commonly occur next to each other.

Simon
Tokenization is the process of splitting a sequence of characters into pieces. In this setting, we split a long text into individual words and then examine sequences of those words. NLTK can extract n-grams from a corpus, and Python's Counter can identify the most common ones.

Anna
In a Sherlock Holmes corpus, common bigrams might include "of the," "in the," and "it was." Common trigrams might include "it was a," "one of the," and "I think that." These frequencies provide statistical information about the structure of language.

Simon
Those statistics can be used to build a Markov chain. A Markov chain predicts the next value based on preceding values. For language, it can use common word sequences to predict what word is likely to come next.

Anna
A generator trained on Shakespeare's works can therefore produce new sentences that do not necessarily appear in the original text, but that follow similar statistical patterns. However, matching local word patterns does not guarantee that the generated sentences have a sensible meaning.

Simon
Now let's turn to text classification: assigning a category to a piece of text. Examples include filtering email into inbox or spam, and sentiment analysis, where a review is classified as positive or negative.

Anna
With reviews such as "My grandson loved it! So much fun" and "Product broke after a few days," people can often identify the sentiment by noticing words associated with each category. Words such as "loved," "fun," and "best" suggest positive sentiment, while "broke," "cheap," and "flimsy" suggest negative sentiment.

Simon
A simple model for this is the bag-of-words representation. It treats a text as an unordered collection of words, ignoring whether a word came first, second, or third. That loses information about word order, but it makes the classification problem easier.

Anna
The bag-of-words model can be combined with a Naive Bayes classifier. Bayes' rule lets us calculate the probability of a sentiment category given the words in a review. For a review such as "my grandson loved it," we compare the probability of positive sentiment with the probability of negative sentiment.

Simon
The classifier uses the probability of the category together with the probabilities of the words appearing given that category. So for the positive case, it multiplies the prior probability of a positive review by the probabilities of seeing "my," "grandson," "loved," and "it" in positive reviews.

Anna
The "naive" assumption is that the words are independent of one another once we know the sentiment category. In real language, words are not truly independent: the presence of one word can affect the likelihood of another. But the simplifying assumption makes the calculation practical and can still produce useful results.

Simon
The prior probability of positive sentiment can be estimated by counting positive training examples and dividing by the total number of examples. A conditional probability such as the probability of "loved" given positive sentiment comes from counting positive examples containing "loved" and dividing by the number of positive examples.

Anna
After calculating scores for both positive and negative sentiment, the scores may not add up to one. We normalize them to obtain a probability distribution. In the example, the review "my grandson loved it" receives a probability of 0.68 for positive sentiment and 0.32 for negative sentiment.

Simon
A problem occurs when a word never appears in a category during training. Its conditional probability becomes zero, and multiplying by that zero makes the entire category score zero. That is too strong a conclusion when the word may simply be rare.

Anna
The usual solution is additive smoothing. Laplace smoothing adds one to each count, effectively pretending that every possible word-category combination has been seen once more than it really has. This prevents zero probabilities from dominating the calculation.

Simon
In Python, a Naive Bayes sentiment classifier can train on labeled positive and negative reviews. With suitable sample data, it might assign about 0.92 probability of positive sentiment to "I enjoyed it" and about 0.96 probability of negative sentiment to "kind of overpriced."

Anna
Naive Bayes is useful, but more sophisticated models need numerical representations. Neural networks take vectors of numbers as input and produce vectors as output, so we need a way to convert words into vectors.

Simon
The simplest method is one-hot encoding. If the vocabulary contains four words, "he" might be represented as 1,0,0,0; "wrote" as 0,1,0,0; "a" as 0,0,1,0; and "book" as 0,0,0,1.

Anna
One-hot vectors have two important problems. A vocabulary of thousands of words produces very long vectors, and similar words do not receive similar representations. Words such as "wrote" and "authored," or "book" and "novel," still have completely different one-hot vectors.

Simon
A distributed representation spreads a word's meaning across many numerical values. Ideally, words with similar meanings have vectors that are close together. This idea is inspired by the linguistic principle that we know a word by the company it keeps: its surrounding context helps reveal its meaning.

Anna
For example, in the context "For blank he ate," words such as "breakfast," "lunch," and "dinner" are all plausible. Because they occur in similar contexts, a model can learn that they have related meanings and should be near one another in vector space.

Simon
Word2vec is a model that learns these word vectors from context. Starting from representations, it adjusts them using training data so that words appearing in similar contexts tend to have similar vectors.

Anna
A vector itself may not be easy to interpret, but distances between vectors are useful. In the example, "book" is closer to "novel" than to "breakfast," while "lunch" and "breakfast" are especially close. The nearest words to "book" can include "books," "essay," "memoir," "novella," and "anthology."

Simon
Word2vec can also capture relationships. Subtracting the vector for "man" from the vector for "king" represents a relationship, and applying that relationship to the vector for "woman" produces a vector near "queen." So the model captures more than similarity; it can also reflect connections among words.

Anna
Once words are represented numerically, they can be passed into neural networks. One important use is machine translation: translating an English word or, more usefully, an entire English sentence into French. Another is question answering, such as converting "What is the capital of Massachusetts?" into "The capital is Boston."

Simon
The difficulty is that neural networks traditionally expect fixed-size inputs and outputs, while sentences have variable lengths. This is a sequence-to-sequence problem: we need to transform one sequence, such as a question or English sentence, into another sequence, such as an answer or French translation.

Anna
Recurrent neural networks address sequences by running the network repeatedly and passing a hidden state from one step to the next. The hidden state carries relevant information from earlier words as later words are processed.

Simon
An encoder-decoder architecture uses one recurrent network to encode the input and another to decode the output. For the question "What is the capital of Massachusetts?", the encoder processes each word and updates its hidden state, including a special end token to indicate that the input is complete.

Anna
The decoder then begins generating the answer. It might produce "the," pass that output and its hidden state into the next step, produce "capital," then "is," and finally "Boston." It generates an end token after the final word to signal that the output is finished.

Simon
A major weakness is that the entire input sequence is compressed into one final hidden state. As the input grows longer, that single state has to retain more and more information, making it difficult to preserve everything needed for accurate output.

Anna
Attention addresses that problem by allowing the decoder to decide which input words matter most at each output step. When generating "Boston," the model might pay especially close attention to "capital" and "Massachusetts."

Simon
The model calculates attention scores for the input words. These scores can be produced using methods such as a dot product or a trained neural network. The input hidden-state vectors are then combined using a weighted average, giving the decoder a context vector focused on the most relevant words.

Anna
Attention was especially important in machine translation. Visualizations can show which source words receive the highest scores when each target word is generated. Often a translated word focuses on its corresponding source word, though it can also attend to several source words, such as a word for "economic" attending partly to "European" as well.

Simon
Recurrent networks with attention are powerful, but they still process words sequentially. Each step depends on the hidden state from the previous step, so the process is difficult to parallelize. This becomes increasingly costly as language models use larger datasets and longer training processes.

Anna
That limitation motivated the Transformer architecture. Transformers can process input words independently and in parallel, making training more efficient. But processing words independently creates a new problem: the model could lose word order.

Simon
Word order matters because "Sherlock Holmes gave the book to Watson" means something different from "Watson gave the book to Sherlock Holmes." Transformers address this with positional encoding, a vector that represents where each word appears in the sentence.

Anna
The word representation and positional encoding are combined before entering the network. This lets the model use both the identity of a word and its position when building an encoded representation.

Simon
Transformers also use self-attention. Each input word can attend to other input words, because the meaning of a word depends on its context. Multiple self-attention mechanisms can operate together; this is called multi-headed attention, and different heads can learn to focus on different aspects of the input.

Anna
The self-attention and feed-forward neural network layers can be repeated, creating deeper representations and allowing the model to learn more complex patterns. The encoder processes all input words this way and produces encoded representations for them.

Simon
A Transformer decoder has a similar structure. It uses the previous output words and their positional encodings, applies self-attention to the output sequence, and uses feed-forward layers. It also includes attention to the encoder's representations, so each new output word can focus on the most relevant input words.

Anna
This combination lets the decoder consider both what it has already generated and what appeared in the input. Because the architecture supports parallel processing during training, it has become highly effective for conversational AI, machine translation, and many other NLP tasks.

Simon
There are different Transformer variants. Some use only an encoder, some only a decoder, and others combine components differently. The central idea remains attention: learning which information is most important for representing language and predicting the next output.

Anna
Let's connect this final topic to the whole course. We began with search, where AI finds solutions, plays games, and chooses actions. We studied knowledge representation, probability for uncertain situations, and optimization for maximizing or minimizing objectives.

Simon
We then explored machine learning, where systems learn patterns from data, including neural networks whose weights are trained to map inputs to outputs. Natural language processing builds on those ideas to handle syntax, semantics, ambiguity, classification, generation, translation, and question answering.

Anna
And this is only an introduction. Natural language remains difficult because structure and meaning can be ambiguous, and the field continues to develop new algorithms and models. But the progression is clear: computers move from formal representations, to statistical patterns, to learned numerical meanings, and finally to attention-based architectures that can process and generate complex sequences.

Simon
So the key lesson is that making computers work with language requires several layers of understanding. We need syntax to reason about structure, semantics to reason about meaning, statistical models to learn usage patterns, and neural architectures such as recurrent networks and Transformers to represent and generate sequences.

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