NLP & Transformers

From Tokens to Self-Attention and Generative AI

Understanding human language is one of the most complex tasks in AI. Whether it's an **Autonomous Vehicle** interpreting a passenger's voice command or a **Medical AI** parsing a messy clinical report, Natural Language Processing (NLP) is the bridge between human intent and machine action.

In this chapter, we master the evolution of NLP: from basic **Vectorization** to the revolutionary **Transformer** architecture. We explore how **Self-Attention** allows models to understand the context of every word in a sentence simultaneously, powering the modern age of Large Language Models (LLMs).

Vectorization: Turning Text into Tensors

Computers don't see words; they see numbers. **Vectorization** is the process of mapping words to numerical tensors. We move from simple **One-Hot Encoding** (which treats words as isolated entities) to **Embeddings**, where words with similar meanings (like "Tachycardia" and "Arrythmia") are placed near each other in a multi-dimensional space.

PythonRuns entirely in your browser — nothing is sent to a server.

Intent Classification & Language Models

A **Language Model** predicts the probability of the next word in a sequence. In an AV context, this powers **Intent Classification**: determining if a passenger wants the car to "Stop now!" versus "Stop at the next signal." We use Softmax layers to turn raw model outputs into a probability distribution over possible intents.

PythonRuns entirely in your browser — nothing is sent to a server.

The Transformer: Attention is All You Need

Traditional RNNs process text word-by-word, which is slow and forgets long-term context. The **Transformer** architecture solves this using **Self-Attention**. It allows every word in a sentence to "attend" to every other word, regardless of distance. This is how a model knows that in the sentence *"The patient was prescribed aspirin because his fever was high"*, the word *"his"* refers back to *"patient."*

PythonRuns entirely in your browser — nothing is sent to a server.

Practice Questions

Question 1

What is the primary advantage of Embeddings over One-Hot Encoding?

  • Embeddings are easier to spell
  • Embeddings capture semantic relationships by placing similar words close together in vector space
  • One-hot encoding is too fast for modern GPUs
  • Embeddings only work with pictures

Question 2

Why is Self-Attention superior to RNNs for long-range dependencies in text?

  • It processes words one-by-one very slowly
  • It allows every word to interact with every other word in a single step, regardless of distance
  • It requires a special keyboard to type
  • It only works on the first word of a sentence