Mid-Semester Exam Revision: NLP Foundations
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Ambiguities in natural language and why language is hard — covered in Lecture 1, Introduction to NLP
- The levels of language understanding, from phonetics to pragmatics — covered in Lecture 1, Introduction to NLP
- Classical, modern, and hybrid NLP systems — covered in Lecture 1, Introduction to NLP
- Accuracy, precision, recall, F1, and task-specific metrics such as ROUGE — covered in Lecture 1, Introduction to NLP
- Term-document matrices, cosine similarity, and TF-IDF weighting — covered in Lecture 2, Vector Semantics and Word Embeddings
- Skip-gram with negative sampling: sigmoid probabilities, the loss, and the update step — covered in Lecture 3, Word Embeddings and Word2Vec
- Markov assumption, bigram estimation, Laplace smoothing, interpolation, and backoff — covered in Lecture 4, CBOW, GloVe, and Statistical Language Modeling
- Perplexity as the intrinsic evaluation measure — covered in Lecture 5, Perplexity and Neural Language Models
- Neural network foundations: perceptrons, forward propagation, sigmoid, and softmax — covered in Lecture 5, Perplexity and Neural Language Models
- Large language models, fine-tuning, and zero-shot versus few-shot prompt engineering — covered in Lecture 6, Large Language Models and Part-of-Speech Tagging
This revision covers the complete pre-mid-semester syllabus for Natural Language Processing: the introductory module, vector semantics and TF-IDF, word embeddings with skip-gram negative sampling, statistical n-gram language modeling, and neural language models with an introduction to large language models. Along the way it collects every piece of exam guidance, worked computation, and clarification that came up during the session.
8.1 Introduction to NLP: Applications, Ambiguities, and Levels of Understanding
The first module is the introduction to NLP, and it is the easiest place to gain marks because the questions here are application-oriented rather than computational. The recap of this module covers what NLP is, where it is relevant, why it is worth studying, the interesting applications, the different roles NLP engineers can play, and a quick history of the field. For this module the reference book is the James Allen book, which is available online. Master the vocabulary and the example types in this module, and the conceptual marks follow cheaply.
8.1.1 What the Module Covers
Hook: A web search engine returns links to pages that mention your words. What would it take for a machine to instead understand what you actually asked — your intent — and answer accordingly? That step from matching words to understanding meaning is the gap NLP works to close.
The module sets out the core question: what is Natural Language Processing? NLP (the area of AI concerned with making machines understand and generate human language) is not one single technique but a whole stack of techniques, and the module first maps the territory. It covers where NLP is relevant, why we study it, and what the interesting applications are. It also maps the different roles an NLP engineer can play in industry, and surveys real-world applications that make the area useful. A quick history of the field rounds out the introduction. The reason this module exists is to give a clear picture of what the course content covers and why each later topic matters, so the rest of the syllabus does not look like a pile of unrelated algorithms.
A case study kind of example was used to understand the complexity of human language. This is the module's central message: natural language is hard, and that difficulty is what makes NLP interesting. The module walks through the different interesting applications, and the challenges that make natural language such a difficult problem, including the ambiguities that exist in language, with examples of each type.
The different roles an NLP engineer can play in industry all sit on this foundation: engineers who build and train models, engineers who ship and serve them, data scientists who turn language data into features, and specialists who design the human-facing applications. For the exam, what matters is being able to say, for a given problem, whether it is an NLP application and how you would implement it at a basic level — the applications themselves, not their internal machinery.
8.1.2 Why Natural Language Is Hard
Human language is genuinely hard for machines. The module opens with a small case study to show the complexity of human language, so that the difficulty of NLP is felt rather than asserted. Think about a simple booking dialogue: a customer says "I want to book a table for two tonight", and the system must decide what "tonight" means (which day, which time zone), what "two" attaches to (people, not tables), and whether "book" is a verb or a noun in this sentence. Each of those decisions is automatic for a human and opaque for a machine.
The challenges of NLP are the reason the field exists: language is ambiguous (one string of words, several meanings), context-dependent (the same word means different things in different surroundings), and full of exceptions (every rule of grammar has counterexamples, from irregular plurals to idioms). A machine must handle all of these to be useful. The difficulty is not a bug in the field; it is the field's defining problem, and every later topic in the syllabus — vector semantics, language models, neural networks — is a different weapon aimed at it.
8.1.3 Ambiguities in Natural Language
Ambiguity is the property of language where one piece of text can carry several meanings. The module distinguishes the different types of ambiguities and expects students to understand each type in depth, with examples. The differences between the different ambiguities matter: a word can be ambiguous on its own (lexical ambiguity), and a sentence can be ambiguous in structure or in what it refers to. Knowing which type of ambiguity an example shows, and why, is exactly the kind of conceptual question this module produces.
The main types to recognize:
- Lexical ambiguity — a single word carries several meanings. "Bank" is a financial institution or a riverbank; "can" is a container, a modal verb, or the verb "to put in a can". The classic classroom sentence "I can can the can" uses all three roles of can in one sentence, and a machine must use context to sort them out.
- Structural (syntactic) ambiguity — a sentence has more than one possible grammatical structure. In "The man saw the boy with the telescope", the telescope can belong to the man (he looked through it) or to the boy (the boy was holding it). Same seven words, two different arrangements of who owns what.
- Referential (anaphoric) ambiguity — a pronoun or phrase has more than one possible antecedent. In "Ravi told Kiran that he had passed", he could refer to either person until the wider context pins it down.
- Pragmatic ambiguity — the same sentence carries different intended meanings in different situations. "Can you pass the salt?" is a question about ability in form, but a request for action in practice. The intent, not the literal words, decides the meaning.
For the exam, be ready to name the type of ambiguity in a given example and justify the choice by pointing at exactly which part of the sentence carries the multiple readings.
8.1.4 Levels of Language Understanding
Language understanding happens at several levels, and the module asks students to explain each level and how the levels differentiate, with examples. The standard stack of levels runs from the sounds of language up to meaning in context:
- Phonetics — the physical sounds of language and how they are produced and perceived.
- Phonology — how sounds combine and pattern in a particular language.
- Morphology — word structure: how roots, prefixes, and suffixes build words (un-break-able).
- Syntax — sentence structure: how words combine into grammatical sentences ("the cat sat" is well-formed; "cat the sat" is not).
- Semantics — meaning: what words and sentences denote, independent of who says them.
- Discourse — multi-sentence structure: how sentences link together, including coreference, where later mentions refer back to earlier ones ("Ravi bought a phone. He charged it overnight" — he and it point backward).
- Pragmatics — meaning in context and intent: what a speaker means by an utterance in a situation, beyond the literal words.
Some texts merge phonetics and phonology into one "sounds" level or add a separate lexical level for word knowledge, which is why you may see the stack counted as six levels in one book and seven in another; the James Allen diagram used in the module names the full set above, and any enumeration that names these seven layers is the complete answer. The exam asks for the levels, an example of each, and how the levels differ — the differences matter more than the count.
Q: Do these levels still matter now that large language models do so much automatically? A: Yes. Today's large language models can already operate up to the discourse level: they can do coreference resolution, and they can do contextual understanding using the attention mechanism, including semantic and pragmatic behavior. Even in the agentic area, these levels of language understanding play different functional roles — a model that plans a multi-step task must still track what earlier sentences referred to, which is discourse, and what the user actually wants, which is pragmatics.
The same stack shows up inside every NLP application in the same shape: there is an understanding part, and then a generation part. A conversational AI system has to understand what the user's intent is and what the entities are, and then has to generate the response. That is exactly an encoder-decoder pattern: understand first, then generate. When you describe any NLP system at a basic level, this two-phase pattern is the skeleton to draw.
8.1.5 Classical, Modern, and Hybrid NLP Systems
The module contrasts the architecture of a classical NLP system with modern NLP systems, and introduces hybrid systems. A classical NLP system runs explicit pipelines: tokenization, parsing, feature engineering, and rules. Every stage is hand-designed: split the text into tokens, parse the grammar, engineer the features, apply the rules. A modern NLP system leans on learned representations and large language models: instead of hand-designed rules, the model learns patterns from data. A hybrid NLP system combines the two: for lighter processing it is a good idea to use classical NLP pipelines; for advanced reasoning kind of tasks, use LLMs; and for post-processing, use guardrails and rules, which are again the classical aspect.
| Dimension | Classical NLP system | Modern NLP system | Hybrid NLP system |
|---|---|---|---|
| Core engine | Explicit rules and pipelines | Learned representations, LLMs | Classical pipelines + LLMs + guardrails |
| Speed and cost | Cheap, fast, predictable | Expensive, slower | Cheap for light work, LLM only for hard work |
| Strengths | Transparent, easy to audit, deterministic | Powerful on open-ended language | Best of both when split by task difficulty |
| Weaknesses | Brittle on unseen language | Opaque, costly, can hallucinate | Needs careful design of which task goes where |
This hybrid pattern is the recommended way to build NLP applications, and it is the same idea for every concept studied in the course: light work goes to the cheap classical pipeline, hard reasoning goes to the large model, and safety checks wrap around the outside. In an exam answer about how you would implement an NLP application, sketching this split — pipeline for the simple parts, LLM for the reasoning parts, guardrails around the edges — is the pattern the course teaches.
8.1.6 Evaluating NLP Systems
Another important part of the module is evaluating NLP systems: what are the different metrics used for NLP? It is not just accuracy. There are task-specific measures such as accuracy and the ROUGE score, F1 score, and considerations of data and generalization. Simple problems on F1 score, accuracy, precision, and recall are possible, because precision and recall have been practiced time and again across courses.
The distinction to internalize: accuracy is the share of all predictions that are right; precision is the share of positive predictions that are right; recall is the share of actual positives that were found; and the F1 score combines precision and recall. With true positives (correct positive calls), false positives (negative cases called positive), false negatives (positive cases missed), and true negatives:
Worked example: precision, recall, and F1 on a spam filter. A filter sees 100 emails: 20 are actually spam and 80 are not. The filter flags 15 emails as spam, and 12 of those flags are correct.
- (spam correctly flagged), (clean mail flagged as spam), (spam not flagged), (clean mail not flagged). The numbers line up: flagged, actual spam.
- Accuracy: , so 89% of all decisions are right.
- Precision: — of everything the filter called spam, 80% really was.
- Recall: — of all real spam, the filter caught 60%.
- F1: .
Sense-check: accuracy is high because there are many easy clean emails, while recall is much lower because a third of spam slips through; F1, the balanced score, sits between precision and recall. That gap between accuracy and F1 is exactly why "it is not just accuracy" — a system can look great on accuracy while failing at the rare class that matters.
Pitfall: precision and recall trade off against each other. If you want to catch every spam email (high recall), you will also flag more clean mail (low precision). If you only flag very confident spam (high precision), you will miss more real spam (low recall). Do not describe one without being able to say what the other loses. Also remember ROUGE is the task-specific measure for summarization-style tasks, not a substitute for F1 — know which metric fits which task.
8.1.7 Student Questions and Answers
Q: A student points out that the announced mark distribution adds up to twenty-nine instead of thirty.
A: That is exactly why the announcement said plus or minus one mark. Some questions carry four or five marks: POS tagging could be five marks, vector semantics could be five. The distribution is roughly equal among questions, and depending on the length or complexity of the problem, any of POS tagging, vector semantics, or language modeling could carry a little more weight. So do not fixate on the exact arithmetic of the mark split; the message is that every module carries a meaningful share.
Q: A student asks whether the stop word list will be given in the exam, or whether they must state it themselves.
A: Either the list will be given in the exam, and then that list must be used, or it will not be given, and then the student must write all assumptions in the paper, stating which words were treated as stop words. The principle is the same in every such question: when the exam does not fix a choice, make a sensible assumption and write it out, so the answer is unambiguous to grade.
Q: A student asks whether the difficulty level differs between the regular and the makeup exam.
A: The papers are more or less kept at the same difficulty, but it depends on what topics each student is strong in. There will not be a replica of questions between the regular and makeup papers; they are roughly eighty to ninety percent similar, not a major difference. Prepare the full syllabus and the difference between the two papers will not matter.
8.1.8 Exam Notes
Exam note: write the justification of answers wherever required, give the specific formulas used, and use the formula specified in the question. Expect an application-oriented case study question on this module. The typical form: given a particular problem, decide whether it is an NLP application, and if it is, explain how to implement it at a basic level. A clear picture of NLP applications is what is needed, not deep detail.
Exam note: a question may ask about preprocessing — what the different preprocessing steps are, and to define these steps with an example. Conceptual questions on why NLP is hard, the types of ambiguities with examples, and the levels of language understanding with examples and their differences are all in scope. Simple numerical problems on precision, recall, accuracy, and F1 score are possible.
Recap and bridge. This module gives the vocabulary for everything that follows: language is ambiguous at several levels, systems are understood in an encoder-decoder shape, and evaluation means more than accuracy. The next module starts the first big tool for taming that ambiguity — representing words as vectors, so that meaning becomes geometry a machine can compute with.
8.2 Vector Semantics: Frequency-Based Embeddings and TF-IDF
The core idea of this module: semantics can be better represented for understanding if words are represented as vectors. If you want to find the semantic relations among words, vectors represent them better. Lexical semantics — how words relate — covers relations like synonymy, similarity, and antonymy, and these are quite intuitive, not something to memorize. The marks here come from the math: a small numerical problem on cosine similarity or TF-IDF is the expected shape.
8.2.1 Why Vectors Represent Words
The intuition behind vector semantics: because of context words and because of vector representation, any word can be represented in a multi-dimensional vector space, and relations among words can then be captured mathematically. This makes similarity easy for machines. Word embedding means converting the textual word representation into a vector representation; they are called embeddings because the words are embedded in the vector space. If words are embedded in a vector space and plotted, words similar to each other will be embedded closer to each other in the vector space.
Intuition: the meaning of a word is defined by the company it keeps — the distributional hypothesis, that words appearing in similar contexts have similar meanings. The module builds on exactly this: a map of language where every word is a place, and places that appear in similar neighborhoods are drawn close together. "Dog" and "cat" live near each other because they both appear near "pet", "feed", and "walk"; "computer" lives far away, near "data" and "process". The map analogy is faithful: closeness on the map is semantic similarity. It breaks where humans differ from machines — idioms and metaphors do not sit neatly on a map — but as a first mental picture it carries the whole module.
There are mainly two families of word embeddings. The frequency-based approach counts occurrences in the corpus, computing term frequency and IDF vectors, and can also build co-occurrence vectors from words lying close to each other in the training corpus. The prediction-based approach learns embeddings by training a model to predict, and it is covered in detail through skip-gram negative sampling, with CBOW and GloVe as relatives.
The basic idea of representing words as vectors comes from a simple representation: a set of documents and a set of words, with numbers indicating how many times each word appears in each document. These numbers are the term frequencies. This matrix can represent a vector for a document or a vector for a word, and both representations are possible. Document vectors help understand which documents are similar to each other, which is useful in many applications including web search. Reading the same matrix row-wise gives each word in the training corpus a vector made of its term frequencies across documents, which helps understand which words are similar to each other or lie in the same semantic space.
A related representation is the co-occurrence matrix: take the matrix of all words and compute the frequency of words occurring close to each other within a plus and minus context window. This gives a vector representation of every word with respect to the other words in the training corpus. This is the same concept later used in skip-gram negative sampling.
8.2.2 Cosine Similarity
To compute the mathematical similarity among vectors, you cannot just subtract vectors and find a distance. The vector similarity measure is the dot product. But the dot product is not normalized by the size of the vectors, so the measure used is cosine similarity, where the dot product is divided by the size of the vectors. For two vectors and :
where is the dot product (multiply matching entries and add) and is the size (magnitude) of the vector. The verbal description from the recap: "you cannot just subtract it and find the distance, you need a vector similarity measure that is the dot product; dot product is not normalized by the size, and that is why we go for cosine similarity, where we divide by the size of the vector." Dividing by the size makes the score normalized, independent of the length of the document.
The dot product alone is a poor similarity measure because it rewards long vectors: a word like "the" occurs often, so its vector has big entries and a big magnitude, and its dot products are inflated by pure frequency, not by meaning. Dividing by both magnitudes removes that inflation and leaves the angle between the vectors — the direction of agreement — as the score. For non-negative count vectors the cosine ranges from 0 (perpendicular, no shared context) to 1 (same direction, same context); opposite directions give .
Worked example: cosine similarity between two word vectors. Let and .
- Dot product: .
- Magnitudes: , and .
- Cosine: , which corresponds to an angle of about between the vectors.
Sense-check: both vectors have the same magnitude, so the raw dot product (4) and the cosine (0.8) tell the same story here; the normalization only matters when magnitudes differ, which is the usual case with real word counts. A cosine of 0.8 is high — these two words share a lot of context.
A lesser cosine similarity value indicates that the two words are not similar to each other. If the value is close to one, the words are similar to each other and lie in the same semantic space. Students should be able to explain whatever output values they get — the exam asks for the calculation and the interpretation of the result, not just the number.
8.2.3 Term Frequency and Inverse Document Frequency
Term frequency is the occurrence of each term in each document, meaning the count of how many times a term occurs in a document. Two refinements are applied. First, since the raw counts can be very large, a logarithm squashes the values. Second, one is added to avoid zeros, so that a term occurring in a document does not get a zero TF value. Following the Jurafsky and Martin convention:
where is the raw count of term in document and is the log-squashed term frequency weight. The plus-one applies only when the term occurs: for a term that does not appear in the document, . Some texts write the squash as , which is the same idea in slightly different form — it also keeps every occurring term above zero and compresses large counts. On the exam, use the form the question specifies; the standard form in the lecture is .
The log matters because raw counts are skewed: a word with 1000 occurrences and a word with 10 occurrences differ by a factor of 100 in raw count but only by a factor of about 3 after the log squash. That stops a very frequent word from dominating the vector by sheer count.
A normalized variant also exists: the raw count divided by the total number of words in the document. This is the normalization used when computing cosine similarity. Advanced normalized versions like BM25 exist but are not part of this curriculum.
Document frequency is how many documents contain the term. This differs from collection frequency, which counts every occurrence of the word across every document. Document frequency only checks whether the term appears in a document at all: out of 100 documents, one of them may have the term Romeo, and out of 100 documents, 31 of them may have the term action — those are document frequency counts, presence only, not multiplicity.
Inverse document frequency captures the rarity of the term. Term frequency alone cannot capture rarity: frequent terms like "the" get more weight in a document, which is not useful. If a document is about Sachin Tendulkar, the word Sachin Tendulkar may not occur frequently, and words like good, player, and cricket may appear more often — but the document should give more weight to Sachin Tendulkar. That is what inverse document frequency captures. The formula:
where is the total number of documents and is the document frequency of term . If a term occurs in fewer documents, the term is more important, so the inverse is taken. The inverse is taken with respect to the total number of documents. The log base 10 is for squashing the values.
Worked example: computing IDF in a 37-document corpus. In the corpus of 37 documents, the words good and sweet are very common and occur across all 37 documents, so their IDF is . The word Romeo occurs in only one document, so its IDF is .
- — appearing everywhere earns no credit.
- — appearing in one document makes it a sharp, distinctive word.
The same pattern at a different scale: with documents, a word in 5 documents gets , while a word in all 100 documents gets .
Sense-check: the rarer the term, the higher the IDF — log base 10 of a larger ratio is a larger number, and a term that appears in every document hits the minimum, zero. The values are all non-negative and the zero case matches the intuition that common words add no information.
The full TF-IDF weight combines both:
The combination rewards words that are frequent locally (high TF) but rare globally (high IDF) — exactly the words that define what a document is about. A worked example computed TF-IDF values from the raw values, producing decimal values; the resulting vector for the word battle was shown alongside vectors for other words. The log also helps squash the values to decimal magnitudes.
Worked example: the TF-IDF vector for "battle" over four documents. The documents are As You Like It, Twelfth Night, Julius Caesar, and Henry V, with raw counts for battle . The word appears in 3 of the 4 documents, so and , giving .
- Document 1 (count 1): .
- Document 2 (count 0): the term does not occur, so the weight is .
- Document 3 (count 7): .
- Document 4 (count 13): .
The battle vector is : zero in the play where battle never appears, largest in Henry V, a historical war play.
Sense-check: raw counts 1, 7, 13 differ by a factor of 13, but the TF-IDF weights differ by only a factor of about 2 — the log squash has compressed them, and the vector is now comparable across documents of different lengths.
8.2.4 Sparse Versus Dense Representations
Scope and pitfall of the frequency-based approach: the frequency-based approach has a sparsity problem: many of the values can be zero. Also, the vector size for each word is as large as the vocabulary size. If the training corpus has a unique vocabulary size of 100,000 words, every word vector has size 100,000, so computing cosine similarity or extracting vectors becomes tedious. Most entries of those vectors are zero, because most words never co-occur with most other words — the matrix is mostly empty. The frequency-based approach is still used, though: later coursework covers the hybrid search approach, combining the sparse representation (TF-IDF frequencies) with the denser representation (contextual word embeddings or SGNS).
The advantage of the frequency-based approach is that it is easy, it does not take much computation, and it is faster to compute. The disadvantages are the many zeros and the long vector length for each word.
The alternative is a dense vector representation with short vector length for each word. Dense models are parameterized by their embedding dimension: GPT-4 has token embeddings of 1024 dimensions, while GPT-3 and earlier models had 768 dimensions. Some small language models have 300 dimensions, and Andrew Ng recommends 300 as a practical dimension. Depending on the model size, the dimensions of the vectors vary for each of the input words, also called tokens. (One slide in the recap attributes 1024 dimensions to GPT-4, and a later remark extends that to newer models; the numbers stand as stated — the takeaway is the ladder: about 300 for small models, 768 for the GPT-3 era, 1024 for the newer generation.)
| Dimension | Sparse (frequency-based) | Dense (prediction-based) |
|---|---|---|
| Vector length | Vocabulary size (100,000+) | Fixed small number (300–1024) |
| Values | Mostly zeros, a few counts | Mostly non-zero real numbers |
| How they are made | Counting (TF, IDF, co-occurrence) | Learned by training a predictor |
| Cost | Cheap and fast to build | Expensive to train, but compact to store |
| Similarity quality | Raw, inflated by frequency unless weighted | Semantic similarity baked in |
Dense vectors were built to fix exactly the two complaints above: no more zeros to store, and short enough vectors that similarity is cheap to compute.
8.2.5 Student Questions and Answers
Q: A student notes that some sources define term frequency as the count of how many times the term appears in a document, while others divide that count by the total number of words in the document.
A: That division is the normalization. The normalized form is what is used when computing cosine similarity. Advanced formulas like BM25 are further normalized versions, but BM25 is not in the current NLP curriculum; the formulas given in Jurafsky are the ones to follow.
Q: A student asks whether natural log or base ten should be used for TF-IDF.
A: If the exam question specifies a formula, use whatever formula is mentioned: if it is natural logarithm, use that; if it is log base two, use that; if log base ten, use that. Otherwise log to the base ten is the most convenient and the most popular. At web scale the values are very large, and log base ten squashes the values further. For toy data sets, people also use natural log or log base two, because the numbers are smaller. Log base ten is also easier to compute.
Q: A student complains that remembering different log bases across topics is confusing: TF-IDF uses log base ten while CBOW uses natural log.
A: It is easier to remember than it seems — it is just the base part. For TF and IDF, log to the base ten is suggested because it is easier for computation. All three bases are used in practice, but log base ten is the most popular at web scale because values are large. Use whatever the question specifies, and state the formula used.
Q: A student asks about a later course, where a document corpus will be presented and the term frequency must be found.
A: Yes, there might be sample sentences treated as documents, and then the term frequency and term count are computed over them. The same counting skills from this module carry straight over.
8.2.6 Exam Notes
Exam note: expect a small numerical problem on either cosine similarity or TF-IDF. Cosine similarity is simple: calculate the dot product between the vectors and divide by their respective sizes, then explain what the output values mean. The mathematical problem on vector semantics covers sparse vectors, TF, IDF, and cosine similarity, worth around four or five marks. For TF-IDF calculations use log base ten, unless the question specifies another base, in which case use that formula.
Exam note: write the formulas you use into the paper. The distinction between document frequency and collection frequency is a favorite conceptual question, and the interpretation of cosine values ("close to one means similar") earns the explanation marks.
Recap and bridge. Sparse vectors turn words into positions in a huge, mostly-empty space, and TF-IDF weights make the positions meaningful by rewarding rare, distinctive words; cosine similarity then measures the angle between any two positions. The catch is scale — 100,000 dimensions per word. The next module throws out the zeros and learns short, dense vectors instead, and the algorithm it uses is skip-gram negative sampling.
8.3 Word2Vec and Skip-Gram with Negative Sampling
Word embedding is the slightly complex topic of the pre-mid-semester syllabus. The sparse vectors have the challenges above, so the course moves to denser vector representations, and the detailed mathematical problem solved in class is skip-gram negative sampling (SGNS). A similar approach is used for CBOW, and GloVe was discussed briefly. Contextual word embeddings involve mathematical problems too, but those belong to the post-mid-semester part.
8.3.1 Self-Supervision and One-Hot Encoding
Word2Vec algorithms are self-supervised: training data is needed, but no human labels are needed for that training data. The SGNS algorithm uses the data itself to automatically create positive and negative samples through self-supervision. The labels the model trains against come from the corpus structure, not from a human annotator: if two words appear next to each other in real text, that appearance is itself the label.
Before the embeddings come the one-hot encoding of words. A one-hot vector is equal to the size of the vocabulary: every word in the one-hot representation is a vector the size of the unique vocabulary, with a 1 at the position where that word occurs in the unique vocabulary and 0 everywhere else. One-hot encoding is not suitable for finding semantic similarity, but it serves as a base: multiply it with the feature-dimension matrix to get the vector representation for each word in the dimensions of the features. The names of the features are immaterial — they are learned by the deep learning algorithms. What matters is the number of features: Andrew Ng recommends 300 dimensions, GPT-2 and GPT-3 have 768, and newer models have 1024 dimensions for each of these token IDs.
Intuition — the lookup trick: multiplying a one-hot vector by a weight matrix does not really compute anything: it selects a row. If the word is word number 2, its one-hot vector is , and multiplying by returns the second row of exactly, because every other row is multiplied by a zero. That is why the rows of the weight matrix are the word embeddings — training the weights is training the embeddings, and the embedding of a word is just the row that word's one-hot vector picks out.
Multiplying the one-hot vector by the weight matrix automatically reduces the dimension of the word embedding. In the in-class example the one-hot had dimension 1 by 4 (4 columns), the weight matrix was 4 by 5, and the resulting vector was 1 by 5:
More generally, if the unique vocabulary size is 50,000, the sparse vector is , and a weight matrix of reduces this vector to . That is the advantage: the sparse vectors are reduced into the denser vector representation.
8.3.2 How SGNS Builds Its Training Data
The first step of SGNS is to create the self-supervised data. Pick a target word, pick the context window of plus minus 5 words, and try to predict whether each word is a context word for the given target or an out-of-context word. This algorithm comes from a very innovative and important research paper by Google. The in-class example took apricot as the target with a plus minus 2 word context window: the words inside that window are positive context words, and all words lying outside the context window are considered negative context words. This is how positive examples and corresponding negative examples are generated.
Careful — the self-supervised caveat: typically there are proportionately negative examples for each positive example; the in-class example considered 2 negative examples for each positive. More negative samples help the algorithm distinguish well, but there is a caveat: some words chosen as negatives could actually also be context words, so care must be taken when making the choice of these self-supervised examples. Randomly picking a negative word does not guarantee it never appears near the target in other sentences — it is simply treated as negative for this training pair.
Once the examples exist, the problem is posed as a classification problem. The final output classification — whether a word is context or not — is not the interest. The interest is in learning the weights of the in-between features, the weight matrix. The classification task is scaffolding: it forces the weights to absorb the useful statistics of co-occurrence, and when training is done, the weights are the embeddings.
8.3.3 Probabilities, Loss, and Gradient Updates
The classifier is simple logistic regression treated as binary classification: context words are positive, out-of-context words are negative. For similarity, a sigmoid function is needed: similarity alone is not enough, so the sigmoid turns the dot product into probability values. Giving a probability of being a context word makes this a probabilistic model, which is more useful in real-world applications than a deterministic model. The standard sigmoid from logistic regression:
where is the context word embedding and is the target word embedding; is their dot product, a scalar. So the probability that is a positive context word of target is:
The probability for a negative context word is one minus the positive probability:
The middle step uses the sigmoid symmetry , which is the single most important identity for this topic: the negative case runs the same dot product through the sigmoid with a plus sign inside. The dot product is the same; the sign is only added inside the sigmoid.
Standard gradient descent learns the word embeddings: each word in the corpus gets both a target word embedding and a context word embedding, because a word can be a target in one pair and a context for other words. The final word embedding for a word is a combination of its target word embedding and its context word embedding.
The training objective is to maximize the similarity (probability) between target and positive context, and minimize the similarity between the word and negative context words. The loss function takes a log of the probabilities, because the log converts a product into a sum, which is easier to calculate; and because it is a loss to minimize, there is a negative sign. This is cross entropy, with negative examples:
Substituting the sigmoid probabilities mechanically gives the expanded form:
To update the embeddings, take the partial derivatives of this loss with respect to the three variables — the positive context embedding, the negative context embeddings, and the target embedding. These are like the three weights in the gradient descent algorithm. The derivation itself does not need to be memorized; only the final formulas matter. For those who want to see where they come from, the two building blocks are and (the second follows from the symmetry identity), with behind both. For the positive context, the derivative is the predicted minus the actual, where the actual for positive is one, which is why the formula has the minus one:
For each negative context word, the actual is zero:
For the target vector, both positive and negative contributions appear, since the target appears in both parts of the loss:
Note the sign convention: in the negative terms the sigmoid is computed with the positive sign inside, , because the probability of a negative sample is one minus the positive probability. The dot product itself is the same; the sign is only added inside the sigmoid. The derivative forms above match the standard treatment in Jurafsky and Martin, chapter 6.
For the positive term, read the factor as predicted minus actual: the actual target for a positive pair is 1, so the factor is , which is why the formula carries the minus one. For a negative pair the actual target is 0, and the factor is simply .
The weight update uses gradient descent with learning rate :
In practice the algorithm loops over many iterations and many positive examples; the in-class demonstration ran only one iteration, and the exam likewise asks for a single iteration.
8.3.4 Worked Example: Learning the Embedding for "net"
The full worked example follows one iteration of the update. The weights start at some random values. The initialization should be random, non-zero, close to zero, lying between and , and ideally not very large. The context word embeddings are initialized the same way.
Setup: the target word is net. Its one-hot vector multiplied by the weight matrix gives the target word embedding . The positive context word is stark (class 1), and the negative context words are pimples, zebra, and idiot (class 0), so . The learning rate is .
An earlier slide showed the prediction check: for a positive pair the computed sigmoid probability was 0.55 while the actual target is 1, so there is an error of . The derivative formula contains the minus one, so this can be read as the predicted minus the actual. The goal of the update is to drive this error as close to zero as possible; whether it is negative or positive is not critical, what matters is closeness to zero.
To run the numbers, take the following 4-dimensional starting vectors (the in-class example used 5 features; the arithmetic is identical at any dimension):
Step 1 — compute the positive probability. Take the dot product of the positive context vector with the target vector, . The dot product is a scalar value. Then take the sigmoid: , which gives the probability of the word being a positive context word.
The model is not confident: it gives 0.55 when the target is 1.
Step 2 — compute the negative probabilities. For each negative context word, take the same dot product (same dot product, no sign added yet), then compute the negative probability as one minus the positive sigmoid, :
The model is badly wrong here: it is 94% sure pimples is a context word of net, when the target is 0. That large mistake will produce the largest push. The remaining two negatives:
Step 3 — build the derivative table. The table has one column for the positive term, three sets of columns for the three negative terms, and a last column for the sum. The positive column is multiplied by the positive context vector. Each negative column set is multiplied by that negative context vector. The last column is the component-wise vector addition of these four scaled vectors, which gives .
| Word | Scalar factor | Context vector | Scaled contribution to |
|---|---|---|---|
| stark (positive) | |||
| pimples (negative) | |||
| zebra (negative) | |||
| idiot (negative) | |||
| Sum = | [3.89, 0.24, -0.12, 0.36] |
Each row is a vector, so the last column is a vector addition: adding the four scaled vectors component-wise gives the derivative . The pimples row dominates because the model was most confident about the wrong answer for it.
Step 4 — apply the update. Multiply the computed derivative vector by the learning rate , then combine it with the original target vector for net, producing the updated target word embedding :
Sense-check. The first component of dropped from 0.5 to 0.31, moving the net embedding away from pimples, whose first component is a large 5.28 — the model was confident pimples was a context word, so the update pushes the target away from it. The positive word stark gets a smaller pull in the opposite direction. One iteration shrinks the mistakes; it does not remove them, which is why training repeats over the corpus many times.
The recap recommends showing this computation in a table step by step in the exam: the table means nothing needs recomputing, each value just gets substituted into the formulas. In the full algorithm the context vectors are updated with their own gradients as well; the in-class procedure and the exam question focus on the target update, which is the single update shown above.
8.3.5 CBOW and GloVe at a Glance
CBOW uses a similar self-supervised approach to SGNS, and there will be no mathematical problems on CBOW — it is conceptual only. CBOW runs the skip-gram idea in the opposite direction: instead of predicting the context words from the target, it averages (or sums) the context word vectors and predicts the target word. GloVe was discussed briefly: it is conceptual, and at most a very minor problem could appear. Where SGNS learns from local context windows, GloVe learns from the global co-occurrence statistics of the whole corpus, fitting vectors so that ratios of co-occurrence probabilities are captured.
| Model | What it predicts | What it counts | Exam status |
|---|---|---|---|
| Skip-gram (SGNS) | Context words from a target word | Local window pairs, with negative samples | Full mathematical problem |
| CBOW | Target word from context words | Local window pairs, averaged context | Conceptual only |
| GloVe | Vectors fit to co-occurrence ratios | Global word-word co-occurrence counts | Conceptual only, at most a very minor problem |
Reviewing the CBOW and GloVe walkthroughs is enough for the exam; the marks and the math sit with SGNS.
8.3.6 Student Questions and Answers
Q: A student asks whether the log in the loss function is to the base ten.
A: No log is needed at this stage of the computation, because the worked computation goes directly to the derivative calculation. The only functions needed are the sigmoid for the positive pair and one minus the sigmoid for the negative pair.
Q: A student asks whether the negative context word should use the same formula as the positive one, as per the derivation.
A: No. Because it is a binary class, the negative cannot use the same formula. The negative probability is one minus the probability of the positive. When the derivation is carried out, the negative form becomes , the sign inside the sigmoid becomes positive. The formula on the slide is correct, and it matches Jurafsky chapter 6.
Q: A student points out that in the figure, the sigmoid for the negative sample pimples shows a different value (0.553) from the values in the table.
A: The dot product is the same; the sign is only added when computing the sigmoid. The dot product has no sign added, and the sign appears only inside the sigmoid function. The figure and the table come from different examples, so their values differ — do not try to reconcile two numbers that were computed from different starting vectors.
Q: A student asks whether, if the negative formula is , the target for the negative sample should become one instead of zero when calculating the error.
A: No. The formula varying means the probability is one minus the positive probability, because it is the opposite probability. If the same formula were used for both, there would be no way to differentiate between positive and negative. The probability of a negative sample is one minus the probability of a positive sample, the standard logistic regression setup. The targets are independent of the prediction formula: the actual values are fixed — context words have target one, out-of-context words have target zero.
Q: A student asks whether the error for the negative contexts should still be minus.
A: Do not confuse the target and the predicted. The prediction probability is given by the sigmoid , and for the negative words the prediction is one minus the positive probability. That is the predicted value, . The other one is the actual value, the target. The two stay separate: the predicted value comes from the formula, the target is fixed by the class of the sample.
Q: A student asks how the first column and the next three sets of columns in the table combine into the last column.
A: The first column is the value (the positive term) multiplied by the positive context vector. Then for each negative word, the sigmoid value for that negative is multiplied by that negative's context vector — for example 0.94 times the pimples vector gives the contribution for pimples, and the same is done for zebra and for the third negative. These are all vectors, so the last column is a vector addition: adding the four scaled vectors component-wise gives the derivative .
Q: A student asks whether one or two decimal places are acceptable in the exam computations.
A: One or two decimals is fine. Calculation is not the purpose; understanding of the concept is the purpose. The examiner wants to see the correct procedure — the formula applied to the right values — not machine-precision arithmetic.
Q: A student asks whether any marks are left in this module apart from the skip-gram problem.
A: It is not necessary that an SGNS problem will be given; there might be an application-oriented question as well. The module can be tested through a scenario rather than through computation, so prepare the conceptual side too.
8.3.7 Exam Notes
Exam note: expect a mathematical problem on word embedding, especially skip-gram negative sampling, worth around four marks. Only a single iteration will be asked in the exam, and the values will not be very complicated — simple values and fewer negative examples than the worked table. Derivation of the derivative formulas is not required; the formulas will most likely be given, and only one or two formulas need to be remembered. The two formulas worth remembering are the positive probability (the standard sigmoid) and the negative probability (one minus the sigmoid), plus the derivative of the loss with respect to the target word. Show the work in a table step by step, it makes the computation easy and it is easy to grade. There will be no mathematical problems on CBOW; CBOW and GloVe are conceptual only, with at most a very minor GloVe question.
Recap and bridge. SGNS turns co-occurrence into a binary classification game: pull the target toward its real context words and push it away from sampled negatives, one gradient-descent step at a time. The table procedure above is the whole algorithm in miniature. The next module switches from learning word meaning to scoring whole word sequences — statistical language modeling with n-grams, smoothing, and perplexity.
8.4 Statistical Language Modeling: N-Grams, Smoothing, and Perplexity
Language modeling is a broad topic with many real-world applications, and it is not that difficult a concept. The exam problem on this module is not necessarily a complete four-mark problem everywhere; it is also possible to get a combination of a mathematical problem and an application-oriented question. The core skill to practice is counting from a corpus and substituting values into the formulas.
8.4.1 The Language Modeling Problem
Language modeling is predicting the next set of words given a set of words. To model any language means to model how sentences are generated; communication is generating a well-formed sentence, and language modeling does that for you. It does so using statistical techniques like the probabilistic n-gram, or using neural language modeling with transformers and LLMs.
Intuition: a language model is a fluent reader with a strong sense of what usually comes next — like the word suggestions on a phone keyboard. You type "See you", and it offers "tomorrow", "soon", "later". It is ranking next words by how likely each one is after what was typed. That ranking is a language model at work. The same idea sits behind machine translation choosing "high winds tonight" over "large winds tonight", and behind spelling correction picking "minutes" over "minuets".
To predict a sequence of words, the standard Bayes rule computes the joint probability of the sequence. Because a sequence of words follows one after another, the joint probability of all the words is what is wanted. The chain rule of probability expands it:
Each factor is one word's probability given all the words before it: the chance of the first word, times the chance of the second given the first, and so on. This is exact probability — no approximation yet.
The challenge: to compute these probabilities in the training data, that much data is needed. Longer context sentences do not repeat, so at most bigram or trigram values exist in a corpus; 5-gram or 6-gram values will not be available. A four-word history like "its water is so" is already rare enough that its counts are unreliable or zero, and the chain rule demands exactly those rare counts. The solution is the Markov assumption: the current word only depends on the previous one word or the previous two words. Depending on the previous one word gives the bigram probability; depending on the previous two words gives the trigram probability:
The approximation trades a little accuracy for counts we can actually measure: the bigram only needs the pair to have appeared, which common pairs do.
The unigram is also a possibility but it captures no context at all, so unigram is not preferred unless no bigram or trigram values are available — only then does one fall back to unigram probability. A unigram model treats a sentence like a bag of words: .
For computing sequence probabilities, log values are generally used instead of probabilities, for faster computation. When computing the probability of a complete sequence, the log values are multiplied into a sum. This matters in practice because the raw product of many small probabilities underflows to zero on a computer: replaces a shrinking product with a stable sum of negative numbers. The Google Ngram corpus makes such counts readily available.
8.4.2 Counting Bigrams and Trigrams
Given a corpus, the bigram and trigram probabilities are computed from a count table. The table has the corpus frequencies — the unigram counts, how many times each word occurs in the corpus — alongside the bigram counts, how many times two words occur together, the second word coming after the first. For example, the count for want coming after want is 0. Each bigram probability is the count of the pair divided by the unigram count of the first word:
where is the bigram count and is the unigram count of the previous word. This is the maximum likelihood estimate: "count the pair, count the first word, divide".
Worked example: bigram probabilities from a count table. In the Berkeley Restaurant Project corpus, the unigram counts include , , and . Selected bigram counts: , , , , and .
- — a third of the time "i" is followed by "want".
- — two thirds of the time "want" is followed by "to", which is the model learning real grammar from counts.
- .
- — the pair never appears, so the raw probability is exactly zero.
The convention for the table: the rows hold the first word (the word already present), and the columns hold the next word. This is a standard convention, true even for the emission and transition matrices in POS tagging.
Sense-check: the probabilities of all words after a given first word add to 1 — for example fills out the whole row. The zero for "want want" is exactly the problem the next section fixes.
Zero probability is a problem, and to avoid zero probabilities Laplace smoothing is applied. A single zero in the product makes the whole sentence probability zero: . The zero is not "very unlikely", it is "cannot happen", which is almost never true for a sensible phrase — and it also makes perplexity infinite, so evaluation breaks too.
Sentence probability: once the individual bigram probabilities exist, the probability of any sentence is computed by multiplying all of these probabilities together, giving the overall probability for that particular sentence. Start and end tags: if the question includes the start and end of the sentence, include them in the counts; if the question does not mention them, make an assumption and write it out. Read the question properly before answering, and write any assumption explicitly — otherwise an ambiguous answer cannot earn marks. For example, a bigram model scores "I want english food" as , where and mark the start and end of the sentence.
8.4.3 Laplace Smoothing, Interpolation, and Backoff
Laplace smoothing (add-one smoothing) adds one in the numerator and the vocabulary size in the denominator:
where is the vocabulary size. If three sentences are given, the unique vocabulary across those sentences gives — just count the unique words. If the question asks to perform Laplace smoothing, or if there is a zero anywhere, add the one in the numerator and the vocabulary size in the denominator to compute the probabilities.
Why add below? Because we added 1 to each of the possible next words, the denominator must grow by so that every row still sums to 1. It gives every unseen pair a small head start of one imaginary sighting: nothing keeps a zero probability, common pairs lose a little mass, and rare pairs gain a little.
Worked example: add-one smoothing on Berkeley bigrams. With vocabulary size :
- — down from the raw 0.33.
- — the zero is gone.
- .
Sense-check: the common pair lost a big chunk of its probability (0.33 to 0.21) while the unseen pair lifted off the floor. That is the price of killing zeros, and it shows why add-one is called a blunt instrument: for the pair "i want" the real count is 827, and the reconstituted count implied by the smoothed probability is about — roughly 300 real sightings were given away to unseen pairs.
Laplace smoothing has a drawback: it manipulates the counts. When the joint counts are substituted into the formula, the counts get changed because of the added one and the vocabulary size, and the counts change substantially, which is not desirable in some applications. With a vocabulary of tens of thousands of words, the swamps the real counts.
The workarounds that avoid manipulating the counts are interpolation and backoff. In interpolation, lambda values weight the three levels, giving more priority to the trigram, less to the bigram, and less to the unigram:
where are the interpolation weights. If the exam gives the lambda values, substitute them to calculate the probability; otherwise make an assumption. The lambda values can also be learned using validation data. By the standard convention the weights sum to one, , which keeps the blended estimate a proper probability; if the lecture materials ever present weights that do not sum to one, that is a simplified example, and the sum-to-one form is the one used in practice.
Worked example: interpolated trigram probability. Suppose the given values are , , , with weights , , . Then:
Sense-check: the trigram gets the biggest weight and its value, 0.50, dominates the blend; the unigram barely matters. If the trigram count had been unreliable, the weight structure would lean on the bigram instead — which is the whole point of mixing the three levels.
Backoff is a similar concept to interpolation but without the combination: use the trigram if it is available; if the trigram is not available, go for the bigram; if the bigram is not available, go for the unigram. Interpolation always takes a combination of trigram, bigram, and unigram; backoff falls down the hierarchy only when a level is missing. Think of asking a local for a restaurant on your exact street: if they know one, great (trigram); if not, they suggest the neighborhood (bigram); if even that is blank, they name a city-wide favorite (unigram).
| Dimension | Interpolation | Backoff |
|---|---|---|
| What it does | Always blends trigram + bigram + unigram | Uses trigram; steps down only when needed |
| Counts manipulated? | No | No |
| Weights | values that sum to one | Fixed discounts as you step down |
| Typical result | Usually performs better | Simpler, cheaper |
In practice, most real-world language modeling problems use interpolation, not Laplace smoothing. Laplace smoothing is used for certain applications like classification; otherwise, today's systems use interpolation or transformers.
8.4.4 Perplexity
Perplexity is an evaluation measure for language models, used not only for n-gram language modeling but also for neural language modeling, and even for ChatGPT and the LLM transformers, where research papers report it. It is an intrinsic evaluation measure because it measures the algorithm level; extrinsic evaluation is black-box, testing the whole system's performance using accuracy, precision, recall, and so on. The extrinsic test is the honest gold standard — put the model in the real task and measure task accuracy — but it is slow; perplexity is the fast stand-in that scores the model directly on test text.
The intuition behind perplexity: raw probability values may not indicate how good the system is, but a single number is easy to compare. Lower perplexity is better; the model should aim for lower perplexity. The formula takes the sequence probability computed from the language model and raises it to the inverse of the sequence length, the Nth root of the inverse of the probabilities:
where is the sequence probability computed from the language model, and is the number of words in the sequence. The minus sign in the exponent turns "high probability" into "low perplexity", and the averages over the length so long and short test sets are comparable.
The cleanest reading of the number: perplexity is the effective number of equally likely choices the model is torn between at each step — the branching factor. A model that gives every digit 0–9 probability has perplexity exactly 10; a sharp model that is usually sure has perplexity near 2.
Worked example: perplexity of 4.47. A bigram model assigns the two-word sequence a probability of , so . Then:
In the worked example, taking the Nth root gave the value 4.47, indicating that the model is uncertain about choosing among 5 words — as if it were picking the next token uniformly among roughly five options. A smaller perplexity means the model is more certain about which word should be the next token.
Sense-check: the inverse-root form makes the interpretation automatic — perplexity of 4.47 means the model behaves like a uniform chooser over about 4.5 options per word. A perfect uniform model over 5 words scores 5; our model is slightly sharper than that, and far sharper than a unigram model over a huge vocabulary.
Real numbers confirm the story: on the Wall Street Journal test set, a unigram model scores perplexity 962, a bigram 170, and a trigram 109 — each extra word of context removes most of the uncertainty, and the drop from 962 to 109 is the value of context written as one number.
Pitfalls: a single zero probability makes perplexity infinite — you cannot compute perplexity from unsmoothed counts, so smooth first (interpolation in practice). Perplexity is only comparable across models that use the same test set and the same vocabulary. And a better perplexity does not always mean a better real task: when the stakes are high, trust the extrinsic test.
8.4.5 Student Questions and Answers
Q: A student asks whether the starting token also counts in the bigram table.
A: If the start and end tags are given in the question, include them. If the question states "include the start and stop", then they must be used. If it is not mentioned, make an assumption and write it out. Read the question properly before answering, and write any assumption explicitly — otherwise an ambiguous answer cannot earn marks.
Q: A student asks which probability value to use when calculating perplexity from three sentences — the value from the Markov assumption or the value after smoothing.
A: Usually perplexity problems are given with a single sentence, similar to the worked example, not a difficult one with three sentences. The probability values are the bigram or trigram values computed from the model. To avoid zeros, use the smoothed values. In practice, people go for interpolation, not Laplace smoothing. Laplace smoothing is used for certain applications like classification, but most real-world language modeling problems use interpolation, and today they use transformers.
Q: A student asks about the table convention: whether the rows are always the next given words and the columns the already-present words.
A: The rows hold the word already present — the first word — and the columns hold the next word. It will generally be mentioned in the exam; if it is not mentioned, make an assumption. But this is the standard convention, and it is the same convention for the emission and transition matrices in POS tagging.
8.4.6 Exam Notes
Exam note: expect a small problem on either n-gram computation, n-gram language modeling, or a Laplace smoothing kind of question. Also possible: what interpolation is and how to calculate it, or a mathematical problem on perplexity. The n-gram module carries a four-mark question, possibly combined with an application-oriented question. If the question specifies including start and end tags, use them; otherwise write assumptions out. For Laplace smoothing, count the unique vocabulary from the given sentences to get , or use the given list. Conceptual or application-oriented questions on the theory are possible, so review the module theory as well.
Recap and bridge. An n-gram model scores a sentence as a product of short-horizon next-word probabilities; smoothing and interpolation rescue the zeros; perplexity turns the model's uncertainty into one comparable number. The next module swaps the count table for a neural network — and softmax takes over from the raw counts at the output side.
8.5 Neural Language Models and Introduction to LLMs
Neural language modeling is applying neural network algorithms to the language modeling problem. Most of the textbook content on this module covers the neural networks part first, because the neural networks must be known before they can be applied to language modeling. The deep neural networks course already covers backpropagation, so this exam will not have a direct backpropagation-through-time calculation. The examinable shape of this module is architectural: how the network is built, what activation ends the output layer, and why the neural model beats the n-gram model on unseen words.
8.5.1 From Perceptrons to Multi-Layer Networks
A neural network is built from perceptrons. A perceptron is the simplest unit: it adds up weighted inputs plus a bias, fires 1 if the sum is above zero, and 0 otherwise. A single neuron cannot solve certain nonlinear functions like XOR, which is why a network with multiple perceptrons is needed — the XOR problem needs 2 perceptrons, and that is why multi-layer perceptron networks exist.
The XOR problem is worth understanding because it explains why depth exists: XOR should fire when two inputs differ, so the yes-cases (0,1) and (1,0) sit on opposite corners of the input square, and the no-cases on the other two corners. No single straight line can separate them, so one perceptron — one straight cut — always fails. Two perceptrons arranged in a hidden layer can do it: one hidden unit learns "at least one input is on", the other learns "both inputs are on", and the output combines them into "at least one on, but not both".
A network has an input layer, a hidden layer, and an output layer. If the output is logistic binary classification, the output side uses a sigmoid. Forward propagation is the simple chain of sum of products and activation function: multiply the weights, then apply the sigmoid or any activation function, get the output; again sum of products, apply the activation, and so on. The bias is replaced with to make the equations simpler: a fake input fixed at 1 with its own weight plays the exact role of the bias, so becomes one clean dot product.
For the language modeling problem, the network takes word embeddings as inputs — the token IDs are converted into word embeddings and given as input, because for any NLP application the input is always word embeddings, never raw tokens. Raw token IDs are just indices with no meaning attached; the embedding vector carries the meaning, and the network can generalize between similar words.
8.5.2 Softmax for Multi-Class Next-Word Prediction
Language modeling is a multi-class problem: the idea is to predict the next word from multiple given words, so the prediction is from multiple words, not just two. So the output side always uses softmax for language modeling. For sentiment analysis, which is usually a binary class problem, the sigmoid at the output side is used. The rule of thumb: two classes — sigmoid; many classes — softmax.
The softmax normalizes the output scores into a probability distribution over the vocabulary:
where is the output score for word , and the sum runs over all words in the vocabulary. It works in two moves: raise to each score, which makes every score positive and rewards large scores; then divide by the total, so the pieces add to 1. A big score gets a big share of the probability.
Worked example: softmax over a five-word vocabulary. A network produces the raw scores for five candidate next words.
- Step 1 — exponentiate: , , , , .
- Step 2 — sum: .
- Step 3 — divide: , , , , .
The probabilities are and they add to 1.
Sense-check: the highest score (2.0) takes more than half the probability mass, and the negative score gets a tiny but nonzero share — softmax never outputs exactly zero, which keeps every word in the race. Sum-check: .
Worked example: building the next-word network with four hidden nodes. A possible exam question asks how you would build the network that predicts the next word, given four hidden nodes. The design: take a context of the previous words, convert each token ID into its embedding via the embedding matrix , join the context embeddings into one input vector , pass it through the hidden layer with four nodes, then through a softmax over the vocabulary.
- Input: three context words, each embedded to dimensions, joined into .
- Hidden layer: weight matrix and bias , giving with four hidden nodes and an activation like ReLU.
- Output layer: weight matrix turns the four hidden values into scores, , one per vocabulary word.
- Softmax: turns the scores into the probability of each word being next.
Sense-check: every layer shape follows from the layer before it — the hidden layer maps 6 inputs to 4 nodes, the output layer maps 4 nodes to vocabulary scores. That is a network-definition question, not a backpropagation computation: state the layers, the shapes, and the activations, and the answer is complete.
A possible exam question: for building the language model that predicts the next word, explain how the neural network would be built given, say, four hidden nodes. That is a network-definition question, not a backpropagation computation.
8.5.3 Sentence Embeddings and the Advantages of Neural Models
Beyond word embeddings, the module covers sentence embeddings: combine the word vectors using the maximum of elements or the mean of elements to get a single vector for the sentence. Texts vary in length, but a feedforward network wants a fixed-size input, and pooling collapses any number of word vectors into one fixed-size vector.
Worked example: pooling three word vectors into one sentence vector. A three-word text has word vectors , , .
- Mean pooling: for the first dimension, for the second, giving .
- Max pooling: and , giving .
Sense-check: both methods produce one 2-dimensional vector regardless of sentence length — a ten-word text would also collapse to a 2-dimensional vector. The trade-off: mean pooling smooths everything together, max pooling keeps the strongest signal per dimension, and both throw away word order.
The loss function was also covered, but there will be no problems on backpropagation through time, which is not a focus of this course — the focus is how the feed-forward network is applied for neural language modeling.
The pros and cons of neural language models are simple to understand. The major advantage is the word embeddings: for unseen words, the neural model can still predict, mainly because of the word embeddings, whereas the n-gram language models work with the actual words and cannot predict unseen words. An n-gram model treats "dog" and "cat" as unrelated symbols; if training text only has "the cat gets fed", a bigram model cannot predict anything after "the dog gets". The neural model sees that dog sits near cat in embedding space and reuses the cat pattern to predict "fed". That sharing is the key exam point.
| Dimension | N-gram language model | Neural language model |
|---|---|---|
| Context used | Short (last one or two words) | Longer contexts, embeddings as input |
| Similar words | Treated as unrelated | Shared through embeddings |
| Unseen words | Cannot predict them | Can still predict, via embeddings |
| Cost | Fast, cheap, light | Slower, needs more data and compute |
| Best for | Small, simple tasks | Large, rich tasks |
When neural language models are mentioned, it means large language models or small language models: LLMs use the same concept as neural language models, though they use the transformer architecture instead of the simple feed-forward network — and the transformer is ultimately neural networks only.
8.5.4 Large Language Models, Fine-Tuning, and Prompt Engineering
Large language models are language models with a large number of parameters, trained on a large set of training data. They could be pre-trained models, and then fine-tuned for specific applications: if a model is wanted for a specific task or specific domain, it is retrained on that particular data set. Many models are openly available on Hugging Face. LLMs are used everywhere today.
Intuition: an LLM is the same next-word predictor from earlier in the course, grown enormous. Same core job — given the text so far, guess what comes next — but with vast data and size, that single skill turns into something that looks like broad language ability. Fine-tuning is the transfer-learning step: start from a model that already knows language, and retrain it on a smaller set of data for a specific task or domain, instead of learning from zero.
Prompt engineering was introduced with zero-shot, where the model is given no training examples, and few-shot, where the model is given a few examples. In zero-shot you describe the task and rely on what the model already learned; in few-shot you place a few worked examples inside the prompt and the model copies the pattern. Both adapt the model with no weight changes — the adjustment lives entirely in the prompt. Generative AI means generating new content: given a certain text as the input prompt, the model generates text. Generative AI is not just for textual content — it can generate image content and video content given text, and today coding agents generate whole chunks of code.
8.5.5 Student Questions and Answers
Q: A student asks whether LLM and prompt engineering related questions will appear in the mid-semester exam.
A: No mathematical problems will be asked on LLM and prompt engineering. There could be a simple conceptual question, like which prompt engineering technique could be used for a given application. It is just a concept that has been introduced; the detailed treatment comes later.
Q: A student asks whether numericals on neural language modeling will appear.
A: No backpropagation questions. About the feed-forward neural network, there could be a numerical in the aspect of defining a network — for example, how to build the network for predicting the next word given four hidden nodes — because feed-forward is what is used in language modeling to predict the next set of tokens. Nothing will be outside what was covered in the course.
8.5.6 Exam Notes
Exam note: the neural language model and LLM module carries an application-oriented question, possibly combined with a small problem on evaluation or a small aspect of neural language modeling. No backpropagation-through-time problems; a small network-definition problem related to language modeling is possible (for example, given four hidden nodes). No mathematical problems on LLM and prompt engineering; at most a simple conceptual question on prompt engineering techniques. Know the pros and cons of neural language models, especially the unseen-word advantage from word embeddings.
Recap and bridge. The neural language model replaces the n-gram count table with embeddings, a hidden layer, and a softmax over the vocabulary; its defining advantage is generalizing to unseen words through embeddings. That same architecture, scaled into transformers, is what LLMs run on today. The revision now closes with a collected summary of the exam guidance and the industry applications behind every module.
Exam Guidance Summary
- The exam is 30 marks, closed book, with 30% weightage. There are around 6 to 7 questions. Each question may have sub-parts, and the paper combines numerical problems, scenario-based case studies, and conceptual questions, assessing problem solving ability as well as understanding.
- The mark distribution has plus or minus one mark variation; some questions carry four or five marks. Depending on the length or complexity of the problem, POS tagging, vector semantics, or language modeling could carry a little more weight.
- Write the justification of answers wherever required. Give the specific formulas used. If a formula is specified in the question, use that respective formula.
- Topic-wise expectations: an application-oriented case study question on the introduction module; a four-mark mathematical problem on statistical (n-gram) language modeling; an application-oriented question, possibly with a small evaluation problem, on neural language models and introduction to LLMs; a mathematical problem on vector semantics (sparse vectors, TF, IDF, cosine similarity); a mathematical problem on word embeddings (skip-gram negative sampling); a problem on POS tagging based on HMM and the Viterbi algorithm; and a small problem on MEMM or ML-based approaches, mostly an application-oriented question on neural language modeling. Nothing will be asked outside the curriculum.
- For stop words: use the list given in the exam; if no list is given, write all assumptions, stating which words were treated as stop words.
- Regular and makeup exams are kept at similar difficulty — roughly eighty to ninety percent similar, not a replica.
- For TF-IDF, use log base ten, or whatever base the question specifies. State the formula used.
- For the SGNS problem, only a single iteration is asked, with simple values and fewer negatives. Derivation is not required. Show the computation in a table step by step. One or two decimal places are fine.
- For n-gram problems, count the vocabulary from the given sentences for Laplace smoothing. Include start and end tags when the question mentions them; otherwise state the assumption. The bigram table convention: rows hold the first word, columns hold the next word; the same convention applies to POS tagging emission and transition matrices.
- No backpropagation-through-time problems. No mathematical problems on LLM and prompt engineering. No mathematical problems on CBOW; CBOW and GloVe are conceptual only.
- Read every question properly before answering, write answers neatly, and write assumptions out so that the evaluation is unambiguous.
- For clarity on the SGNS formulas, refer to chapter 6 of Jurafsky and Martin.
Key Industry Applications
- Web search uses document vector representations to find similar documents.
- ChatGPT and today's LLM transformers use perplexity as an intrinsic evaluation measure, reported in research papers.
- Token embedding dimensions in production models: GPT-3 era models use 768 dimensions, GPT-4 uses 1024, and small language models use around 300 dimensions, the size Andrew Ng recommends.
- The Word2Vec skip-gram negative sampling algorithm comes from a research paper by Google.
- The Google Ngram corpus provides ready-made n-gram counts.
- Hugging Face hosts many openly available pre-trained language models that can be fine-tuned for specific tasks and domains.
- Generative AI goes beyond text: given a text prompt, models generate images, videos, and code; coding agents generate whole chunks of code.
- Conversational AI systems follow an encoder-decoder pattern: understand the user's intent and entities, then generate the response.
- Hybrid NLP systems are the recommended production pattern: classical pipelines for lighter processing, LLMs for advanced reasoning, and guardrails and rules for post-processing.
- Hybrid search combines sparse representations (TF-IDF) with dense representations (contextual embeddings or SGNS), a topic of a later course.
- Sentiment analysis is a binary classification problem, so the network output uses a sigmoid.
- In production language modeling, interpolation is preferred over Laplace smoothing; Laplace smoothing finds use in applications like classification.
- BM25 is an advanced normalized ranking formula used in information retrieval; it is mentioned as beyond this curriculum.
NLP Lecture 8 Notes · Mid-Semester Exam Revision: NLP Foundations
Sections Breakdown
What NLP is, why natural language is hard, the types of ambiguity with examples, the levels of language understanding, classical versus modern versus hybrid systems, and evaluation metrics beyond accuracy.
Words as vectors: term-document and co-occurrence matrices, cosine similarity, TF-IDF weighting with log squashing, and the sparsity problem that motivates dense embeddings.
Dense embeddings by self-supervision: one-hot inputs, the sigmoid as probability, the SGNS loss, gradient updates, and the full one-iteration worked example on the word net.
Language modeling as next-word prediction: the chain rule and Markov assumption, bigram MLE by counting, Laplace smoothing, interpolation and backoff, and perplexity as branching factor.
Neural language modeling: perceptrons and multi-layer networks, softmax for multi-class prediction, sentence embeddings by pooling, the unseen-word advantage, and LLMs with fine-tuning and prompt engineering.
Collected exam intel: mark distribution, topic-wise expectations per module, log-base conventions, and the list of non-examinable topics.
How the syllabus maps onto production NLP: hybrid systems, hybrid search, embedding dimensions in modern models, and intrinsic evaluation in the LLM era.
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
Introduction to NLP: Applications, Ambiguities, and Levels of Understanding
Must-know: NLP is the area of AI concerned with making machines understand and generate human language; ambiguity types (lexical, structural, referential, pragmatic) and the levels of language understanding (phonetics, phonology, morphology, syntax, semantics, discourse, pragmatics) with examples.
⚠️ Top pitfall: Precision and recall trade off: catching more positives (high recall) means more false alarms (low precision); accuracy alone hides failures on a rare class.
Self-check: Which type of ambiguity does "The man saw the boy with the telescope" show, and why?
Connects to: 8.2 Vector Semantics: Frequency-Based Embeddings and TF-IDF, 8.3 Word2Vec and Skip-Gram with Negative Sampling
Vector Semantics: Frequency-Based Embeddings and TF-IDF
Must-know: Cosine similarity is the dot product divided by the product of vector sizes; TF-IDF combines 1 + log10(tf) with log10(N/df); rarer terms get higher IDF (Romeo: log10(37/1) = 1.57; good/sweet: 0).
⚠️ Top pitfall: Using raw counts without the log squash lets frequent words dominate; using dot product without normalization rewards long vectors by frequency, not meaning.
Self-check: In a corpus of 37 documents where Romeo appears in 1 document, what is idf(Romeo) using log base 10?
Connects to: 8.1 Introduction to NLP: Applications, Ambiguities, and Levels of Understanding, 8.3 Word2Vec and Skip-Gram with Negative Sampling
Word2Vec and Skip-Gram with Negative Sampling
Must-know: P(+) = 1/(1+e^{-c·t}) for positive pairs; P(-) = 1/(1+e^{+c·t}) for negatives (sign only inside the sigmoid); one target update t_new = t_old - η·∂L/∂t with ∂L/∂t = [σ(c_pos·t)-1]c_pos + Σ σ(c_neg·t)c_neg.
⚠️ Top pitfall: Using the same formula for negative as for positive pairs; the negative probability is one minus the positive probability, so the sigmoid gets a plus sign inside. Keep the predicted value (from the formula) separate from the actual target (1 or 0).
Self-check: Why does the negative term use 1/(1+e^{+c·t}) instead of 1/(1+e^{-c·t})?
Connects to: 8.2 Vector Semantics: Frequency-Based Embeddings and TF-IDF, 8.4 Statistical Language Modeling: N-Grams, Smoothing, and Perplexity
Statistical Language Modeling: N-Grams, Smoothing, and Perplexity
Must-know: Bigram MLE is C(w_{n-1},w_n)/C(w_{n-1}); Laplace smoothing adds 1 to the numerator and V to the denominator; perplexity PP = P(w_1..w_N)^{-1/N}, lower is better (4.47 means choosing among roughly five options).
⚠️ Top pitfall: A single unseen pair gives probability zero and makes the whole sentence probability zero and perplexity infinite — smooth before scoring; include start/end tags only when the question says so, otherwise state the assumption.
Self-check: For the pair (i, want) with C(i,want)=827 and C(i)=2533, what is the Laplace-smoothed P(want|i) with V=1446?
Connects to: 8.3 Word2Vec and Skip-Gram with Negative Sampling, 8.5 Neural Language Models and Introduction to LLMs
Neural Language Models and Introduction to LLMs
Must-know: Language modeling is multi-class, so the output uses softmax over the vocabulary (sigmoid only for binary sentiment); the neural model's key advantage is predicting unseen words through embeddings; no backpropagation-through-time problems.
⚠️ Top pitfall: Confusing when to use sigmoid versus softmax: sigmoid for two classes, softmax for many; and forgetting that the input to any NLP network is word embeddings, never raw tokens.
Self-check: Why can a neural language model predict after "the dog gets" when training only ever showed "the cat gets fed"?
Connects to: 8.3 Word2Vec and Skip-Gram with Negative Sampling, 8.4 Statistical Language Modeling: N-Grams, Smoothing, and Perplexity
Exam Guidance Summary
Must-know: Exam is 30 marks, closed book, about 6-7 questions mixing numerical problems, case studies, and conceptual questions; nothing outside the curriculum will be asked.
⚠️ Top pitfall: Not writing assumptions out (stop words, start/end tags, log base) — ambiguous answers cannot earn marks.
Self-check: Which topics are NOT examinable mathematically: CBOW, prompt engineering, or backpropagation-through-time?
Connects to: 8.1 Introduction to NLP: Applications, Ambiguities, and Levels of Understanding, 8.2 Vector Semantics: Frequency-Based Embeddings and TF-IDF, 8.3 Word2Vec and Skip-Gram with Negative Sampling, 8.4 Statistical Language Modeling: N-Grams, Smoothing, and Perplexity, 8.5 Neural Language Models and Introduction to LLMs
Key Industry Applications
Must-know: The syllabus maps directly onto production systems: hybrid pipelines for light versus hard tasks, TF-IDF plus dense embeddings in hybrid search, and interpolation over Laplace smoothing in production language modeling.
Self-check: Why does production language modeling prefer interpolation over Laplace smoothing?
Connects to: 8.2 Vector Semantics: Frequency-Based Embeddings and TF-IDF, 8.4 Statistical Language Modeling: N-Grams, Smoothing, and Perplexity, 8.5 Neural Language Models and Introduction to LLMs
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.