Text & Language — Interactive Lab
A hands-on tour of the machinery that turns raw text into structure and meaning — tokenizers, inverted indexes, edit-distance grids, language models, and similarity metrics, built from scratch and run in front of you. Three layers: The machine dives that step you through a full text pipeline one operation at a time, Math focus dives that derive the scoring formulas, and Concept cards for the vocabulary. Click, drag, and run each idea to see it work. A sibling to the ML, Deep-Learning, Time-Series, Data-Engineering, and Databricks labs. Press Esc anytime for this menu.
The tokenizer, one merge at a time
How raw text becomes the integer tokens a model sees. Press Next to normalize the text, split it into words and then symbols, count adjacent pairs, learn a sequence of merges (byte-pair encoding) that grow the vocabulary, then encode an unseen word into subword tokens and read off its ids.
The search engine, one posting at a time
How a search engine finds and ranks documents. Press Next to analyze a corpus into tokens, build an inverted index, analyze a query, fetch the matching postings, compute idf from document frequencies, score each candidate with BM25 (term-frequency saturation + length normalization), and rank the results.
The spell checker, one candidate at a time
How autocorrect picks the right word. Press Next to take a misspelling, generate every word one edit away, filter to real dictionary words, identify each edit, weigh a language-model prior against an error-model channel, combine them into a posterior, and choose the correction — the noisy-channel model behind spell checkers.
Edit distance, one cell at a time
How far apart are two strings? Press Next to set up the two words, initialize the base case, learn the recurrence, fill the dynamic-programming grid cell by cell, read the distance in the corner, backtrace the cheapest path, and recover the alignment of edits.
Cosine similarity, one term at a time
How similar are two documents, regardless of length? Press Next to turn each document into a vector over a shared vocabulary, take their dot product, measure each magnitude, divide to get the cosine, and read off the angle between them — the similarity metric behind search and clustering.
The TF-IDF vectorizer, one weight at a time
How raw word counts become weighted vectors that know which words matter. Press Next to count term frequencies, measure each term’s document frequency, turn that into an idf weight (rare = high), multiply to get tf-idf, and normalize each document to a unit vector — ready for cosine similarity and search.
The regex engine, one state-set at a time
How a regular expression actually matches text. Press Next to compile the pattern ab*c into an NFA, take the ε-closure of the start state, then feed the input one character at a time — watching the set of active states advance through the b* loop until an accepting state is reached. Tracking a set (Thompson’s method) means matching in one linear pass, with no backtracking.
The autocomplete, one node at a time
How a search box finishes your word. Press Next to load a small dictionary, build a trie where words sharing a prefix share a path, type a prefix, walk down to its node, collect every word in that subtree, rank them by frequency, and show the top suggestions.
The diff, one cell at a time
How a diff finds what changed between two versions. Press Next to line up the two sequences, fill the LCS table, read the length of the longest shared subsequence, backtrace it, and turn the path into a diff of keeps, insertions and deletions.
The n-gram generator, one token at a time
How a Markov model generates text. Press Next to read a corpus, count bigrams, normalize them into next-word probabilities, view the transition table, sample the next word from a distribution, walk the chain, and read the generated text.
The string matcher, one comparison at a time
How KMP finds a pattern in linear time. Press Next to set up the pattern and text, build the LPS table (the prefix function), scan the text comparing characters, use the table to shift on a mismatch without moving the text pointer back, and find the match.
Naive Bayes, one log-probability at a time
How Naive Bayes classifies text. Press Next to read training documents, compute class priors, count words per class, turn them into smoothed likelihoods, take a test document, sum the log scores per class, and predict the most probable label.
The NER tagger, one token at a time
How named entities are extracted. Press Next to take a sentence, compute per-token features, assign BIO tags (B-/I-/O), group consecutive tags into spans, and read off the typed entities.
Softmax, one temperature at a time
How raw scores become a probability distribution. Press Next to start from logits, divide by a temperature, exponentiate, and normalize into probabilities — then use the temperature button to watch the distribution sharpen or flatten.
The topic model, one resample at a time
How latent topics emerge from raw co-occurrence. Press Next to load documents, posit K topics, give every word a random topic, build the counts, resample one word’s topic from the LDA probability, run many sweeps, and read the discovered topics.
Word2Vec, one update at a time
How words become vectors. Press Next to take co-occurrence pairs, scatter random vectors, run the skip-gram score, take a softmax + loss, update the vectors so co-occurring words move together, train to convergence, and find a word’s nearest neighbor.
The dedup, one signature at a time
How near-duplicates are found at scale. Press Next to take documents, build shingle sets, compute the true Jaccard, hash them into MinHash signatures, estimate the similarity from matching positions, band them with LSH, and surface the near-duplicate.
PMI, one pair at a time
How to detect phrases statistically. Press Next to read a corpus, count words and bigrams, form the marginal and joint probabilities, compute PMI for each pair, and rank them to surface the collocations.
Entropy, one symbol at a time
How information content is measured. Press Next to take a distribution, compute each symbol’s surprisal (−log2 p), weight it by its probability, sum to the entropy, and compare against the uniform maximum.
Perplexity, one token at a time
How well does a model predict text? Press Next to take a test sequence, read the model’s probabilities, turn each into surprisal, average to cross-entropy, exponentiate to perplexity, and compare a good model against a weak one.
Smoothing, one estimate at a time
How models avoid assigning zero probability. Press Next to see raw counts, the MLE estimate, the zero problem for an unseen word, the Laplace add-one fix, the general add-k, and how mass is redistributed from seen to unseen events.
Zipf & Heaps, one curve at a time
Two empirical regularities of text. Press Next to read a corpus, rank words by frequency, see Zipf’s law on a log-log plot, watch new words appear as you read more (Heaps), plot the vocabulary-growth curve, and interpret both.
LSA, one singular value at a time
How latent topics fall out of linear algebra. Press Next to build a term–document matrix, factor it with the SVD, inspect the singular values, truncate to the top few, and view documents in the resulting latent space where topics separate.
Hamming distance
When two strings are the same length, the simplest way to measure their difference is to count the positions where they disagree. That count is the Hamming distance. Flip the bits below and watch it move.
Edit distance, live
Edit distance is the fewest single-character insertions, deletions, and substitutions that turn one string into another. Type a word and watch the distance to kitten — and the exact operations — update on every keystroke.
Jaccard similarity
To compare two sets, divide the size of their overlap by the size of their union. That ratio — the Jaccard index — runs from 0 (nothing shared) to 1 (identical). Toggle which items belong to A and B and watch it respond.
Bag of words
The simplest way to turn text into numbers: forget the order and just count how often each word appears. The result is a bag of words — a vector of counts. Shuffle the sentence and the bag is unchanged; that is exactly the information it throws away.
and click any word above to drop it from the sentence.
One-hot vs dense vectors
How do you hand a word to a model? The naive way is one-hot: a vector as long as the vocabulary, all zeros except a single 1. It is huge and says no two words are alike. A learned dense vector is short, and its numbers place similar words near each other.
vocabulary size 16
Cosine vs Euclidean
Two ways to compare vectors. Euclidean distance is the straight line between their tips — it cares about length. Cosine similarity is the angle between them — it cares only about direction. Drag the purple vector and watch both react; text similarity almost always uses cosine.
Characters & code points
A string looks like letters, but underneath it is numbers. Each character is a Unicode code point; UTF-8 then encodes that number as one to four bytes — ASCII in one, accented letters in two, many symbols in three.
Strings as sequences
A string is an ordered sequence of characters with positions. You address a character by its index from zero, take a slice with a half-open range, and read its length. Drag across the characters to select a slice.
s[a:b] includes a, excludes b.s[0:k] and s[k:n] cover the whole string with no overlap.Hashing a string
A hash folds a whole string into one fixed-size number. A polynomial rolling hash takes each character in turn: multiply the running value by a base and add the next code, modulo a large number. Same string, same hash; order matters.
base 31
h = (h·base + code) mod M, left to right. The multiply makes position matter.The three edit operations
To measure how different two words are, count the single-character edits to turn one into the other. There are exactly three: insert, delete, substitute. Edit them yourself and watch the running count — these are the atoms of edit distance.
Whitespace, subword, character
Before a model sees text it is cut into tokens. Split on spaces and rare words break the vocabulary; split into characters and sequences grow long; subword tokenization keeps common words whole and breaks rare ones into reusable pieces.
Sentence segmentation
Splitting text into sentences sounds like “cut at every period” — until abbreviations and initials get in the way. A period both ends sentences and marks abbreviations. Click each period to decide, and watch the sentences regroup.
N-grams
An n-gram is a contiguous run of n tokens. Slide a window of width n across the text and each position emits one gram. Set n and move the window yourself to see unigrams, bigrams, and trigrams appear.
n = 2
Why subwords win
A whitespace vocabulary can never list every word — names, typos, compounds appear forever. Subword tokenization fixes a vocabulary of frequent pieces and spells any word from them, so nothing is ever truly unknown. Type a word and watch it decompose.
<UNK>).Case folding & normalization
Two strings can look identical yet be unequal to a computer — different case, or “é” written as one code point versus an “e” plus a combining accent. Edit both fields and watch when they match raw, after case folding, and after Unicode normalization.
Stemming vs lemmatization
To treat “runs,” “running,” and “ran” alike, reduce each to a base form. Stemming chops suffixes by rule — fast, sometimes wrong. Lemmatization returns the true dictionary form, even for irregulars. Type a word and compare.
try: running, ran, better, mice, happily
Stopwords
A few words — “the,” “of,” “is” — dominate any text yet carry little topical meaning. Classic pipelines drop these stopwords. Type your own sentence, and click any word to add or remove it from the stoplist.
Morphology
Words are built from morphemes — the smallest meaning-bearing units. A root carries the core; prefixes and suffixes bend it. Assemble a word from pieces and watch its structure — the same idea that makes subword tokenization work.
Exact match: the naive scan
The simplest substring search: line the pattern up at a position, compare left to right, and on a mismatch shift one step and start over. Drive the alignment yourself and watch it re-compare characters — the waste that smarter algorithms remove.
Regular expressions
A regular expression describes a set of strings: character classes say what kind, quantifiers how many, anchors where. Type a pattern and a test string, and the engine highlights every match live.
patterntext
\d digit · [A-Z] capital · . any · + one-or-more · * zero-or-more · ? optional.[A-Z][a-z]+ or \w+.Finite automata
A finite automaton has a few states and labeled transitions. Feed it characters and each moves it between states; if it ends in an accepting state, the string is in the language. This DFA accepts strings ending in “ab.” Type a string and step it through.
Wildcards & globbing
Globbing is the wildcard matching shells use for filenames: * is any run of characters, ? is exactly one. It is simpler than full regex and compiles straight into one. Type a glob and watch which files match.
try: data?.csv, *.*, report.*
* any number of characters · ? exactly one.*.txt → ^.*\.txt$. Matches below are computed that way.Embedding geometry
Learned word vectors put meaning into directions. Differences between related words line up, so you can do arithmetic on them: take king, subtract man, add woman, and you land next to queen. Click three words and watch the analogy resolve.
Dot product
The dot product multiplies two vectors into a single number: a·b = aₓbₓ + aᵧbᵧ. Geometrically it is the length of b’s shadow on a, times the length of a. Positive means they point the same way, zero means perpendicular, negative means opposed. Drag b.
Vector norms
A norm measures a vector’s size, and there is more than one. L2 is the straight-line length; L1 sums the absolute components (city-block distance); L∞ takes the largest component. Drag the vector and compare all three.
The inverted index
Search engines do not scan every document at query time. They build an inverted index once — a map from each term to the list of documents that contain it (its postings). A query just looks up those lists and combines them. Type a query and watch.
Precision & recall
When a system returns results, two questions matter: of what it returned, how much was relevant (precision)? And of all that was relevant, how much did it find (recall)? They trade off. Click documents to mark them retrieved and watch both move.
N-gram language model
A bigram model learns, from a corpus, how likely each word is to follow the last one. To generate text it just keeps sampling the next word from that distribution. Build a sentence yourself — click the next word from the live probabilities, or let it sample.
Bayes’ rule for text
A naive-Bayes spam filter starts from a prior belief and updates it with evidence. Each word in a message nudges the odds toward spam or ham by how much more likely it is under one than the other. Toggle which words appear and watch the posterior move.
Linear decision boundary
A linear classifier splits the plane with a straight line: everything on one side is class A, the other side class B. Drag the line’s endpoints to separate the two clouds of points and watch the accuracy climb — the same thing training does automatically.
Sentiment lexicon
The simplest sentiment analyzer keeps a dictionary of word polarities and adds them up: “great” is +3, “terrible” is −3. A negator like “not” flips the next word. Type a sentence and watch each word’s contribution and the running total.
BIO tagging for NER
Named-entity recognition is framed as tagging every token. The BIO scheme marks each one B (begins an entity), I (inside the same entity), or O (outside). Contiguous B…I runs become spans. Click tokens to tag them and watch the entities get extracted.
Part-of-speech tagging
Every word plays a grammatical role — noun, verb, adjective. POS tagging labels each one, and context decides: the same word can be a noun in one sentence and a verb in another. Tag the words yourself, then reveal the gold answer.
Document clustering (k-means)
Unsupervised clustering groups documents with no labels. k-means repeats two steps: assign each point to its nearest centroid, then move each centroid to the mean of its points. Drag the centroids or step the algorithm and watch the clusters settle.
Topic mixtures
A topic model says each document is a mixture of topics, and each topic is a distribution over words. Build a document by clicking words, and watch its topic proportions emerge from which topics those words belong to.
Keyword vs semantic search
Keyword search matches the exact words you type — so “puppy” misses a document about a “canine.” Semantic search compares meaning vectors, so paraphrases match even with no shared words. Type a query and compare the two rankings.
Attention weights
Attention lets each token look at every other and decide how much to borrow from each. For a chosen query token, it scores every token by similarity and softmaxes those scores into weights that sum to one. Pick a token and adjust the temperature to sharpen or flatten its focus.
T = 1.0