Week 7 of 8 · Language half
From meaning to measurement
Last week we created vectors from text. Today we use those vectors to explore documents, measure things in text, extract entities, and retrieve documents by meaning.
Before class
- Bring. The same setup as the last two weeks: laptop, Python + Jupyter, an agentic coding tool, and your notebook.
- Tools. The same
marvel_pages.zipfrom the course data page. New this week:sentence-transformers,transformersandbertopic, allpip install-able, plus spaCy'sen_core_web_smfrom week 5. The first run of each pretrained model downloads it (between 90 MB and 440 MB each), so run the Python examples once before class. - As always. Work this page from top to bottom. From this week, pretrained models become part of the analysis, and checking a model on examples you have read yourself is part of the analysis too.
A quick status. In week 5, we turned written language into tokens and counts. In week 6, we turned documents and words into vectors, which meant that a document or a word could be represented by a string of numbers. We then used those vectors to compare documents, find recurring topics, and represent words through the contexts in which they occur. And we ended on one limitation: every bank got the same vector, river or money.
This week we put those representations to work. We begin with modern text embeddings, which fix the bank problem, and use them to move around an entire corpus. Then we ask more specific questions. Can the same documents be grouped in different ways? How positive or negative is a piece of language? Which entities are mentioned? Which documents are most relevant to a query?
Modern NLP makes many of these analyses surprisingly easy to run. But that ease makes the checking more important, not less. A model will always give you an answer. The scientific question is whether that answer represents what you think it represents (and if it's meaningful).
As in weeks 5 and 6, most sections end with a short Python example. They are there to be run: put them in Jupyter, change something, and watch what the model does with it.
1 · One vector for a whole text
One vector per word type. Word2Vec and GloVe gave us one vector per word. These are static word embeddings, which means that each word type gets a single fixed vector. A simple way to represent a sentence would be to average the vectors of its words. That can be useful as a baseline, but it also throws away word order and gives the same word the same representation every time it appears.
The bank problem. The problem is easy to see with bank. Compare these two sentences:
I went to the bank to deposit money.I sat on the river bank near the water.
A static embedding means that bank is represented by the same vector in both sentences. A contextual model lets the representation depend on the surrounding words, so the two occurrences can end up with different vectors. The same idea applies more broadly, take apple: the fruit, Apple the company, and the Big Apple appear in different contexts and can therefore be represented differently.
Pretrained encoders. Modern text encoders extend this idea from individual tokens to larger pieces of text. Give the encoder a sentence, paragraph or document and it returns a single dense vector intended to summarize information in that text, including context and word order. With a pretrained encoder, somebody else has already done the expensive part (training) for us. That means we can take a fancy encoder and use it on a dataset of our choosing.
What makes pretrained encoders so useful is that large models often transfer surprisingly well to text they were never trained specifically for. At the same time, when we use pretrained encoders, we also inherit the representations they learned from their (often large) training data. Useful linguistic regularities come with the model, but note that stereotypes and other biases can come with it too. Passing our own documents through the encoder means that we don't have to start from scratch; the new vectors are computed using what the model already learned.
Once we pass a document through an encoder, we are back in familiar territory from week 6. Each page is now a vector, so we can compare documents with cosine similarity, find nearest neighbors, or project a set of document vectors into two dimensions so we can explore the corpus visually.
Before we get started, the 3Blue1Brown video below provides a useful visual bridge from the static word vectors we used last week to the representations inside modern language models. You don't need every architectural detail. Watch for the geometry and the idea that relationships in language can be distributed across many dimensions.
Focus on the geometry and on how relative positions can carry regularities in language. Do not try to give every individual dimension a human label.
The video moves quickly from word vectors toward much larger models. For our purposes, keep one distinction clear: a static embedding looks up one vector for a word type, while a contextual model computes a representation from the surrounding text. We will use the resulting document vectors without worrying about how to train the encoder ourselves (there's a different course for that).
Read
Jurafsky & Martin, Chapter 9, Masked Language Models, sections 9.1–9.2. Read for the idea of a bidirectional encoder: every token's vector is computed from the whole sentence around it, which is exactly what makes it contextual. Section 9.5 returns later today, when the same kind of model is used for named entities.
Python example. The bank claim is easy to check with a pretrained encoder. BERT returns one 768-dimensional vector for every token in a sentence, so we can pull out the vector for bank in each of three sentences and compare them:
from transformers import AutoTokenizer, AutoModel
import torch, numpy as np
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
bert = AutoModel.from_pretrained("bert-base-uncased")
sentences = ["I went to the bank to deposit money.",
"I sat on the river bank near the water.",
"The bank approved the loan this morning."]
def vector_of(word, sentence):
enc = tokenizer(sentence, return_tensors="pt")
with torch.no_grad():
hidden = bert(**enc).last_hidden_state[0] # one vector per token
tokens = tokenizer.convert_ids_to_tokens(enc["input_ids"][0])
return hidden[tokens.index(word)].numpy()
money, river, loan = (vector_of("bank", s) for s in sentences)
cos = lambda a, b: a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
print(round(cos(money, river), 2), round(cos(money, loan), 2))
# 0.48 0.81
A static embedding would print 1.0 1.0, since there is only one bank vector to compare with itself. Here the two money banks sit at 0.81 while money and river are at 0.48: the same word, two different vectors, and the context decided which. The small sentence encoder we use below gives 0.75 and 0.82 for the same pairs, a smaller gap, because it was trained to summarize whole sentences rather than to keep single tokens apart.
Documentation: the Transformers quicktour.
7.1 — Static and contextual representations, by hand 🧠 Learn
No notebook for this one. Keep track of what object is being represented and where the context enters.
- Explain why a static embedding gives the two occurrences of
bankabove the same vector, while a contextual model can give them different vectors. - Write two short sentences of your own where the same word has clearly different meanings. Explain which surrounding words you would expect a contextual model to use as clues.
- Suppose an encoder maps a whole Marvel page to 384 numbers. What does one row in the resulting matrix represent? What would it mean for two rows to have high cosine similarity?
- A pretrained encoder was trained before you ever showed it the Marvel pages. Explain what is pretrained and what is computed only when you pass your own documents through the model.
2 · Walk through a corpus
A document embedding contains many more dimensions than we can draw. A text encoder might, for example, represent each Marvel page using 384 numbers:
$$ \mathbf{x}_i = [x_1, x_2, \ldots, x_{384}] $$
The 303 pages then become 303 points in a 384-dimensional space. Those dimensions are not simple labels such as technology, violence or friendship. Information about the text is distributed across many coordinates at once, so we usually learn more by comparing whole vectors than by trying to interpret one coordinate at a time.
The obvious problem is that we cannot see 384 dimensions. If we want a map of the corpus, we need to turn every vector into two coordinates that can be drawn on a screen. This is dimensionality reduction. PCA, SVD, t-SNE and UMAP are all examples of ways to plot high dimensional vectors in 2D space, but they do not preserve the same things.
Two drawings of the same vectors. Take PCA and t-SNE. PCA gives us a broad linear view of variation in the data. t-SNE focuses on getting local neighborhoods right and tries to keep points that were close in the original space close on the map. That often makes clusters easier to see, but the distance between far-away groups on a t-SNE map is much harder to interpret. The t-SNE link is Distill's interactive essay on exactly that trap; there is more in the Goodies.
The important part is that the original document vectors haven't changed. PCA and t-SNE give us two different drawings of the same high-dimensional objects. The nearest documents by cosine similarity should therefore always be calculated in the original embedding space, not read off the 2D map.
I plotted the corpus atlas below so you can see that distinction directly. It runs on the full 303 Wikipedia pages, embedded with the same encoder you will use in your notebook, called all-MiniLM-L6-v2. Search for a character, inspect its nearest neighbors in the original 384-dimensional space, and then switch the 2D projection. The map moves, while the underlying document representation stays fixed.
Search for a character and compare its nearest neighbors in the original representation with the nearest dots on the 2D map. Then switch between PCA and t-SNE and watch the drawing change. Finally color the points by network community and ask whether the communities from the first half of the course live in different parts of the map.
Python example. Once you have document embeddings, making the two projections is only a few lines of code. One thing to check first is the encoder's maximum input length.
from sentence_transformers import SentenceTransformer
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
names = list(marvel_pages)
texts = [marvel_pages[n] for n in names] # one string per document
model = SentenceTransformer("all-MiniLM-L6-v2")
print(model.max_seq_length)
# 256
embeddings = model.encode(texts, normalize_embeddings=True) # 303 × 384
pca_xy = PCA(n_components=2, random_state=42).fit_transform(embeddings)
tsne_xy = TSNE(n_components=2, perplexity=30, init="pca",
learning_rate="auto", random_state=42).fit_transform(embeddings)
That 256 matters. The encoder reads at most 256 word pieces, and 302 of the 303 Marvel pages are longer than that, the median page by a factor of six. So model.encode(texts) quietly embeds the first paragraph or two of each page and throws the rest away, without a warning. This is an important modeling choice! When you work with these methods, you should always either 1) document that truncation or 2) choose a chunking rule and combine the chunk embeddings in a way you can explain. The corpus atlas above uses the second option: each page is cut into passages of at most 180 words along sentence boundaries, every passage is embedded, and the page's vector is the mean of its passage vectors.
import re
import numpy as np
def passages(text, max_words=180):
out, current, n = [], [], 0
for sentence in re.split(r"(?<=[.!?])\s+", text):
words = len(sentence.split())
if current and n + words > max_words:
out.append(" ".join(current)); current, n = [], 0
current.append(sentence); n += words
if current:
out.append(" ".join(current))
return out
doc_vectors = []
for text in texts:
chunk_vectors = model.encode(passages(text), normalize_embeddings=True)
v = chunk_vectors.mean(axis=0)
doc_vectors.append(v / np.linalg.norm(v))
embeddings = np.array(doc_vectors) # 4,473 passages → 303 vectors
Two notes on the projections. PCA is the SVD of the centered vectors; TruncatedSVD skips the centering, and on unit-length embeddings its first axis then just points at the average vector and explains 0.9% of the variance, so the map collapses toward a line. And on these pages PCA's two axes together explain about 10% of the variance, so the 2D picture is a very rough summary of the 384 dimensions, which is the whole reason the nearest-neighbor list is computed in the original space.
Documentation: Sentence Transformers, scikit-learn PCA, and scikit-learn t-SNE.
Compared to what? Last week we scored each representation by how many of a page's ten closest textual neighbors are also its neighbors in the link network: 4.0 for TF-IDF, 2.8 with stopwords removed, 1.9 for raw counts, 0.3 for ten random pages. The pretrained encoder gets 2.5 with the passage rule and 2.1 with plain truncation. Lower than TF-IDF. That is not a failure of the encoder; it is a reminder of what each representation sees. TF-IDF rewards rare words, and in this corpus the rare words are names, which is exactly what Wikipedia links on. The encoder was built to summarize what a text is about, and about-ness is a different thing from who links to whom. The page for Storm shows the difference: under TF-IDF her closest page was the Human Torch, through the surname Storm; under the encoder it is Emma Frost, then Jean Grey, Surge, Jubilee and Cyclops, the X-Men women and teammates, and the surname trap is gone. Doctor Strange's neighbors are Doctor Druid and Jericho Drumm, the corpus's other sorcerers.
Now look back. I'd argue that the fun part of the explorable above is not the scatterplot. It is clicking strange neighbors and going back to the text to work out why the model placed them together.
7.2 — Build a corpus atlas 🔬 Tool
Now make the high-dimensional representation and the 2D picture separately, so you never confuse one with the other.
- Use a pretrained sentence or document encoder to embed the 303 raw Marvel pages. Record the exact model and inspect its maximum input length. State the truncation or chunking rule you use for long pages.
- Pick three characters and calculate their five nearest neighbors by cosine similarity in the original embedding space. Read the relevant pages before you explain why the pairs are close.
- Project the same embeddings with PCA and either t-SNE or UMAP. Keep the original embeddings untouched.
- Build a plot where you can hover over a point to see the character name and click it to list the five cosine-nearest documents from the original space.
- Compare the nearest dots on the 2D map with the cosine-nearest documents for three characters. Find at least one case where the projection gives a misleading visual impression and explain what happened.
- Color the same 2D coordinates by a structural community from the network half of the course. Do not recompute the coordinates when you change the color.
3 · Different ways to split up the same corpus
Last week we used LDA to find recurring topics from patterns of word use. LDA represents a document through word counts, so if you randomly shuffled every word inside the document, the model would see the same Bag-of-Words.
Document embeddings give us another way to represent the same 303 pages. Because these models use a pretrained language model to produce dense vectors from the text, two documents can end up close even if they do not share exactly the same vocabulary. Once the pages are represented in that vector space, we can cluster nearby documents and ask what those groups are about.
Thus, a very direct way to use document embeddings for finding groups of related pages is to simply cluster pages that are close in embedding space ... and then inspect the words and documents that characterize each cluster.
BERTopic. BERTopic is a popular tool that does this. Its default setup combines document embeddings, dimensionality reduction, clustering, and a class-based TF-IDF representation to describe the resulting groups. (You do not need to memorize every internal step of this thing for Test 2. The important idea is that the grouping is based on a different representation from LDA, and both are different again from the network communities you built from hyperlinks.)
One useful BERTopic visualization is an intertopic map. Each circle represents a topic, circle size reflects how many documents are assigned to it, and nearby topics have similar topic representations. The map itself is still a two-dimensional projection, so the warning from the corpus atlas applies here as well.
On our corpus, though, that map has four circles, which is not much of a map. Instead, scroll back up to the corpus atlas and set Color to BERTopic topic. Every page is now colored by the topic that the run below assigned it, the 110 outliers are gray, and the legend shows each topic's top words. The symbiote topic sits in Spider-Man's corner of the map, the mutants topic in the X-Men's, and the two generic piles and the outliers fill the middle. Treat the topic words as summaries that need to be checked against the documents, not as ground truth, and click a few gray points to see what the clusterer could not place.
Python example. BERTopic takes the document embeddings from the atlas and does the rest. Reuse the embeddings you already computed, so the grouping runs on exactly the same vectors as the map, and reuse week 6's name filter for the topic words, or every topic will be a list of character names again.
from bertopic import BERTopic
from umap import UMAP
from sklearn.feature_extraction.text import CountVectorizer, ENGLISH_STOP_WORDS
topic_model = BERTopic(
embedding_model=model,
umap_model=UMAP(n_neighbors=15, n_components=5, min_dist=0.0,
metric="cosine", random_state=42), # seeded, so the run repeats
vectorizer_model=CountVectorizer(stop_words=list(ENGLISH_STOP_WORDS | proper)),
min_topic_size=10,
)
topics, probs = topic_model.fit_transform(texts, embeddings=embeddings)
topic_model.get_topic_info()
Here proper is the set of mostly-capitalized words from week 6's Take the names out. When we ran this, BERTopic found four topics and left 110 of the 303 pages as outliers, topic -1, which is what a density-based clusterer does with a corpus this small. topic_model.reduce_outliers(texts, topics, strategy="embeddings", embeddings=embeddings) assigns those pages to their nearest topic, and after that the four topics hold 166, 62, 44 and 31 pages. Two of them are easy to name: the one whose distinctive word is symbiote is the Spider-Man family, and mutants, mutant, team, powers is the X-Men. The other two are generic piles whose top words are character, series, appears, new. And 35 of the 44 pages in one network community land in the mutants topic, so the embedding-based grouping rediscovers part of the link structure with no links in sight. Run BERTopic with its defaults instead, no name filter and no stopword list, and the topics come back as the, and, of, to: week 5's lesson, one more time.
Documentation: BERTopic.
Three ways to group the same pages. We now have at least three different ways of grouping the same objects. LDA groups documents through word-count patterns, BERTopic groups them with an embedding-based method, and a network community groups pages through hyperlinks. There is no reason they have to agree. Agreement can be interesting, and disagreement can be even more informative if you return to the documents and links to understand it. Comparing and contrasting clusterings can be a key tool for you to use in your final project.
7.3 — Same documents, different groupings 🧠 Learn
Keep the 303 pages fixed and change only the information used to group them.
- In one sentence each, explain what information an LDA topic, an embedding-based text cluster, and a structural network community use to place two Marvel pages together.
- LDA gives a document a mixture over topics, while a clustering algorithm may assign it to one group. Explain why those are different kinds of outputs.
- Suppose an LDA topic and a BERTopic cluster contain many of the same pages. Give one reason that agreement is interesting and one reason it is not proof that either model found the "true" topic.
- Explain why two circles appearing close on an intertopic map is weaker evidence than a similarity calculated in the original representation.
7.4 — Compare groupings on Marvel, as code 🔬 Tool
Use the same documents throughout so the comparison is actually about the representation and grouping method.
- Take your LDA model from week 6 and keep both each page's full topic mixture and its highest-weight topic.
- Run BERTopic on the Marvel pages. Record the embedding model and the main settings you changed from the defaults. Inspect representative words and documents before you give a cluster a human-readable label.
- Make one compact view that compares
LDA topic,BERTopic topic, andnetwork communityfor the same pages. A contingency table, heatmap or color toggle on your corpus map is enough. - Find one place where two groupings agree and one where they disagree. Read the relevant pages and inspect the network links before you explain either case.
- Change one reasonable BERTopic choice, such as the minimum cluster size or embedding model. Which groups survive the change and which do not?
4 · Sentiment as a measurement
Topic modeling and clustering help us ask what text is about. Another very common question is how positive or negative the language is. We call that the sentiment.
Sentiment becomes interesting when we want to make claims about change. It is common to hear that public discourse has become more negative, that news has become more depressing, or that social media has become more hostile. Our own memories are a pretty poor baseline for claims like these. Text gives us the possibility of defining a measurement and applying it repeatedly across a large corpus.
The difficulty is deciding what the measurement actually captures.
The simplest instrument is a lookup table. The simplest sentiment system is a lookup table. Give words scores, find those words in a document, and combine the scores. A toy lexicon might contain:
| word | score |
|---|---|
| wonderful | +2 |
| good | +1 |
| bad | -1 |
| terrible | -2 |
This is easy to inspect because every part of the final score is visible. Context causes trouble quickly. good is positive in the table, while not good is usually not a positive expression. I just love being stuck in traffic contains a strong positive word even though many readers would understand the sentence negatively. I worked a lot with sentiment detection from word lists back in the day. Check out the goodies for more info if you want to learn more and hear the stories.
Learn the rule instead. A supervised classifier learns how to measure sentiment from labeled examples instead. One classical way to do this is to represent the labeled texts with TF-IDF and train logistic regression to predict their labels. The input is still a Bag-of-Words style representation, but the feature weights are learned from examples rather than written by hand. A contextual sentiment classifier changes the representation too, allowing the contribution of a token to depend on the rest of the sentence.
If you want to fully understand the underlying classification setup, read the sentiment example in Chapter 4. The second reading shows the longer tradition of constructing affective lexicons from human judgments.
Read
Read the sentiment-classification section of Jurafsky & Martin, Chapter 4, Logistic Regression and Text Classification. Then skim the opening of Chapter 23, Lexicons for Sentiment, Affect, and Connotation. For a computational-social-science example of aggregating human word ratings, Dodds et al. is also worth a look; the Goodies have a box on it and on its predecessor.
The explorable below sends the same sentence through three measurement ideas so you can compare what information each one uses. Start with not good, then try the traffic example. The contextual column shows the real output of the classifier you will run below, rounded to three decimals. In your notebook you will run the model yourself and inspect its predictions on sentences of your own.
Use the same sentence in all three columns. Compare a fixed lexicon, a TF-IDF classifier, and the output of a contextual model. Pay special attention to the examples where the systems disagree.
Marvel has no ground truth. The Marvel pages do not come with an obvious sentiment ground truth, and Wikipedia is written to be neutral on purpose, so a sentiment score on an encyclopedia page is a strange object from the start. A model can still assign every page a positive or negative score, but that does not tell us whether the number is a useful measurement of anything we care about. On an encyclopedic character page, a negative prediction might reflect a villain, a tragic plot, words such as death, or simply a mismatch between the model's training data and Wikipedia prose.
Python example. You can run a pretrained classifier in a few lines:
from transformers import pipeline
sentiment = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english"
)
sentiment([
"The movie was good.",
"The movie was not good.",
"I just love being stuck in traffic.",
"The hero died, but saved everyone in the city.",
])
# [{'label': 'POSITIVE', 'score': 1.000}, {'label': 'NEGATIVE', 'score': 1.000},
# {'label': 'POSITIVE', 'score': 0.998}, {'label': 'POSITIVE', 'score': 0.999}]
The model handles the negation, and then it calls the traffic sarcasm POSITIVE at 0.998 and the hero's death POSITIVE at 0.999, each time with near-total confidence. Point it at the Marvel pages themselves (it reads at most 512 word pieces, so pass truncation=True) and 179 of the 303 pages come back NEGATIVE: Jubilee at 0.987 and Doctor Strange at 0.931, while Storm is POSITIVE at 1.000. Nothing in those numbers tells you what was measured.
Documentation: the Transformers pipeline tutorial.
That particular model was fine-tuned on movie-review sentiment. If we apply it to political news, Reddit posts or Wikipedia biographies, we are assuming that what it learned as positive and negative transfers to another kind of text. That's an assumption that needs checking.
Sentiment is built for text that feels something. I mentioned that sentiment is about change over time, so stories are the natural home of this measurement. A narrative moves: things go well, then badly, then the ending lands, and a sentence-by-sentence score through the text should show that movement. Vonnegut drew the shapes of stories on a blackboard (the lecture is on YouTube); Reagan et al. measured them across 1,327 stories from Project Gutenberg and found six recurring arcs. Wikipedia does not contain stories, so we have to move beyond our trusted dataset to really get into sentiment detection (it's even worse with Wikipedia because (as mentioned above) the text is written to be neutral — so it's hard to get sentiment out of it). Thus, I've been online to find a Marvel fan-fiction novel, Dark Matter by mysterycyclone for our sinister purposes. In the book, Peter Parker lands in Gotham instead of turning to dust: 46 chapters, 240,000 words, and, unlike Wikipedia, written to make you feel something. Every one of its 21,748 sentences is scored by the movie-review classifier from the Python example and by VADER, a lexicon built for social-media text. The top panel shows the whole novel chapter by chapter; click a chapter to see its sentences, and choose how many of them to average over.
Open chapter 22 and slide the smoothing from none to forty sentences: a square wave becomes an arc. Then read the list at the bottom: the sentences where the lexicon and the classifier point in opposite directions are the ones to read closely. The first one is about the King of Wakanda: the classifier says +0.96, the lexicon −0.96. Hover either panel for the sentence and what each instrument made of it. Across the novel, the two instruments agree on the sign of only 36% of the sentences.
Note how the two approaches don't align. That is both a challenge and an opportunity come project time. You need to be aware that the tool you choose influences the results. And sometimes, the disagreement between tools is information to be mined and used.
Beyond positive and negative: DeepMoji. A one-dimensional score throws away most of what a sentence does. Anger and grief are both "negative"; relief and sarcasm are hard to place at all. In DeepMoji, a model from my own group (Felbo et al., 2017), we took a different route. We trained the model on 1.2 billion tweets to predict which of 64 emoji the author used. So we used the emoji as labels! Nobody had to annotate anything, the labels were already there. Pretty clever if I have to say so myself. The result is a model that answers with a distribution over emoji instead of a number. I just love being stuck in traffic comes back as 🔫 😡 😑 😠, where the movie-review classifier said POSITIVE at 0.998, and the King of Wakanda sentence comes back as 👿 😡 😠. The explorable below runs DeepMoji through the same novel. The emoji strip shows the most likely emoji in each slice of a chapter, and the emotion track sums the probability of a group of emoji, so anger, sadness, love or joy can be followed separately through the story. One more thing about DeepMoji: predicting emoji turned out to be a good way to learn about text in general. Fine-tune the pretrained model on a small set of human-labeled sentences and it becomes a sentiment classifier, and in the paper that recipe beat the state of the art at the time on all eight benchmarks we tried across sentiment, emotion and sarcasm, the same pretrain-then-fine-tune pattern behind the movie-review classifier earlier in this section. The Goodies have the paper and how to run the model yourself.
The two explorables stay on the same chapter, so if you opened chapter 22 above it is open here too. It is the angriest chapter of the novel, and the list at the bottom shows why: The Joker takes a few steps towards Peter, raising his crowbar comes back as 👿 😉 👊, a sentence both sentiment instruments called mildly positive. Switch the emotion to sadness or joy and watch the chapter overview change shape.
Producing a score is the easy part. Showing that the score behaves like the thing you wanted to measure is where the scientific work begins.
7.5 — Sentiment, by hand 🧠 Learn
Start with transparent measurements before letting a model return a probability.
- Using the toy lexicon above, calculate the sentiment score of
good but terrible. Then explain why a pure lookup system mishandlesnot good. - In a TF-IDF + logistic-regression classifier, what does a positive coefficient for a feature mean? What does a negative coefficient mean? Explain without using the word "important" by itself.
- A contextual model returns
POSITIVE, 0.97. Give two reasons why the confidence score is not the same thing as evidence that sentiment has been measured validly. - The model above was trained on movie reviews. Name one piece of Marvel or Wikipedia language that might behave differently from movie-review language and explain how you would test it.
7.6 — Validate a sentiment instrument 🔬 Tool + 🚀 Builder
Here the model is a measurement instrument. Do not scale it up until you know something about its errors.
- Choose a manageable labeled sentiment dataset and create a held-out test set. Keep the same test examples for every method you compare.
- Compare a lexicon baseline, a TF-IDF + logistic-regression classifier, and one pretrained contextual sentiment model. Record the dataset, split, exact pretrained model and preprocessing choices.
- Before looking at one overall accuracy number, read a random set of examples yourself. Make a small error table from patterns you actually see, such as negation, sarcasm, mixed sentiment, domain language or ambiguous wording.
- Create at least three small stress tests by changing one sentence in a controlled way, for example adding
not, swapping one sentiment word, or turning a literal sentence into sarcasm. Record how all three systems react. - Pick a narrative text you know well, such as a short story, a fan-fiction chapter or a long Wikipedia plot summary, and score it sentence by sentence with the lexicon and the contextual model. Plot both arcs with a moving average and find the three sentences where the two instruments disagree most. Read them, decide which instrument you side with, and say what that tells you about what each one measures.
- Only after that, run the systems on a small sample of Marvel pages. State what you think a page-level sentiment score represents there and one reason you would be cautious about comparing that score across network communities.
5 · Entities turn prose into structured data
Sometimes the output we want is not one number for a whole document. We want to find particular things inside the text. If a sentence says
Iron Man (Tony Stark) met Black Widow in New York.
then a named entity recognizer can turn the prose into structured spans:
| span | type |
|---|---|
| Iron Man | PERSON |
| Tony Stark | PERSON |
| Black Widow | PERSON |
| New York | GPE |
Named entity recognition, NER, asks which spans in a piece of text refer to named things such as people, organizations, places or dates, and which type each span belongs to. In the sentence above, for example, the useful output is not simply that Iron looks like a person word. We want the complete span Iron Man, and we want to know that New York is one place rather than two unrelated tokens.
From tokens to spans. NER is therefore often framed as a sequence-labeling problem. The model gives a label to each token and neighboring labels are then combined into entity spans. Something we call the BIO notation makes those boundaries explicit: B-PER begins a person span, I-PER continues it, and O means that the token is outside an entity. Don't spend any energy worrying about the type names changing between PERSON in the table above and PER here — different annotation standards abbreviate the same categories differently, and a model reports whichever set it was trained on. What matters is the structure: one label per token, and B versus I telling you where a span starts rather than continues. The result is structured text we can count and connect later, but it still does not tell us whether two different names refer to the same underlying entity.
The explorable below shows those two levels one after the other. In the first row, inspect the model output token by token and switch between entity labels and BIO tags. In the second row, see how those token labels become structured entity spans. Notice what is still missing: recognizing Iron Man and Tony Stark does not tell us that they refer to the same character.
First inspect one prediction per token, then the structured spans created from those labels. Switch to BIO tags and pay attention to where multi-token entities begin and continue.
If BIO tags are new to you, the NLP textbook gives the standard sequence-labeling view and shows how named entities are represented as spans.
Read
Jurafsky & Martin, Chapter 18, Sequence Labeling for Parts of Speech and Named Entities, section 18.3 and the evaluation in 18.6. Focus on named entities, span boundaries and BIO-style labels; the HMM and CRF machinery in between can wait. Section 9.5 of Chapter 9 shows the modern version: the same tags, predicted by a fine-tuned pretrained encoder.
Python example. spaCy's small English pipeline from week 5 includes a named entity recognizer, and every token carries its BIO tag and entity type:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Iron Man (Tony Stark) met Black Widow in New York.")
[(t.text, t.ent_iob_, t.ent_type_) for t in doc]
# [('Iron', 'O', ''), ('Man', 'O', ''), ('(', 'O', ''),
# ('Tony', 'B', 'PERSON'), ('Stark', 'I', 'PERSON'), (')', 'O', ''),
# ('met', 'O', ''), ('Black', 'B', 'ORG'), ('Widow', 'I', 'ORG'),
# ('in', 'O', ''), ('New', 'B', 'GPE'), ('York', 'I', 'GPE'), ('.', 'O', '')]
[(e.text, e.label_) for e in doc.ents]
# [('Tony Stark', 'PERSON'), ('Black Widow', 'ORG'), ('New York', 'GPE')]
Compare that with the explorable, which shows what a tagger should do with the sentence. The real small model never sees Iron Man as an entity at all, and it files Black Widow as an organization. Neither mistake is strange: superhero names are rare in the news text the model was trained on, and Black Widow could totally look like a company name. But both would silently shape any network built from this output, which is why exercise 7.8 starts with hand-labeled sentences.
The same tags turn a whole page into a co-mention network in a dozen lines:
from collections import Counter
import networkx as nx
page = nlp(marvel_pages["Spider-Man"])
pairs = Counter()
for sentence in page.sents:
people = sorted({e.text for e in sentence.ents if e.label_ == "PERSON"})
for i in range(len(people)):
for j in range(i + 1, len(people)):
pairs[(people[i], people[j])] += 1
G = nx.Graph()
for (a, b), weight in pairs.items():
G.add_edge(a, b, weight=weight)
pairs.most_common(4)
# [(('Mary Jane', 'Peter'), 15), (('Peter Parker', 'Spider-Man'), 14),
# (('Peter', 'Spider-Man'), 9), (('Ditko', 'Lee'), 8)]
The Spider-Man page has 445 sentences and 635 PERSON spans, 179 of them distinct, and the network has 146 nodes and 293 edges. Look at the top pairs before you trust either number. Peter, Peter Parker and Spider-Man are three nodes for one character, so the second- and third-strongest edges in the network connect a man to himself. Ditko and Lee are Steve Ditko and Stan Lee, who created the character and are not in the story at all. Resolving the aliases and deciding who counts as a character are modeling decisions, and the tagger made neither of them.
Documentation: spaCy named entities.
Extraction is only the first step. If we want to count actors or build a network, we often need entity resolution as well. Iron Man, Tony Stark and sometimes simply Stark may all refer to the same character. Whether they should be merged is a separate decision from detecting the spans in the first place.
From entities to a network. Once entities have been extracted and resolved, we can turn them into a network. A nice example comes from Fields et al. (2023), who combine NER and social network analysis to study nineteenth-century Ottoman-Iraqi diaries. They identify person mentions, resolve them to individuals, and connect people who occur in the same dated diary entry.
We can do the same kind of construction with Marvel text. First we extract the entity spans, then decide which aliases refer to the same character, and finally choose what it means for two entities to co-occur before we draw an edge between them. That last choice is doing a lot of work. Two characters could be connected when they appear in the same sentence, paragraph or page. Those choices create different networks and imply different meanings for an edge.
The next explorable lets you watch this construction happen. Follow the text through entity extraction and alias resolution, then change the unit of co-occurrence and watch which edges appear or become stronger.
Follow the path from prose to extracted entities to resolved names to a network. Change the co-occurrence unit and ask what the resulting edge actually means.
What does an edge mean? Before interpreting the graph, ask the same question we asked about hyperlink networks: what relationship have we actually measured? Co-mention is not the same thing as interaction. Two characters can be mentioned together without meeting, and two characters can interact without being named in the same sentence. Fields et al. make the same point when they discuss co-mention in a diary entry as a proxy for a social relationship.
From an AI-drafted report
"We scored every Marvel page with a DistilBERT sentiment classifier that reports 96% accuracy, so the measurements are reliable. Villain pages are significantly more negative than hero pages (−0.42 against +0.11). The NER model found 1,847 distinct characters, and the co-occurrence network built from them shows clear community structure." There are three flaws. Find them. Sections 4 and 5 give you everything you need, and in exercise 7.7, item 6, you will rewrite the report yourself.
7.7 — BIO tags, entities, and edges, by hand 🧠 Learn
Go from prose to a network on paper before a tagger does it for thousands of sentences.
- Write BIO tags for
Iron Man (Tony Stark) met Black Widow in New York.Choose sensible entity classes and state one annotation decision another scheme could reasonably make differently. - Explain the difference between entity extraction and entity resolution using
Iron Man,Tony StarkandStark. - Take two short sentences containing three named characters and draw the co-occurrence network you would get from sentence-level edges. Then combine the same sentences into one paragraph and draw the paragraph-level network.
- Give one example where a co-occurrence edge would suggest a relationship that the underlying text does not actually support.
- Explain why changing the unit of co-occurrence is a modeling decision rather than a plotting decision.
- 🧠 Rewrite the AI-drafted report above in three honest sentences: what was actually measured, what would have to be checked before believing it, and what the entity count really counts.
7.8 — Tag, check, resolve, connect 🔬 Tool + 🚀 Builder
Now use a pretrained NER model as a measurement instrument and carry its output all the way into a network.
- Hand-label a manageable random sample of Marvel text before you run the model. Keep those labels as a small reference set.
- Run a pretrained NER model and compare its spans with your reference labels. Report at least span-level precision and recall, then inspect the mistakes and describe recurring errors.
- Make a short alias-resolution table for names you can justify merging. Keep the original model output so the resolution decisions remain inspectable.
- Build an entity co-occurrence network using at least two units, for example sentence and paragraph. Compare node counts, edge counts, degree distributions, communities and several concrete edges.
- Find one edge that looks convincing and one that becomes questionable when you read the underlying text. Explain what created each one.
- Combine methods from the course in one small analysis. Ask a question where the entity network becomes more useful when paired with topic modeling or sentiment, and state what each method contributes to the answer.
6 · Search by meaning
Week 5 asked you to build a Marvel search engine in 20 lines, and week 6 gave it TF-IDF. Represent a query and every document with TF-IDF, calculate cosine similarity, and rank the documents. This works especially well when the query and the useful document share vocabulary.
Vocabulary mismatch. The weakness is vocabulary mismatch. A user might search for automobile repair while the relevant document repeatedly says fixing cars. Sparse TF-IDF vectors see different words. A dense retriever instead encodes the query and documents into a shared vector space where similar meanings can be close even without exact word overlap.
The reading below gives the dense-retrieval setup and then shows how retrieval becomes the first stage of RAG. The name and the recipe come from Lewis et al. (2020), Retrieval-augmented generation for knowledge-intensive NLP tasks. If you have followed the earlier readings, section 11.3 will already be familiar. One note that helped me: Keep the concepts of retrieval and generation separate when you read.
Read
Continue Jurafsky & Martin, Chapter 11, sections 11.3–11.4. Section 11.3 introduces dense retrieval. Section 11.4 adds generation after retrieval.
Now try the same query under two representations. The explorable below places sparse and dense retrieval side by side so you can look for cases where exact vocabulary helps and cases where semantic similarity helps. The dense column uses the same pretrained encoder as the corpus atlas, over the full Wikipedia pages, which is what you will use in your notebook.
The preset queries were run offline over the full pages, so both columns are the real thing: TF-IDF on the left, MiniLM on the right, and each preset knows which page it is about, so the line under the menu keeps score. The first six are paraphrases that share few words with the page they describe, and the dense column wins them; a deaf archer who never misses is the other way around, because deaf and archer are literally on Hawkeye's page. The dense column has two versions, the page's best short passage or one mean vector per page: switch to the page mean on the Russian-spy query and watch Black Widow drop from rank 2 to rank 20, because her whole biography is about more than being a spy. The last preset asks for the Norse god of thunder, and Thor is not in the corpus: look at what each retriever returns when the answer does not exist. Type your own words and only the sparse column can answer, live, over the one-line descriptions, because a text encoder does not run inside a web page.
Python example. Both retrievers are a few lines once the representations exist. Sparse retrieval is basically week 6's TF-IDF with the query treated as just one more document. Dense retrieval encodes the query using the same model as the pages and then simply ranks by dot product (which for unit-length vectors becomes the cosine similarity).
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
query = "a Russian spy who became an Avenger"
tfidf = TfidfVectorizer()
X = tfidf.fit_transform(texts)
sparse = (X @ tfidf.transform([query]).T).toarray().ravel()
q = model.encode(query, normalize_embeddings=True)
dense = embeddings @ q
for scores in (sparse, dense):
top = np.argsort(-scores)[:4]
print([(names[i], round(float(scores[i]), 2)) for i in top])
# [('Ursa Major (character)', 0.07), ('Black Widow (Natasha Romanova)', 0.06), ('Red Guardian', 0.05), ('Yelena Belova', 0.05)]
# [('Red Guardian', 0.61), ('U.S. Agent', 0.49), ('Ursa Major (character)', 0.47), ('Quicksilver (Marvel Comics)', 0.47)]
The obvious answer is Black Widow, and here sparse retrieval finds her and dense retrieval does not. TF-IDF matches Russian, spy and Avenger literally, and her page uses all three. The dense query lands nearest Red Guardian, the Soviet answer to Captain America, because the page-level embeddings summarize whole biographies, and hers is about much more than being a Russian spy. Cut the pages into short passages of two or three sentences (14,976 of them), score those instead of the 303 page means, give each page its best passage, and Black Widow is back at rank 2, behind Red Guardian. Over a larger set of test queries the same encoder puts the right page in the top 3 for 33% of them as page means, 72% with 180-word passages and 89% with 60-word passages, against 67% for TF-IDF. As always preprocessing matters for the outcome! How you cut the documents is part of the retriever, which is why exercise 7.10 asks you to change the chunk size and watch the rankings move.
Documentation: the Sentence Transformers semantic-search guide.
Then generate. Retrieval-augmented generation, RAG, adds a language model after retrieval. You ask a question. Then, the system first finds passages that appear relevant to the question (retrieval) and then gives those passages to the language model when it generates an answer.
But an important point here is that there are more things that can go wrong. A retrieval error and a generation error are different failures. If the retriever brings back the wrong passage, the generator never had the right evidence. If the retriever brings back the right passage and the answer is still wrong, the problem happened later. When you work with this kind of system, keeping the retrieved evidence visible makes it much easier to inspect and interpret where things could have gone wrong.
7.9 — Sparse and dense retrieval, by hand 🧠 Learn
Think about what each representation can see before you build a search interface.
- Explain why
automobile repairandfixing carscreate vocabulary mismatch for a word-count representation. What information would a dense representation need to place them close anyway? - Suppose two document vectors are already normalized. Explain why ranking them by cosine similarity to a normalized query is equivalent to ranking them by dot product.
- Write one query where you expect TF-IDF retrieval to work especially well and one where you expect dense retrieval to have an advantage. Explain your prediction before you run either system.
- A RAG system gives a wrong answer. Write one example of a retrieval failure and one example of a generation failure. What would you need to inspect to tell them apart?
7.10 — Search the Marvel corpus 🔬 Tool
Use queries where you can read the returned pages and judge relevance yourself.
- Reuse your week 6 TF-IDF representation for sparse retrieval and the pretrained encoder from exercise 7.2 for dense retrieval.
- Write at least six queries before looking at the rankings. Include some with obvious vocabulary overlap and some paraphrases. Save the top five results from both methods for every query.
- Read the returned pages and make your own relevance judgments. Find at least one query where sparse retrieval is more useful and one where dense retrieval is more useful. Keep a failure from each system too.
- Build a side-by-side search interface where the query, similarity score and returned text are visible rather than showing only character names.
- Change one modeling choice, such as the encoder, chunk size or TF-IDF preprocessing, and rerun two queries. Which conclusions survive?
- If you add an LLM answer on top, keep the retrieved passages visible and report retrieval errors separately from generation errors.
7 · Bias can enter before the model
Optional · not on Test 2
This final section is an extension for anyone who wants to follow the measurement problem one step further. The ideas are useful, but this section is not part of the week 7 material assessed on Test 2.
By this point, the analyses can start to look very technical. We have vectors, clusters, sentiment scores, entity spans and ranked documents. It is easy to focus on bias in the final model, even though the model is really just a part of a much longer process of handling data. Bias can already enter through who appears in the data, which platform was available to collect from, what was labeled, what was discarded during preprocessing, and what outcome we decided to predict.
Bias can also be learned as an association in the representation itself. Imagine training on text from a society where women are repeatedly described near words such as nurse, while men are more often described near engineer. An embedding model can learn part of that pattern as geometry in its vector space. Reusing the model years later does not make the association disappear simply because the new application is more modern. Those learned relationships can still influence which texts look similar, how examples are classified, or what gets ranked.
In a text project there are sooo many sources of bias (all easy to forget and ignore). Some people post much more than others. Some languages and dialects are easier for our tools to process. A corpus may overrepresent people who are already visible online. We might remove short texts, keep only English documents, or force ambiguous examples into a fixed set of labels. The model then learns from the result of all those earlier choices.
If you want the framework behind the figure below, the following optional reading is from public and population health, but the same sequence of choices transfers very naturally to text analysis.
Optional reading
Read Vishwali Mhasawade, Yuan Zhao and Rumi Chunara, Machine learning and algorithmic fairness in public and population health, especially Figure 2 and the surrounding discussion.
The visual below adapts the logic of Mhasawade et al.'s Figure 2. Read it from top to bottom. At every step, one version of the world is translated into another, which means something can be selected, lost or changed before the final model ever sees the data.
Read from the social world toward the model. At each step, ask what entered the data, what was left out, and which choices could change the final output.
7.11 — Trace bias through one NLP analysis 🧠 Learn + 🔬 Tool · optional
Pick one route from this week and trace one plausible distortion from the social process to the final output.
- State the social process behind the text and who is likely to be present or absent from the corpus.
- Describe one way the move from the world to the data could distort what you observe.
- Describe one way preprocessing, labels, representation or model choice could preserve or amplify that distortion.
- Propose one check you could actually run on the data or model output.
7.12 — Ship an explorable 🚀 Builder · stretch, optional
Pick one idea from the week that became clearer when you could see it and build the version you wish had been on this page. Agents encouraged; the explanation still has to be yours.
Some ideas to explore: let a user move between a high-dimensional nearest-neighbor list and a 2D projection; compare LDA, BERTopic and network communities with one color switch; build a sentiment stress-test playground; show BIO tags becoming entity spans and then a network; or build a search box that compares sparse and dense retrieval. The best ones get embedded on the page with credit.
7.13 — Go nuts with your LLM 🚀 Builder · every week
The standing rules live in week 1, exercise 1.8: one free-form post on your group's site, link in this week's Teams channel by Monday evening, friendly criticism for at least one other group. Winner announced at the start of the next session.
This is the last week of the language block, so use the Marvel text and network to ask one question that genuinely interests you. One good question and one convincing figure beats five methods thrown together. Whatever model you use, keep enough of the underlying text visible that you can check what produced the pattern.
Some openers, if you want them:
- Who is semantically close but structurally far away? Find characters whose pages are close in embedding space but far apart in the hyperlink network, then read the pages and work out why.
- How much does the grouping method change the story? Compare LDA topics, embedding-based clusters and network communities for the same characters. Focus on the cases where they disagree.
- Can you break a sentiment model? Design a small set of examples that isolate negation, mixed sentiment, sarcasm or Marvel-specific language, then compare several sentiment measurements.
- Six shapes? Score a few dozen fan-fiction stories sentence by sentence, smooth, and cluster the arcs. Do Reagan et al.'s six shapes show up, and does DeepMoji's anger follow the same shape as the classifier's negativity?
- Can text build a useful network? Construct an entity co-occurrence network and compare it with the Wikipedia hyperlink network. Investigate the edges that exist in only one of them.
- When does semantic search beat keyword search? Design queries where sparse and dense retrieval disagree and read the returned pages to decide which representation helped.
- Or ignore every suggestion and chase something one of the explorables made you wonder about. The winner is rarely the group that played it safe.
Write the post around the question rather than the software package you used: what you asked, what representation or measurement you chose, one strong figure or table, what surprised you, what you checked in the underlying text, and one limitation.
8 · Next week: putting it all together
Across the three language weeks, we have moved from raw text to representations and then from representations to measurements and tools. The recurring habit should be the same one we used for networks: know what the object is, know how it was constructed, and inspect the data underneath a result before you believe the story it seems to tell.
Next week there is no new method. Instead we work on the hard part: choosing the right dataset and the right question, so that seven weeks of tools have something worth doing. The final project starts the week after, and it runs on a dataset you pick, so bring your group and a first idea.
Essentials
This is the 🧠 Learn core of the week in one place. If you can explain what is being represented, what information each model uses, and what you would check before interpreting its output, you are ready for this week's share of Test 2.
- Static word embedding
- one fixed vector for each word type, regardless of the sentence in which it occurs.
- Contextual representation
- a representation that depends on the surrounding text, so the same word can receive different vectors in different contexts.
- Document embedding
- one dense vector representing a sentence, paragraph or document so texts can be compared geometrically.
- Pretrained encoder
- a model trained on another corpus before we apply it to our own text to produce representations.
- Chunking
- cutting a long document into passages before embedding it; the cutting rule is part of the representation, and an encoder's input limit silently truncates what you do not cut.
- Dimensionality reduction
- mapping high-dimensional vectors into fewer dimensions, often two for visualization. The projection is a simplified view of the original representation.
- t-SNE
- a nonlinear dimensionality-reduction method that emphasizes local neighborhoods. Nearby points can be informative, while global distances and cluster shapes require caution.
- Embedding-based text cluster
- a group of documents placed together because their dense representations are close under a clustering procedure. This is a different object from an LDA topic or a network community.
- Sentiment lexicon
- a list of words with sentiment or affect scores that can be combined into a transparent text-level measure.
- Emotional arc
- a sentence-level sentiment score smoothed along a narrative; the shape, not the level, is the thing being measured.
- Text classifier
- a model learned from labeled examples that maps a text representation to a label or probability.
- Validation
- checking a measurement or model output against examples, labels or behaviors that let you judge whether it works for the intended task and domain.
- Named entity recognition, NER
- finding spans in text that refer to entities such as people, organizations or places and assigning them entity types.
- BIO tags
- sequence labels in which B begins an entity span, I continues it and O marks a token outside an entity.
- Entity resolution
- deciding when different mentions or names refer to the same underlying entity.
- Entity co-occurrence network
- a network in which entities become nodes and an edge is created when two entities appear within a researcher-defined unit of text.
- Sparse retrieval
- retrieval based on sparse lexical representations such as TF-IDF, where shared vocabulary contributes directly to similarity.
- Dense retrieval
- retrieval in which queries and documents are encoded as dense vectors and ranked by vector similarity.
- Vocabulary mismatch
- the retrieval problem that occurs when a relevant document expresses the right idea using different words from the query.
- Retrieval-augmented generation, RAG
- a two-stage setup in which relevant passages are first retrieved and then supplied to a language model for generation.
On Test 2
From this week, you should be able to do the following on paper, closed book. Any formula you need is printed on the test paper — you are never asked to write one from memory:
- distinguish a static word embedding from a contextual representation using an ambiguous word such as
bank; - explain what a document embedding represents, and distinguish the original vector space from a two-dimensional projection of it;
- explain why nearest neighbors in a 2D map can differ from nearest neighbors by cosine similarity in the original space;
- distinguish topic-model topics, embedding-based text clusters and structural network communities as three different ways of grouping the same documents;
- calculate a simple lexicon sentiment score and explain why negation, mixed sentiment or sarcasm can break word lookup;
- explain how a TF-IDF representation can enter a logistic-regression text classifier, and interpret the sign of a feature weight;
- explain why a model confidence score is not by itself evidence that a text measurement is valid for a new domain;
- read and construct simple BIO tags — B begins an entity span, I continues it, O marks a token outside one — and distinguish finding an entity from deciding that two mentions are the same entity;
- explain how the chosen unit of co-occurrence changes the meaning and structure of a text-derived entity network;
- distinguish sparse TF-IDF retrieval from dense retrieval and explain the vocabulary-mismatch problem;
- explain the two stages of retrieval-augmented generation (RAG) separately, and distinguish a retrieval error from a generation error;
- give a concrete validation check for a pretrained model used as a measurement instrument;
- spot the flaw in a short (possibly AI-written) claim built on a model's output: an accuracy borrowed from another domain presented as validation, a score reported without saying what it measures, or an entity count that skipped resolution.
Goodies
Everything above is the course. Everything below is for the student who finished the page and wants more. Nothing here is on the test; all of it is worth your time.
How not to fool yourself with t-SNE
Wattenberg, Viégas and Johnson's interactive essay How to Use t-SNE Effectively is still one of the best ways to understand why a beautiful 2D map can be misleading. Change the perplexity and watch familiar high-dimensional structures turn into very different pictures.
Semantic search with Sentence Transformers
The Sentence Transformers semantic-search guide goes beyond the tiny Marvel search engine and explains symmetric versus asymmetric search, cosine scoring and efficient retrieval over larger corpora.
Go deeper into BERTopic
The BERTopic documentation makes the different steps unusually transparent. You can inspect the embedding, dimensionality-reduction, clustering and topic-representation steps separately and replace them one at a time. That is much more useful than treating fit_transform() as magic.
Pulse of the Nation: a word list meets 300 million tweets
In 2010 Alan Mislove, Yong-Yeol Ahn, Jukka-Pekka Onnela, Niels Rosenquist and I scored 300 million tweets, September 2006 to August 2009, with a word list and drew the result as a time-lapse map of the United States: Pulse of the Nation. The list was ANEW, the Affective Norms for English Words (Bradley and Lang, 1999): about a thousand words rated by volunteers on a nine-point scale from unhappy to happy, and a tweet's mood is the average rating of the ANEW words it contains. That is all the NLP there is, and it was enough to see the day (happiest early in the morning and late at night, the afternoon at work the low point), the week (a Sunday-morning peak, a Thursday-evening trough), and the West Coast running three hours behind the East. As far as I know it was the first large-scale analysis of Twitter anyone had done, and it went around the world: the CBS Evening News, the New York Times, the BBC, and a long tail of "Twitter proves California is happier" headlines. Two things from it are worth keeping. The maps are cartograms, with each county scaled to its number of tweets, which is the first question to ask of any such map: who is tweeting? And the list measures whether people use happy words, not whether they are happy; that gap is what §4 is about.
The hedonometer and the labMT word list
Peter Dodds, Chris Danforth and their group in Vermont built a word list by asking a different question: not which words psychologists chose, but which words people actually use. They took the 5,000 most frequent words from each of four sources (Twitter, Google Books, the New York Times and song lyrics), merged them into 10,222 words, and had Mechanical Turk workers rate each on the same 1-to-9 happiness scale as ANEW; the result is labMT, language assessment by Mechanical Turk (Dodds et al., Temporal patterns of happiness and information in a global social network: Hedonometrics and Twitter, PLoS ONE 2011). One detail in the paper is worth stealing: before scoring a text they drop the neutral middle of the scale, every word rated between 4 and 6, because the and of carry no mood but dominate every text. The hedonometer has applied the list to a daily sample of Twitter since 2008, and a decade of history is readable off the curve: the Christmas peaks, the dips after attacks and shootings, the long low of spring 2020. The list itself is downloadable and runs in three lines of pandas, which makes it a good first instrument for exercise 7.6.
Video: word lists, at length
Twenty-four minutes from an earlier year of this course, where I go deeper into word-list sentiment than this page does: where the lists come from, what the ratings mean, and the stories behind the two projects above.
Test behaviors, not only accuracy
Ribeiro et al.'s Beyond Accuracy: Behavioral Testing of NLP Models with CheckList is a great continuation of the sentiment section. The paper asks what happens when we deliberately test capabilities such as negation and invariance instead of relying on one held-out accuracy number.
DeepMoji: emoji as labels
Felbo, Mislove, Søgaard, Rahwan and Lehmann, Using millions of emoji occurrences to learn any-domain representations for detecting sentiment, emotion and sarcasm (EMNLP 2017). The trick is distant supervision: 1.2 billion tweets already carried their own labels, the 64 most common emoji, so a bidirectional LSTM with attention could be trained to predict them and then transferred layer by layer (the paper's "chain-thaw" recipe) to small human-labeled datasets for sentiment, emotion and sarcasm, where it set the state of the art at the time. To run it yourself, use the PyTorch port torchMoji with the weights mirrored on Hugging Face; it predates Python 3.11 and PyTorch 2 and needs two one-line patches: in torchmoji/tokenizer.py make the title regex RE_TITLES = r'|'.join([r'(?i:' + t + r')' for t in TITLES]), and in torchmoji/lstm.py unpack the packed sequence as input, batch_sizes = input.data, input.batch_sizes. For the shapes of stories, Reagan et al., The emotional arcs of stories are dominated by six basic shapes (EPJ Data Science, 2016), is the paper behind the sentiment explorable; its instrument is the labMT list from the hedonometer box above.
From entities back to networks
Fields et al.'s study of Ottoman-Iraqi diaries is a real example of the full route from named-entity recognition to social network analysis. It is especially useful because the authors keep returning to the source text when interpreting what a co-occurrence edge means.
Bias can enter long before training
If the optional final section caught your interest, Mhasawade, Zhao and Chunara's Machine learning and algorithmic fairness in public and population health gives the original figure used there. The domain is health rather than NLP, but the distinction between the social world, observed data, measurement and model output transfers directly.