Skip to main content
Information Retrieval

Text Classification, Clustering, and Web Search

Published: 2026-09-13
Level: undergraduate
Audience: Undergraduate students studying Information Retrieval

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

  • Naive Bayes with Laplace smoothing and multinomial versus Bernoulli — covered in Lecture 10 (Text Classification with Naive Bayes and Vector Space Models)
  • Rocchio centroids with cosine similarity and nearest-neighbor voting — covered in Lecture 10 (Text Classification with Naive Bayes and Vector Space Models)
  • Term weights with TF-IDF and cosine similarity for ranking — covered in Lecture 2 (IR Models: Boolean, Vector, and Probabilistic Retrieval)
  • Precision, recall, F-score and accuracy for unranked evaluation — covered in Lecture 9 (Evaluation in Information Retrieval)

11.1 Bernoulli Naive Bayes Smoothing and Worked Numerical

11.1.1 Mathematical Formulation

A single zero can wipe out a whole document score. That risk is the reason smoothing exists, and it is the thread that ties this section together.

Why should one unseen word never decide the label on its own? A Naive Bayes score is a long product of small chances. A single zero factor forces the full product to zero, no matter how strong the rest of the proof is. Smoothing gives every word a small backup chance so rare events stay rare but never impossible.

Think of the two models with two everyday pictures. A multinomial Naive Bayes model is a bag of marbles where each draw is one word slot and repeats count. Pulling five Chinese marbles out of eight draws means something different from pulling one. A Bernoulli Naive Bayes model is a checklist where each word gets a tick for present or a cross for absent. The checklist never asks how many times a word rang the bell, only whether it rang at all. Remember the detective updating a hunch as clues arrive: the prior is the opening hunch, each word is a fresh clue, and absence of a clue is also a clue under the checklist view. The bag picture breaks for Bernoulli because repeats are thrown away; the checklist picture breaks for multinomial because absence carries no weight there.

A multinomial Naive Bayes model treats each document as a bag of token counts. An occurrence chance, written , is the chance of word in class . A prior chance, written , is the share of training documents in class before any word is seen. A smoothing value, written , is a small added count, taken as in this session. The symbol counts how many times word appears in training material of class . The symbol is the total count of word slots in class . The symbol is the number of distinct words in the vocabulary, written .

The smoothed multinomial estimate is built in three moves. Start from the raw share of slots:

Add one fake hit to every word so no numerator is zero:

Balance the books by adding the same fake mass to the denominator once per vocabulary entry. Summing the numerator over all words adds in total, so the denominator must grow by the same amount for chances over the vocabulary to still sum to one:

A concrete anchor used here was the word Chinese with five hits out of eight word slots, so before smoothing, and after smoothing with . The loop behind the denominator runs over every entry of the vocabulary while counting tokens. That loop is what puts the distinct-word count into the denominator and balances the extra added on top.

A Bernoulli Naive Bayes model asks only whether a word shows up or stays away. Presence maps to one and absence maps to zero. Here is the number of class- documents where word shows up at least once. The symbol is the number of documents in class , not the number of word slots. Each word is a coin with two faces, present or absent, so the smoothing mass added to the denominator is two per word, not the size of the vocabulary and not the number of classes.

With smoothing value , the Bernoulli estimate is:

With this becomes . The constant counts the two instances of the attribute: a word either shows up or does not show up. A three-class problem still uses two, because the two counts presence against absence of the token itself. Texts often write the same idea as directly; here we keep visible so the link to the multinomial form stays plain. The two formulas share one shape, add fake counts on top and balance them below, but they count different things, slots against documents, and they balance with different constants, against two.

Scoring a fresh document uses the posterior chance of each class, written . The posterior stays in proportion to the prior times the occurrence chance for words in the query times the non-occurrence chance for the rest:

Here is the vocabulary set and marks presence () or absence () of word in document . When the factor picks ; when it picks . Words in the query use their occurrence chance. Words missing from the query use the non-occurrence chance . The product form rests on an independence bet: each word trait is treated as standing apart from the rest, so separate chances may multiply. In practice the computation runs in log space as a sum of log chances, which keeps small products away from underflow and turns the winning class into the largest log score. Non-occurrence words count as real proof, which is the sharp split from the multinomial form where absent words drop out of the product.

Picture a bar chart with one bar per vocabulary word for a fixed class. Bar height is . The horizontal axis lists words, the vertical axis runs from zero to one. Smoothing lifts every zero bar a little off the floor and shaves a little off the tall bars so the total still sums to one. The takeaway in one line: smoothing trades a little sharpness on seen words for safety on unseen words. The same chart under the Bernoulli view has paired bars per word, present against absent, and the pair always sums to one.

Scope: Use the multinomial form when repeats carry signal, such as long reviews where saying good four times is stronger than saying it once. Assumption: Word slots are treated as separate draws given the class, which ignores word order and phrase meaning. Scope: Use the Bernoulli form for short texts or title-like data where presence matters more than count. Assumption: Presence of each word is treated as separate from the rest given the class, which is false for glued pairs such as peanut and butter but still works well in practice.

Do not swap the two denominators. Using in a Bernoulli task over-smooths and washes out the signal; using two in a multinomial task under-smooths and leaves the sum over the vocabulary below one. Do not read the two as the number of classes. A three-class setup still smooths each word with two outcomes, present or absent. Do not drop the non-occurrence factors in a Bernoulli score. Scoring only the query words throws away half the model and can flip the label.

11.1.2 Worked Examples

Example 1 — the word Chinese under the multinomial view. Five hits sat in eight word slots, with and a distinct-word count filling the denominator. Raw share first: . Smoothed next: . With a six-word vocabulary this is ; with a larger vocabulary the same numerator spreads over a larger denominator. Sense-check: smoothing pulls the raw 0.625 down because one fake hit per vocabulary word dilutes the seen count. The point of the example was contrast: here repeats matter, and counts distinct tokens across the text.

Example 2 — the word Chinese under the Bernoulli view. Take a class with three documents where the word showed up in the first, second, and third document, so and . With and two instances, the estimate is . Step by step: numerator counts documents with the word present plus one fake present, ; denominator counts class documents plus one fake present and one fake absent, . A word seen in none of the three documents would score , never zero. Sense-check: a word present everywhere still keeps a 0.2 absent chance in reserve, which is the price of never trusting a short training set fully. The same shape was stressed again and again: numerator counts documents with the word present, denominator adds two for the two instances.

Example 3 — the six-document query good nice in full. Nine tokens formed the vocabulary: good, excellent, nice, bad, terrible, poor, okay, average, fine. Three classes shared the six documents evenly: two positive, two negative, two neutral. The query held the words good and nice.

Priors came first. Each class owned two of six documents, so prior chance for each class is documents in class over all documents:

Occurrence chances came next for the positive class. The word good sat in both positive documents, so its smoothed chance was . The word nice sat in one positive document, so its smoothed chance was .

Non-occurrence chances followed. The word excellent sat in one positive document yet stayed out of the query, so its occurrence chance was , and its non-occurrence chance was . Six further words from the other classes never showed up in any positive document. Each had occurrence chance and non-occurrence chance . Since six such words existed, their joint factor was .

The posterior for the positive class multiplied prior, occurrence chances for good and nice, the non-occurrence chance for excellent, and the six shared non-occurrence factors:

Parallel products ran for the negative and neutral classes over the same nine slots, with their own document counts in each numerator. The lecture-reported unnormalized values were about for the positive class against about for the rival, so the query good nice landed in the positive class by a wide gap. Sense-check: good and nice both point at positive training material while the six rival words stay absent, so the positive product keeps large factors near 0.75 where rivals multiply small 0.25 factors. A follow-up task was set to run the multinomial classifier on the same data and to compare its label with the Bernoulli label, then to trace any split back to its cause. The multinomial form weighs repeats, while Bernoulli ignores repeats, so frequency effects are the prime suspect when labels differ.

Exam note: Run the multinomial classifier on the same good nice data and compare labels. When the two models disagree, look at repeats first. A word that appears many times in one short document can swing the multinomial score while leaving the Bernoulli score almost flat.

11.1.3 Student Questions and Answers

Q: For the word good, should the smoothing denominator add three for the three classes, giving something like two plus three?

A: No. The denominator constant is not about the class variable at all. It counts instances of the token: present or not present, only two outcomes. That is why the same three-class setup still uses two, and why the working equation writes the number two directly instead of a class count. Several students tripped on this link between class count and smoothing mass. The fix is to read the two as faces of one word coin, not as the number of classes in the task.

Body text bridges the two doubts. The first doubt mixed up two counts that sound alike: how many classes exist against how many faces one word has. The second doubt mixed up two stages that run back to back: table lookups against the final product.

Q: In the earlier Chinese example, were we finding the occurrence chance rather than the posterior?

A: Both stages existed. The table lookups were occurrence chances such as 4/5 or 3/4. Toward the end the prior joined them, and the posterior always brings together prior, occurrence chances of query words, and non-occurrence chances of the rest. If a line has no prior factor, it is a table entry; if it multiplies prior with present and absent factors, it is a posterior score.

Bernoulli smoothing adds one fake present and one fake absent per word, so the denominator adds two. The posterior multiplies the prior with present-word chances and absent-word chances over the full vocabulary. Exam note: Never write the class count into the smoothing denominator; write two for presence against absence.

Real use is close by. Short-message sentiment tools and spam filters often start from this checklist model because a single spam trigger word matters more than how many times it repeats in one short note. Longer news-topic engines lean multinomial because five mentions of Beijing carry more topic proof than one.

11.2 Rocchio Centroid Classification with TF-IDF

11.2.1 Mathematical Formulation

How do you sort documents when text has no numbers in it at all? The answer runs in three moves: turn words into weights, make long and short documents fair, then replace each class by its middle point.

A class with ten long essays should not outshout a class with two short notes just because it holds more words. Raw counts favour long documents. Weighting plus length fixing removes that unfair edge before any comparison starts.

Think of each class as a sports team photo. Each player is one document vector. The centroid is the spot where the team would balance if every player pulled with equal force. A new player joins the team whose balance point sits closest. The picture breaks when a team forms a ring instead of a huddle: the middle of a ring is empty air, and the average points at no one. That limit is why Rocchio suits round blobs and struggles with rings and chains.

A Rocchio classifier sorts documents by centroid, which is the average vector of a class. For a class with document vectors , the centroid is the centre of mass of its members. Here is the centroid vector of class , is the set of training documents in that class, and counts them. A fresh query vector goes to the class whose centroid sits closest, measured by Euclidean gap or, for length-fixed vectors, by the matching cosine score.

The spoken definition behind this line was centroid for the China class is D1 plus D2 plus D3 divided by three. Each slot of the centroid is the plain mean of that slot across members, with no extra fixing step on the centroid itself.

Raw text is unstructured data, so numbers must be built before any vector method can run. The chosen bridge was TF-IDF, the product of term frequency and inverse document frequency. Term frequency, written , counts hits of term in document . Inverse document frequency, written , down-weighs terms spread across many documents. With documents in the whole store and documents holding the term, the spoken form log of N by df renders as:

The log base was left unstated in the session. Reference material uses base 10 for its worked idf table and notes that the exact base does not change the ranking order, since changing the base multiplies every idf by one shared constant. Numbers below use base 10, so and ; any other base keeps every comparison in the same order. A constrained term-frequency variant one plus log TF also came up, rendered as , with smoothing as its motive: it damps the tenth hit of a word so it counts less than the first hit. The session set that variant aside for ease and used raw counts, with library code left to do the full form in real runs.

The TF-IDF weight of term in document is then:

A word found everywhere adds no split power. When , the ratio is one and , so every entry for that word becomes zero.

Vectors then pass through normalization, which divides each vector by its own length so long and short documents meet on fair terms. With length , the unit form is . A document with two unit entries has length , so each entry becomes . Converting all prices to the same currency is the matching everyday picture: after the fix, only direction matters, not document size.

The reason IDF for a test document still comes from training counts is that the training store defines the background rates. New words in a query borrow the document frequencies seen during training. A query never gets to vote on how rare its own words are.

Picture a scatter plot with one axis per word after fixing. Each document is one arrow from the origin to the unit circle. Long and short originals now end on the same circle, so the gap between arrow tips measures topic angle, not length. Class blobs form caps on the circle and each centroid arrow points at the middle of its cap. The takeaway in one line: weighting picks the telling words, fixing puts all arrows on one circle, and the centroid marks the middle of each team.

Scope: TF-IDF plus Rocchio suits topic classes with telling content words, such as China against non-China. Assumption: Classes form round, non-overlapping blobs in vector space, which is the contiguity bet. When classes form rings, stripes, or mixed patches, the middle point misleads. Assumption: Training background rates match query time rates, so borrowing training idf stays fair.

Do not normalize the centroid a second time. Member vectors are fixed to unit length, then averaged as a straight mean; fixing the average again would drag it back onto the circle and shift every boundary. Do not compute fresh idf on the test set. One query document cannot set background rates. Do not keep everywhere-words in the table out of habit. Their idf is zero, so they add work and no signal.

11.2.2 Worked Examples

Example 1 — the China against non-China set in full. Four training documents and one query document D5 fed the task. Documents D1, D2, and D3 belonged to the yes class and D4 alone formed the no class. Fix the vocabulary order as Chinese, Beijing, Shanghai, Macao, Tokyo, Japan. Term-frequency rows were:

  • D1: Chinese 2, Beijing 1, rest 0
  • D2: Chinese 2, Shanghai 1, rest 0
  • D3: Chinese 1, Macao 1, rest 0
  • D4: Chinese 1, Tokyo 1, Japan 1, rest 0
  • D5 query: Chinese 3, Tokyo 1, Japan 1

With , document frequencies are , and for each of Beijing, Shanghai, Macao, Tokyo, and Japan. So and for the other five terms. Every TF-IDF entry for Chinese became zero, which is exactly right: a word found everywhere adds no split power.

The word Japan had , so . Term hits were zero in D1, D2, and D3, one in D4, and one in the query D5, giving row values except at D4 and D5. Tokyo behaved the same way: at D4 and D5, zero elsewhere. Beijing, Shanghai, and Macao each had with , with their single hits on D1, D2, and D3 in turn.

Since multiplied every nonzero cell, the whole table was divided through by for ease, leaving a plain zero-one table in the fixed order above:

  • D1: 0, 1, 0, 0, 0, 0
  • D2: 0, 0, 1, 0, 0, 0
  • D3: 0, 0, 0, 1, 0, 0
  • D4: 0, 0, 0, 0, 1, 1
  • D5: 0, 0, 0, 0, 1, 1

Dividing by one shared positive constant keeps all gaps in the same order, so no label can flip. Documents with a single one kept length one. Documents with two ones, namely D4 and D5, took length , so each of their entries became .

Centroids closed the task. The yes-class centroid averaged D1, D2, and D3, leaving nonzero means only on the three early-class words, each . The no-class centroid equalled the lone D4 vector . The query D5 matched the no-class centroid exactly, so the shortest gap picked the negative class. Sense-check: after the everywhere-word drops out, the query shares no active slot with the yes centroid and both active slots with the no centroid, so the no win is forced.

11.2.3 Student Questions and Answers

Q: Should term frequency be a chance or a log form such as one plus log of the count, and how do we know which form a problem wants?

A: For classroom work the plain count is fine when ease matters. In a handwritten setting, pick the form you can handle, write the premise down, and solve without gaps. Library code in real runs uses the full proper form with log damping and smoothing. The marker rewards the written premise: it shows the idea is in place and only the arithmetic was shortened.

Body text links the next two doubts. Both ask what may be borrowed and what may be cut: background rates are borrowed, shared constants are cut.

Q: For test data, do we take IDF from the training counts?

A: Yes. Background frequencies come from the training store, and the query borrows those same IDF values. A single test line cannot reset how rare a word is in the collection.

Q: Why drop the log four factor across the table?

A: It multiplies every nonzero cell, so dividing the whole table by that one constant keeps all gaps in the same order. After that cut, fixing runs on the plain ones. The cut is safe only because the factor is shared and positive.

Q: Must the centroid itself be fixed like the documents?

A: No. The centroid is a plain average of its member vectors, such as one third each for three members, with no extra fixing step. Members are unit arrows; their average sits inside the circle by design.

Weight with TF-IDF, fix members to unit length, average directly for centroids, and send the query to the nearest centroid. Borrow training idf for the query and never fix the centroid twice.

Real runs hand the full TF-IDF form to library code, which adds log damping and smoothing without hand cuts. News-topic routing is a classic home for this pipeline: a stream of fresh articles meets stable class middles for sport, business, and world news.

11.3 Second Rocchio Example and Exam Technique

11.3.1 Worked Examples

A second Rocchio pass shows the hand-safe path: TF only, no fixing, plain Euclidean gaps. The point is exam craft as much as geometry.

When the ask names TF only, every IDF column is skipped work. Writing TF only, no fixing on the page takes seconds and protects the marks even if the arithmetic slips later.

Purpose: sort pet lines into dog against cat with the cheapest correct arithmetic. Inputs and outputs: four short training lines, two per class, plus the query white puppy go in; one class label comes out. Term-frequency rows are the only weights. No IDF column is built and no vector is fixed to unit length.

Steps run in order. Build one count row per line over a fixed shared word set. Average the two dog rows for the dog centroid and the two cat rows for the cat centroid. Score the query against each centroid with plain Euclidean distance, the square root of summed squared gaps, and hand the query to the nearer middle point.

Example 1 — dog against cat with query white puppy, traced end to end. Fix one vocabulary order for the whole trace: cute, puppy, white, fluffy, kitten. The spoken centroid digit strings in the recording were unclear, so the slot order below is fixed once here and used throughout; the method and the averaging pattern match the session, not a word-for-word read-off of garbled digits.

Training rows in TF units:

  • Dog D1 cute puppy: 1, 1, 0, 1, 0
  • Dog D2 cute fluffy: 1, 0, 0, 1, 0
  • Cat D3 white kitten: 0, 0, 1, 0, 1
  • Cat D4 white puppy kitten: 0, 1, 1, 0, 1
  • Query white puppy: 0, 1, 1, 0, 0

Dog centroid is the plain mean of its two rows:

Cat centroid is the plain mean of its two rows, which is the halved pattern noted in the session:

Gaps use Euclidean distance over the five shared slots. Against the dog centroid:

Against the cat centroid:

The nearer centroid claims the query, so white puppy lands with cat on these rows. No fixing ran in this pass. Sense-check: the query shares white with the cat side and fluffy with the dog side absent, so the cat middle point sits closer. The stated exam move was to write that choice down as a premise: TF only, no fixing, for speed. That written line shows the marker that the idea is in place and only the arithmetic was shortened.

Picture two middle points on a flat sheet with the query dot between them. The dog point sits toward the cute-fluffy corner, the cat point toward the white-kitten corner, and the query dot falls inside the cat half of the sheet. The boundary is the line of points at equal gap from both middles. The takeaway in one line: middles plus nearest-gap rule is the whole classifier.

Read the ask with care. A request may say TF only, TF-IDF, or neither. Computing IDF when only TF was asked burns time for zero gain, and a handwritten paper rewards the cheaper correct path. Name the gap too: Euclidean is the default here, while Manhattan is the lighter hand choice when the ask leaves the measure open.

Do not mix fixed and raw rows in one table. Either fix every member row or fix none; a half-fixed table compares arrows of different lengths. Do not fix the centroid after averaging. The centroid is already the mean and stays where the mean falls.

Exam note: TF only means skip IDF, write the TF and fixing premise on the page, build count rows, average per class, and score with Euclidean gaps. Exam note: When the ask leaves the gap open, Manhattan keeps hand arithmetic short; name the choice and go.

Hand Rocchio of this size also lives in support ticket routing: a fresh ticket meets the middle of each queue by word counts and joins the nearer queue.

11.3.2 Student Questions and Answers

Q: Why is nothing normalized in this dog and cat run?

A: Normalization was skipped to keep the arithmetic light. Either path is valid when the premise is written out, so state TF only and no normalization, then solve. The written premise is the proof that the shortcut was a choice, not a gap in knowledge.

The dog-cat run bridges the full TF-IDF pass and the neighbour vote next: same rows, cheaper weights, same nearest-middle logic before voting takes over.

11.4 K-Nearest Neighbour Classification of Text

11.4.1 Mathematical Formulation

Why train at all when you can just ask the neighbours? That question opens this method, which stores almost everything and decides at test time.

A test document should share the label of the training documents crowded around it in its local patch. Neighbours that use the same words are probably about the same thing. The vote of the local crowd beats one far-away average.

Think of a new family moving onto a street. To guess which school their kids will join, ask the three nearest houses, not the town average. If two of the three nearest send kids to the north school, bet north. The street picture breaks when streets mix: one odd house in a mixed block can tip a small vote, which is why the size of the voting crowd matters.

A K-nearest neighbour classifier, shortened to KNN, skips training almost fully. It stores the processed training vectors, and at test time it measures gaps between the query and every stored vector, then lets the closest neighbours vote. The guiding contiguity hypothesis says documents in one class form a continuous patch with no overlap from other classes, so a test point deep inside a patch should take the patch label. The letter , a hyperparameter (a setting fixed before testing, not learned from data), fixes how many neighbours vote.

Training holds two duties: process and store the vectors, and fix . Testing holds the costly duty: score the query against the store and assign the majority label. That test-time cost is the known price, accepted because the method often beats Naive Bayes and Rocchio on real collections with odd shapes. Small training stores and cases where sample counts sit far below feature counts still suit Naive Bayes well, while larger stores favour neighbour voting.

Distance usually means Euclidean distance between query and document over shared slots :

Each slot gap is squared, squared gaps add, and the root brings the total back to length units. When a problem leaves the measure open, Manhattan distance, the sum of absolute gaps , is the lighter hand choice. Manhattan skips squares and roots, so hand arithmetic stays short. For length-fixed vectors the same choice can be read as a cosine score; for raw TF rows the gap forms above are the working tools.

Picture the China blobs from the last section, now with no middle points drawn. The query dot sits inside a yes patch with D1 and D2 close by and D4 far off in its own corner. Circles around the query with radius to the first, second, and third neighbour each catch a voting crowd. The takeaway in one line: patches plus local votes replace middles.

Scope: KNN suits large stores and bent class shapes where one middle point per class misleads, such as topics with several word styles. Assumption: The local patch around the query holds the right label, which fails near mixed borders and in thin regions with few stored points. Assumption: Stored rows use the same weights and fixing as the query; mixing raw and fixed rows bends every gap.

Side-by-side contrast helps here. Rocchio keeps one middle per class and scores gaps per query, which is fast but stiff. KNN keeps every row and scores gaps per query, which is slow but bendy. Naive Bayes keeps chances per word and scores products, which is fast and strong on small stores. Pick middles for speed on round topics, votes for shape on big stores, chances for small stores.

Do not let grow past the local patch. A huge pulls in far recipes from other topics and drowns the local signal. Do not use for a two-class vote without a tie rule: two neighbours can split one-one, so odd values or a stated tie rule keep the label defined. Do not forget to turn text into rows first; voting on raw strings is not defined.

11.4.2 Worked Examples

Example 1 — the same China set under one, two, and three neighbours. TF rows with no IDF fed the vote, in the same vocabulary order as the Rocchio trace. The query met each of the four training rows through Euclidean distance: square each slot gap such as or , add them, and take the square root. The spoken arithmetic named gaps of that exact kind, for instance a slot with query count 3 against a training count 2 gives gap 1 and squared gap 1, while a slot with 1 against 0 gives the same.

Ranking the four gaps put D1 and D2 nearest, then D4, then D3. Voting then ran three ways. With the single nearest row was a yes document, so the label was yes. With the two nearest rows were D1 and D2, both yes, so the label stayed yes. With the three nearest rows were D1, D2, and D4, giving votes yes, yes, no, so the majority still said yes. All three settings agreed on this data. Sense-check: the query sits deep in the yes patch, so widening the crowd from one to three still cannot pull in enough no votes to flip the call.

Example 2 — practice task with TF and no IDF. The method repeats: build count vectors, score the query against every row, rank the gaps, and read the majority label at the requested . Take a tiny check with query row and stored rows A yes, B no, C yes. Euclidean gaps are , , . With the tie between A and C needs a stated rule such as lowest index, and both point yes; with the vote is yes, no, yes, so yes wins. Sense-check: the two yes rows hug the query on the first slot while the no row sits two steps away. The only fresh skill against earlier neighbour classes is the first move, which turns text into rows before the familiar voting starts.

Exam note: When the gap measure is missing from the ask, Manhattan keeps hand arithmetic short. Name the choice and go. Write TF only and the fixing choice on the page next to it.

11.4.3 Student Questions and Answers

Q: What is new here against the neighbour method already seen in other classes?

A: The voting itself is old. The fresh move is bringing structure to text first with term-frequency rows. Once rows exist, the rest is the familiar nearest-neighbour routine: score, rank, vote. Students who try to vote on raw strings stall; students who build rows first move fast.

Store rows, fix , score every gap at test time, and let the local crowd decide. Small trusts the very nearest; larger smooths noise but risks pulling in far topics.

Ticket triage at scale is a natural home: a fresh ticket meets thousands of old tickets and takes the label of its closest past cases, even when each queue holds several writing styles.

11.5 Judging Classifiers

11.5.1 Mathematical Formulation

A classifier that brags about one number is hiding the rest of the story. This section builds the full scorecard: one table, four cells, and the scores that read it.

Why is raw right-rate not enough? A rare-disease test that always says no scores 99 percent right and catches zero patients. High accuracy can mask total failure on the rare class. Precision and recall expose what accuracy hides.

Think of airport screening. True positives are banned items caught, true negatives are safe bags waved through, false positives are safe bags pulled aside, and false negatives are banned items that slip through. Catching everything means pulling many safe bags aside; waving everyone through means missing threats. The trade between alarms and misses is the whole game.

A confusion table (also called a contingency table) lays actual labels against predicted labels. Its four cells are true positive (actual yes, predicted yes, written TP), true negative (actual no, predicted no, written TN), false positive (actual no, predicted yes, written FP), and false negative (actual yes, predicted no, written FN). Rows fix what was true; columns fix what was called.

Accuracy is the share of all calls that came out right:

Accuracy can mislead on skewed data, so precision and recall split the story. Precision asks how many predicted yes calls were truly yes: of all bags pulled aside, how many held threats. Recall asks how many actual yes cases got caught: of all threats in the stream, how many were stopped. With the cell names above:

Take a tiny table: TP 8, FP 2, FN 4, TN 86. Accuracy is . Precision is . Recall is . The 0.94 headline looks strong while recall shows one third of threats slip through. That split is why skewed tasks quote precision and recall, not accuracy alone.

Pushing one of the pair usually hurts the other, which is the classic trade-off. A strict caller raises precision but drops recall; a lax caller raises recall but drops precision. Their harmonic mean, called the F1 score, blends them into one number:

The harmonic mean punishes lopsided pairs more than a plain average. With precision 0.8 and recall 0.667, F1 is , below the plain average 0.733 and far below accuracy 0.94. Equal weights sit inside this form; tasks that prize catches over false alarms weight recall more, and tasks that prize clean alarms weight precision more.

A receiver operating curve watches the trade across all thresholds. It plots true positive rate against false positive rate:

True positive rate is recall under another name: threats caught. False positive rate is safe bags pulled aside per safe bag in the stream. Each threshold gives one dot; sweeping the threshold draws the curve from the lax corner to the strict corner.

Picture the unit square. The horizontal axis runs from zero to one false-alarm rate, the vertical axis from zero to one catch rate. A random ranker traces the diagonal: catching 30 percent of threats costs 30 percent false alarms. Good rankers bow the curve toward the top-left corner, catching most threats at tiny false-alarm cost, and the area under the curve grows as the bow strengthens. The aim is to push that area as high as it can go, with the top-left corner as the ideal. Area 0.5 reads random; area near 1.0 reads near perfect.

Scope: Accuracy suits balanced classes with equal miss costs. Assumption: Skewed data or uneven costs break that premise, so quote precision, recall, F1, or the curve instead. Spam filtering prizes precision because false alarms burn trust; disease screening prizes recall because misses cost lives.

Do not swap the two rates on the curve axes. Horizontal holds the false positive rate and vertical holds the true positive rate; swapping them mirrors the story and misreads the ideal corner. Do not average precision and recall with a plain mean when one side collapses; the harmonic blend is the honest single number.

11.5.2 Student Questions and Answers

Q: Which quantity sits on which axis of the receiver operating curve?

A: The horizontal axis holds the false positive rate and the vertical axis holds the true positive rate. The curve climbs as true hits rise for each false-alarm level, which is why the top-left corner is the target. Read left to right as the caller turns lax: both rates rise together, and the better ranker rises faster.

Accuracy counts all right calls; precision counts clean alarms; recall counts caught threats; F1 blends the pair; the curve watches the trade across thresholds. On skewed data, lead with precision, recall, and the curve, not accuracy alone.

Spam triage uses precision to protect the inbox from false blocks, while outbreak screening uses recall to catch every case for follow-up. Both quote the same four cells and read different corners of them.

11.6 Clustering Foundations

11.6.1 Core Ideas

Labels cost money; raw text is free. Clustering is what you do when the answer tags never arrive.

Why group without answers? Large text stores often arrive with no ground truth at all. Hiring readers to tag millions of pages is slow and costly. Groups must be read out of the data itself, then checked with care before anyone acts on them.

Clustering groups data with no class labels to learn from, which is the unsupervised setting (learning without answer tags). No gold answer sheet exists to check against, so groups must be read out of the data itself. Text without tags is a natural fit: large stores often arrive with no ground truth at all. Supervised sorting from earlier sections asked which shelf a tagged book joins; clustering walks into an untagged warehouse and decides how many piles exist and what belongs together.

The goal is easy to state. Points inside one group should sit close together, which is low intra-cluster distance (small gaps within a group) or high inner density. Groups should sit far apart, which is high inter-cluster distance (large gaps across groups) or high separation of densities. Whatever method runs, hitting both marks at once counts as success. Tight huddles far apart read well; loose clouds that bleed into each other read poorly.

The first hard question is how many groups, , the data really holds. The elbow method is the book path: run the grouper for and beyond, plot the error on the side, and look for the bend where fresh gains flatten out. Picture error on the vertical axis against on the horizontal axis: the curve drops fast at first, then the slope flattens at the bend like an arm. That bend marks the near-best . Small under-splits real groups; huge chops one real group into slivers for tiny gains. Other paths named were Jaccard similarity (overlap of sets as a score, shared members over all members) and normalized mutual information (shared information between two groupings, scaled to a fixed range). The price of the elbow path is reruns: the method must run again and again until successive errors barely move.

The second hard question is naming. Geometry may show three blobs, yet only a later check with domain knowledge tells whether three real groups exist. A patient example made the point: one blob could be stage one cases, a second blob stage two cases, and a tiny third blob patients sliding toward stage three. Or the tiny blob could belong inside stage two, leaving two groups. Or hidden splits could push the count to four. Method output plus metadata and expert review must agree before the count is trusted. Geometry proposes; experts dispose. Treating blob count as truth without that check is how treatment groups, fraud rings, or news topics get misread.

A hard grouping puts each point in exactly one group. Fifth-grade against sixth-grade pupils was the picture: no pupil sits in both grades at once. K-means gives hard groups. A soft grouping lets points belong on both sides. The picture was two commentators who are both cricketers and politicians at once. Expectation maximization (a fit-and-reassign loop that softens membership) gives soft groups by scoring fractional membership per point and retuning centres by expected pull. Remember the grade pupils for hard borders and the double-role commentators for soft shares; the same person can be mostly one role with a real foot in the other.

Scope: Hard grouping suits disjoint duties such as grade levels or single-topic filing. Soft grouping suits overlapping roles such as multi-topic articles or mixed audiences. Assumption: Gap or density scores mirror real meaning, which holds only when the chosen distance matches the task. A bad distance invents blobs that mean nothing.

Picture three blobs on a sheet: two big clouds and one tiny patch between them. The tiny patch could be its own group, a bridge, or noise. Error-against- bends near three, but the naming choice still needs metadata. The takeaway in one line: geometry counts shapes while people confirm meanings.

Do not trust the elbow bend alone. Flat curves, double bends, and noisy reruns all blur the bend; pair the bend with metadata and reruns. Do not hand soft data to a hard method without thought. Forcing overlapping commentators into one grade each hides the overlap the task needs.

11.6.2 Student Questions and Answers

Q: What gap idea sits at the heart of grouping?

A: The within-against-between gap. Within-group gaps should stay small while between-group gaps stay large, measured as distance or as density. Dense patches far apart pass; loose clouds that touch fail.

No tags means no answer sheet: keep within gaps small, between gaps large, pick at the bend, confirm names with experts, and match hard or soft output to the real roles. Patient staging needs expert review of group counts before any treatment meaning is attached.

News engines group fresh stories without tags so readers can browse events, and inboxes group threads the same way. Both start untagged and earn trust only after human checks.

11.7 K-Means Algorithm Step by Step

11.7.1 Mathematical Formulation

Averages can sort data on their own if you let them move. That moving-average loop is the whole method.

Why start with middles instead of borders? Borders in high space are hard to draw, but middles are easy to average. Assign each point to its nearest middle, move each middle to its new crowd, and repeat. Borders emerge on their own halfway between middles.

Purpose: split points or count rows into tight groups with one middle per group. Centroid here means the mean of a group, the same centre of mass met in Rocchio. For points in group with centroid , the centroid is the slot-wise mean of its members. Distance scoring sits on top, but the mean is the core object.

Here is group , counts its members, and the sum adds vectors slot by slot. A small number sketch fixed the mean idea. With , , and in one group, the centroid is:

Each slot adds its member values and divides by the member count of three. First slot: , over 3 gives 2.67. Second slot: , over 3 gives 4.33.

Inputs and outputs: plus the point set go in; member lists plus centroids come out. Steps: pick starting centroids, score every point against every centroid and hand each point to its nearest centroid, rebuild each centroid as the mean of its new members, then repeat the score-and-rebuild cycle. Stop rule: close when two back-to-back rounds change neither the member lists nor the centroid spots. One side shifting would move the other, so stillness on both sides means the run has settled. In code this loop is only a few lines: seed, assign, refresh, repeat until calm.

Picture points on a sheet with red and blue flags for centroids. Round one draws borders halfway between flags and colours each point by its nearer flag. Flags then jump to the middle of their new colour crowds, borders tilt, and colours update. The takeaway in one line: flags pull points, points pull flags, until neither moves.

Scope: K-means suits round blobs of like size under Euclidean gaps. Assumption: is known or guessed from the bend, starts are given, and gaps are Euclidean on comparable slots. Rings, chains, and wildly uneven blobs break the round-blob bet no matter how long the loop runs.

Do not stop after one round. One pass only shows the first pull; only a second round with matching members and matching middles proves calm, with a third round as backup when wobble remains. Do not hand documents to the largest gap. Each document joins the centroid with the minimum gap; largest-gap assignment builds inside-out groups.

11.7.2 Worked Examples

Example 1 — five points with red and blue starts, traced. Five points A, B, C, D, E fed the run with two starting centroids, one red and one blue. Round one scored red against all five points and blue against all five. Point C sat nearer red than blue, so A, B, C joined the red group and D joined the blue group, with the fifth point joining its nearer side on the same minimum-gap rule. Fresh centroids followed as member means: add each slot across the new members and divide by the new member count. Round two rescored everything against the fresh spots. Membership and centroids came back unchanged, so the run closed with group one holding A, B, C and group two holding the rest. Sense-check: unchanged members force unchanged means, and unchanged means force unchanged members, so the loop has no move left.

Example 2 — text version over fly, eagle, go. Three distinct words in all fixed the slots as fly, eagle, go. The request used TF only, with no IDF and no fixing, under Euclidean distance. Starting centroids came from the data itself: document one as the first centroid and document three as the second, exactly as the question framed it. Term-document rows counted hits of each word per document. Where fixing runs, lengths follow the unit rule: a row with two ones has length , so each unit entry is . Hand runs under the TF-only premise skip that fix and score raw counts. Each centroid then met every document through Euclidean gaps. The smaller of the two gaps owned each document: documents one, two, and four joined the first group, while documents three and five joined the second. Member means then gave the first true centroids on the plane: add the three member rows slot by slot and divide each slot sum by three for the first group and by two for the second. One round is never enough to stop: only a second round with matching centroids and matching members lets the run close, with a third round as backup when wobble remains. Sense-check: fly-heavy lines huddle at one middle while eagle-go lines huddle at the other, so the split mirrors word use.

Exam note: When the ask leaves the gap measure open, Manhattan distance keeps hand work short: sum of absolute slot gaps with no squares or roots. When TF only is asked, skip IDF and write that premise down with the fixing choice.

11.7.3 Student Questions and Answers

Q: Do we take the smallest or the largest centroid gap when handing out documents?

A: The smallest. Each document joins the centroid with the minimum gap. Think of the nearest flag, not the farthest.

Body text bridges the two doubts. The first doubt fixes the direction of the assignment; the second fixes what the halving meant.

Q: The neighbour task divided something by two. Do we do the same here?

A: No. That halving was length fixing. Fix only when the ask calls for it. Notebook runs in Python automate the full flow and fix when the data and the problem call for it. Hand runs skip it when the ask says TF only.

Seed, assign to the nearest middle, refresh middles as means, repeat until two calm rounds in a row. The mean sketch is the unit move; everything else is repetition.

Store layouts use the same loop: nightly baskets meet middles and each basket joins its nearest buying pattern.

11.8 Initial Centroids and Cluster Quality Scores

11.8.1 Core Ideas

Good middles are not handed over with the data. Bad starts can trap the whole run, and no answer sheet exists to cry foul.

Why do starts matter so much? The loop only walks downhill to the nearest valley. A bad start drops it into the wrong valley, and every later step defends that valley as if it were home. Starts pick the valley; the loop merely walks to its floor.

Picture one dataset run twice. With lucky seeds the run settled into the expected three groups by the sixth round. The same data with unlucky seeds still looked wrong at the fifth round: one true group had split in two while two true groups had merged into one, with no known count of further rounds to repair it. More rounds cannot promise escape because each round deepens the current valley. The fix must come from better starts, not longer walks.

Three workarounds were laid out. First, rerun many times from fresh random seeds, a brute-force path with an open bill since the settling point stays unknown. Keep the tightest run by score. Second, run a hierarchical grouping first (a tree-building grouper, bottom-up merging or top-down splitting) and read its dendrogram (the merge tree). A high tree cut reads fewer groups, such as one branch against the rest for two groups. A lower cut across three branches reads three groups. The cut sets the seed count with proof behind it, and branch middles seed the flat run. Third, seed more centres than the elbow count: if the bend says five, open with six, seven, or ten, watch for over-splitting or under-splitting, and trim back to the count the splits support. Extra seeds catch small true groups that one-per-guess starts miss; empty or twin seeds then merge away. No single foolproof path exists, so each problem earns its own fix.

Judging a finished grouping without answer tags leans on the centroids as stand-in truth. The sum of squared errors, shortened to SSE, adds each point's gap to its nearest centroid across the whole store. Per-group subtotals add into one grand total:

Here is group and its centroid. The inner sum scores one group; the outer sum adds groups. Squaring punishes far strays more than near wobbles, so tight huddles score low. Smaller totals mean tighter groups, so runs compete downward. The residual sum of squares follows the same sum-of-squared-gaps idea over the vectors and likewise aims low. The two read as one and the same in practice. A numeric anchor was given: a five-group run scoring beats a three-group run scoring , so five groups would be kept. The same score also picks : plot SSE against and read the bend where extra groups buy little extra tightness, matching the elbow path from the foundations section.

Example — SSE on a toy line plus the five-group anchor. Work the score on a toy line to fix the moves. Centroids at 0 and 10, points 1 and 2 near the first, point 11 near the second. Gaps are 1, 2, and 1; squares are 1, 4, and 1; per-group subtotals are and ; grand total SSE is 6. A rival grouping that drags point 2 across to centroid 10 scores on that point alone and loses at once. Sense-check: one far move dominates the total, which is why strays decide contests. The session anchor compared two full runs the same way: a five-group run scoring beats a three-group run scoring , so five groups would be kept.

Picture SSE against falling fast then flat. At the total is huge, at much lower, at lower still at 0.7 against 0.8 at three. Past the bend the curve crawls because new middles split true groups for crumbs. The takeaway in one line: starts pick the valley, SSE scores the valley floor, and the bend prices extra middles.

Scope: SSE suits round blobs under Euclidean gaps with comparable slots. Assumption: Centroids stand in for truth, which fails for rings and chains where the middle sits in empty air. SSE always falls as grows and hits zero when each point gets its own middle, so never pick by raw minimum alone; read the bend or price complexity.

Do not rerun once and trust it. One start is one valley; several starts plus the best SSE is the working habit. Do not cut the tree at one height and stop thinking. High cuts merge, low cuts split, and only the bend plus domain sense sets the height.

11.8.2 Student Questions and Answers

Q: Can the squared-error score be shown on a small example?

A: List the centroids, list the points near each one, score each point-to-centroid gap, square and add within each group for per-group subtotals, then add the subtotals. The grand total is the score, and the smaller total across candidate group counts wins. The toy line above follows exactly these moves: gaps 1, 2, 1 become squares 1, 4, 1, subtotals 5 and 1, total 6.

Lucky seeds settle by round six while unlucky seeds still split and merge at round five. Rerun from fresh seeds, or seed from a tree cut, or overseed past the bend, then keep the lowest SSE at the bend. A five-group 0.7 beats a three-group 0.8.

Ad platforms use the same habit: many seed sets overnight, one SSE contest in the morning, and the tightest audience map goes live.

11.9 Other Clustering Families and Picking the Right Tool

11.9.1 Core Ideas

One shape bet cannot fit every dataset. This section tours the other bets and the rule for matching tool to setting.

Why keep more than K-means? K-means bets on round blobs around middles. Rings, trees, networks, and overlapping bells all break that bet. Each family below bets on a different shape, and the right bet follows the data, not habit.

Many groupers exist beyond K-means, and each leans on its own shape bet. K-means expects neighbours to clump in blobs around means under Euclidean gaps. A K-medoids grouper swaps the mean for the medoid (the most central actual member), with partitioning around medoids, shortened to PAM, as the named routine. Medoids resist strays because the centre must be a real member, not a pulled mean; the price is higher cost on big stores. Hierarchical groupers expect tree-shaped merges and offer four gap readings: minimum gap, maximum gap, average gap, or centre-to-centre gap, each giving its own variant. Minimum gap chains neighbours dot-to-dot and can snake; maximum gap keeps groups tight and round; average and centre readings sit between. DBSCAN (a density grouper that grows groups from thick patches) expects thick patches of neighbours and names three roles: core point (a point with enough neighbours in reach), border point (a reachable point too thin to grow from), and noise point (a point left out). Reachable core points keep joining until the thick patch ends, so rings and trails group by linkage, not roundness.

The four-circle picture showed the density bet at work. Dots chained dot-to-dot across each ring, so each ring read as one group even though no round blob existed, giving four groups in all. K-means would plant middles in the empty centres and slice rings into wedges; the density rule instead walks each ring and keeps it whole. Further families were named in quick tour form: OPTICS (a density ordering method that ranks points by reachability for many thresholds at once), minimum spanning tree grouping (a graph-link method that cuts long links), spectral grouping (a graph-cut method that slices weakly joined sheets), and node-link science methods Louvain, Leiden, and WalkTrap plus Newman-style community reading. In the WalkTrap picture a random walker treads some paths far more often than others, and the heavily trodden node sets become groups. Walkers linger inside tight knots and rarely cross thin bridges, so tread counts expose knots.

Matching tool to setting was the closing moral. Peak-hour ride grouping over a trip network calls for a network method, since raw closeness misses the link structure: two stops may sit near on the map yet share no direct route. Shopping-pattern mining over buyer similarity calls for gap-based methods such as hierarchical grouping or K-means: baskets with shared items sit near in count space and blobs mean taste groups. A Gaussian mixture model (a soft grouper that fits overlapping bell shapes with an expectation maximization loop) came up from the floor as the soft option: it scores each point's chance under each group and tunes centres by expected likelihood, which helps when groups overlap. That soft scoring has been used in software-testing data analysis, where failing runs blend causes instead of sitting in one hard box.

Scope: Gap methods suit blob data with honest distances; density methods suit trails and rings with even thickness; network methods suit linked data with routes and knots; soft mixtures suit overlapping bells. Assumption: The shape bet matches the data. A density rule on thin, uneven patches shreds groups into noise; a network rule on plain baskets invents links that mean nothing.

Picture a choice grid: rows are data shapes, columns are tools, and only the matching cells light up. Blobs light K-means and medoids; trees light hierarchical cuts; rings light density walks; graphs light Louvain, Leiden, and WalkTrap; overlaps light mixtures. The takeaway in one line: name the shape first, then lift the tool.

Do not hand a network problem to a gap tool. Map nearness without routes groups the wrong stops. Do not hand overlapping bells to a hard tool and trust the borders. Hard cuts through overlap hide the blend the task needs.

Exam note: The numerical ask for grouping stays limited to K-means. Hierarchical and density methods live as background from earlier courses, not as hand-worked problems. Quote them for setting matches, not for arithmetic.

11.9.2 Student Questions and Answers

Q: Are the fancier groupers such as the density scan still worth knowing?

A: Yes. Each method lands well only on its own kind of problem. Learn the setting first, then pick the method whose shape bet fits: network tools for network problems, gap tools for similarity problems. The four rings are the proof: blobs tools slice them while the density walk keeps them whole.

Body text bridges the two doubts. The first doubt asks whether background tools matter; the second asks when softness pays.

Q: When does a mixture model with expectation maximization earn its keep?

A: When groups overlap and hard borders feel forced. The model fits a bell shape per group, scores soft membership chances per point, and retunes centres through the expectation maximization loop. Overlapping test causes are the home case: each run gets a share under each cause instead of one forced tag.

Blobs take K-means or medoids, trees take hierarchical cuts, rings take density walks, networks take Louvain, Leiden, or WalkTrap, and overlaps take mixtures. Match shape to tool and the groups read themselves.

11.10 Why Web Search Is Harder Than Classical Retrieval

11.10.1 Core Ideas

A tidy library and the open web both answer queries, but only one of them fights spam, money, and endless change at once. This block follows Chapter 19 of Introduction to Information Retrieval by Manning and co-authors, the same book source as the rest of the block.

Why does the same query engine behave so differently on the web? Classical stores are curated and cooperative: known collectors, known formats, stable contents. The web holds billions of pages, both static and moving, from finest writers to spammers, with mixed motives and mixed quality. Scale, drift, and deceit arrive together.

That heterogeneity (mixed origins, mixed motives, mixed trust) breaks the tidy-collection bet. One index must hold peer papers, shop fronts, rants, and traps side by side and still rank with a straight face. No single style, length, or quality rule fits all corners.

A gene query showed the mix. The query BRCA1, a gene widely studied for breast cancer, pulls peer-reviewed papers, recorded patents on the gene, pharmacy adverts, and casual explainers into one result list. One short string returns science, commerce, and chatter side by side. The engine cannot wish the adverts away; it must rank proof above pitch without pretending the pitch is absent.

Four puzzles follow for any engine builder. How does one index a store that huge. How does one attach a trust score to each page. How does one cope with a collection that never sits still. How does one handle repeats and near-repeats. An index here means the stored page collection behind the engine, like the word index at the back of a book: look up a word and jump straight to its pages instead of scanning the whole book. Remember the back-of-book jump the next time crawl size feels abstract: without the jump, every query scans billions of pages.

Money pressure is the last twist. Search owners need brand income, yet brand weight must not bend ranked results. The first-generation paid engine GoTo, dated 1996 in the session, ranked results purely by advertiser bids, which put revenue first and relevance second. GoTo ranked purely by bid money. The second-generation answer, Google, split the page strictly: ranked results on one side from search merit, adverts on a separate side ordered by money but never mixed into the ranked list. Google keeps ranked results apart from paid adverts. The open policy question is how much brand bend, if any, a results list may carry, with zero bend as the ideal. Trust dies fast once users sense bids inside the rankings.

Picture a market street against a library hall. The hall holds tagged shelves that rarely move; the street holds shouting stalls that open, copy each other, and vanish by night. The takeaway in one line: the web is a street, not a hall, so ranking must weigh trust and freshness alongside topic match.

Scope: Classical tricks carry over for matching words to pages, but trust scoring, drift handling, and repeat filtering are web-first duties. Assumption: A static, honest, fully seen collection underlies classical guarantees; drop that premise on the web and add defences instead.

Do not rank bids as relevance. Paid order belongs in marked advert slots, never inside the ranked list. Do not treat a gene query as single-intent: papers, patents, pills, and primers share the string and the ranker must serve proof first.

11.10.2 Student Questions and Answers

Q: If brands fund the engine, should bid money not set the ranking?

A: Ideally never. Income may order the advert slots, but the ranked results must stand on search merit alone, or users lose trust in the list. Zero bend is the target; any bend needs a marked slot and an honest label.

Huge, mixed, drifting, copied, and paid: those five forces split web search from classical retrieval. Index at scale, score trust, track drift, kill repeats, and keep bids out of the rankings.

Drug queries live this split daily: trial papers, patent filings, and pill adverts share one string while patients need proof ranked first.

11.11 Search Engine Parts and Differences from Classical Systems

11.11.1 Core Ideas

An engine is a line of workers, each handing a cleaner product to the next. Miss one worker and the line jams.

What actually happens between typing and results? Pages are found and fetched, stored and mapped, then matched and ranked. Each stage has one job, and context plus money press on the last stage hardest.

A full engine reads as a pipeline. Web documents feed a crawler (an automated fetcher that finds and pulls pages). Crawled pages feed an index (the store-and-organize stage). A user query then searches the index and returns ranked documents. Between the boxes sit parsers (text cleaners and splitters) and an indexer (the builder of the inverted index, the word-to-page map), plus a link graph (the page-to-page hyperlink map) and duplicate removal (the near-repeat filter). In short: crawl means find and fetch, index means store and organize, and search means rank and retrieve. The coming sessions continue with index size, duplicate deletion, ranking, crawling, and search challenges. Think of a kitchen line: foragers fetch, prep cooks clean and chop, the pantry maps every jar, and the head cook plates per order while tossing copied plates.

Classical and web systems split five ways. First, links: web pages carry hyperlinks to other pages, so reading one result opens doors to more results, while classical retrieval is flat and static with no such doors. Links spread trust and topics across pages, which later ranking turns into scores. Second, queries: web queries run into the billions and vary wildly, far past the neat statements of a closed store. Short, mixed, and multilingual strings are the norm. Third, users: web users number in the billions with mixed skill, unlike the trained searcher a classical system expects. Plain boxes beat query languages at this scale. Fourth, scale: the web holds hundreds of billions of documents, so every stage must stream and shard. Fifth, context and commerce: location, session trail, and personal profile steer web results, and adverts plus spam press in from the sides, while classical setups face neither force.

Context decides meanings. The query Python from a library terminal should surface programming books, while the same string from a forest-department post near the Amazon should surface the snake. Classical setups paid little heed to such signals; web engines live by them. Place, role, and trail flip the top hit without changing the string.

Picture the pipeline as five boxes with arrows: fetch, clean, map, link, rank. Side arrows feed context into rank and adverts into their own marked lane. The takeaway in one line: fetch wide, map tightly, rank with context, and fence the money lane.

Scope: The pipeline suits fresh, linked, user-facing search at scale. Closed, trained-user stores can skip context and link stages. Assumption: Crawls stay fresh enough, parsers match the languages in the stream, and repeat filters catch copies before rank wastes time on them.

Do not feed raw fetched pages straight to rank. Unparsed markup, scripts, and copies pollute scores and waste shards. Do not mix advert order into ranked order; the lanes stay split so trust survives.

11.11.2 Student Questions and Answers

Q: Why do library and forest-department searches for one word disagree?

A: Place and role change the need behind the string. The engine reads that context and ranks the matching sense first. Same word, different job, different top hit.

Crawl, parse, index into word-to-page maps, track links, kill repeats, then rank with context while adverts stay fenced. Links, wild queries, mixed users, huge scale, and context plus commerce are the five splits from classical setups.

Travel search shows the line daily: crawled listings, cleaned text, word maps, link scores, repeat filters, and location-aware ranks with marked sponsored slots apart.

11.12 Static Web Graph and User Behaviour

11.12.1 Core Ideas

Links turn pages into a map, and readers turn the map into habits. Ranking must read both.

Why draw pages as dots and arrows? Dots expose which pages even connect; arrows expose who trusts whom. Habits then decide how far down the ranked list eyes ever travel. Structure plus behaviour sets what good ranking means.

A static web (fixed pages with fixed hyperlinks, leaving aside moving and script-built pages) draws neatly as a directed graph (nodes for pages, arrows for hyperlinks). With pages A, B, C, D in rank order, opening A may show a link to C, which draws an arrow A to C. Page B may point at A and at itself. Page C may point at B. Each arrow gives an out-link (an arrow leaving a page) to its source and an in-link (an arrow entering a page) to its target, with out-degree and in-degree counting each side. Self-links count on both sides of their page. Rank order here means crawl or label order, not quality order.

Reachability is not promised: some pages sit off the walked paths, so no chain of arrows ever lands on them. Connected components (tightly knit node sets) expose such splits, and triangle counts (three pages linking round in a loop) act as the working signal. More triangles mean a tighter patch. A clique (a fully connected set where every node links every other node) is the extreme: four nodes with all four triangles present score the maximum component value of one. Reading triangle loops on undirected graphs ignores arrow colours, but on directed graphs each arrow must face the right way round the loop, which is why only one directed triangle survived in the worked sketch. Direction is the whole test: three edges that fail to chase round the loop do not count.

Guessing need splits two ways. Context-free guessing reads the bare string only. Context-aware guessing reads geography, past sessions, and personal profile alongside the string. The query Jaguar may mean car, animal, or operating system until context breaks the tie. A string such as five plus four should wake a calculator, and a string such as one kilogram in pounds should wake a converter. Two ranking moves then apply. Restriction drops wrong-sense results outright and re-ranks what stays, as when Google.fr (the French Google domain) keeps French documents even for an English string. Ranking modulation keeps the shared pool yet reorders it per person and session, which is why two searchers may share page-one entries in a different order. Google.fr ranks French documents first for its users. Restriction filters the pool; modulation shuffles it.

Behaviour data backs simple designs. Searchers type short strings, about three words on average and rarely past four. They skip AND and OR operators even when the logic is known; at most a quoted phrase such as linked list or a plus sign binds words. They read only the first pages and almost never cross page two. They want a plain box plus results that fit their own setting on the first screen. Fancy query grammar sits unused while the first screen decides trust.

Classical scores still count, with a top-heavy twist. Precision, recall, and the F1 blend hold good on the web, but since eyes stop early, precision at one and precision at ten (precision scored over only the first one or ten results) are the working cuts. Precision at ten asks how many of the first ten hits satisfy the need; precision at one asks whether the very top hit does. New pressures join them: trust in pages, duplicate elimination, reliability, readability, and latency (answer speed). Classical flat stores never faced repeats or trust at web scale, so these weigh far more here. A fast, readable, trusted top ten beats a slow perfect list buried on page three.

Picture the graph as four dots with arrows A to C, B to A, B to self, and C to B, plus one directed triangle that chases round correctly while near-miss triples fail the direction test. Beside it picture a steep attention curve: most clicks on rank one, few by rank ten, almost none past page two. The takeaway in one line: link shape picks candidates, context orders them, and only the top survives readers.

Scope: Static graphs suit link-structure study; live ranking must add drift, scripts, and behaviour. Assumption: Triangles signal tightness only when arrows chase round the loop on directed graphs; undirected counts overstate tightness.

Do not quote full-list precision as the web headline. Eyes stop early, so lead with precision at one and ten plus trust, repeats, readability, and speed. Do not let tagging debates stall ranking work: tagging is a fixed rule in classical pipelines, and its exact weight inside web ranking was left open, with a note that it may well play a part.

11.12.2 Student Questions and Answers

Q: When counting triangles, may arrow directions be ignored?

A: Only on undirected graphs. On directed graphs each arrow must run the right way round the loop, so the component math changes and fewer loops qualify. The worked sketch kept a single directed triangle for exactly this reason.

Body text bridges the two doubts. The first doubt fixes the geometry rule; the second fixes the language-rule weight.

Q: Does parts-of-speech tagging steer web ranking?

A: The tagging step is a fixed rule in classical pipelines. Its exact weight inside web ranking was left open, with a note that it may well play a part. Do not claim more than the session gave: possible part, open weight.

Draw the static web as a directed graph, count only direction-correct triangles, guess need with context, restrict or modulate the rank, and judge by precision at one and ten plus trust, repeats, readability, and speed. Exam note: Quote precision at one and ten with trust, duplicate elimination, reliability, readability, and latency as the added pressures.

Local search shows the blend: map dots, direction-aware tightness, French-first modulation on Google.fr, and a top-ten readers actually see.

Exam Guidance Summary

Expect the grouping numerical only from K-means; hierarchical and density methods stay as background and will not be asked as hand problems. Read each classification ask word by word: TF only means skip IDF, TF-IDF means run both halves, and a free choice means Manhattan distance keeps hand arithmetic short. Write every premise on the page, including TF scope and whether fixing ran, since that line proves the idea is in place. Show table work row by row so partial marks can follow the trail. For Bernoulli smoothing, the denominator constant is two for token presence against absence, never the class count. For Rocchio and neighbour runs, IDF rates come from the training store. For web search, precision at one and precision at ten are the scoring cuts to quote, with trust, duplicate elimination, reliability, readability, and latency as the added pressures. For the curve, horizontal holds the false positive rate and vertical holds the true positive rate with the top-left corner as the target. For K-means, assign each point to the minimum gap and close only after two calm rounds in a row.

Exam note: Premise lines earn marks: TF scope, fixing choice, and gap choice written out in full. Tables row by row, means slot by slot, gaps ranked, votes counted, and the bend read for .

Key Industry Applications

News-topic routing runs Rocchio middles over TF-IDF rows to sort fresh articles into sport, business, and world desks. Ticket triage at scale runs neighbour votes over count rows so a fresh ticket takes the label of its closest past cases. Nightly basket maps run K-means middles over buying patterns to refresh audience groups. Short-message spam and sentiment filters start from Bernoulli checklists where one trigger word matters more than repeats. Peak-hour ride grouping over trip networks fits network tools such as Louvain, Leiden, and WalkTrap because raw map closeness misses route links. Shopping-pattern mining over buyer similarity fits gap tools such as K-means and hierarchical grouping. Soft membership scoring with Gaussian mixtures has served software-testing analysis where failing runs blend causes. Library code computes full TF-IDF with log damping and smoothing for all of the above. On the web, the early paid engine GoTo ranked results purely by advertiser bids, while Google split ranked results from paid adverts, keeping the ranked side on search merit. Google.fr re-ranks toward French documents for its users. Pharmacy adverts and patents share result lists with peer-reviewed papers for gene queries such as BRCA1, so proof must outrank pitch.

Match the tool to the setting: middles for round topics, votes for bent shapes on big stores, checklists for short texts, density walks for rings, network tools for routes, and mixtures for overlaps.

IR Lecture 11 notes · Text Classification, Clustering, and Web Search

Information Retrieval· undergraduate· 2026-09-13

Sections Breakdown

1Bernoulli Naive Bayes Smoothing and Worked Numerical

Multinomial vs Bernoulli Naive Bayes smoothing with full good-nice posterior trace; denominator two counts word faces not classes

2Rocchio Centroid Classification with TF-IDF

Rocchio centroid with TF-IDF weighting and unit fixing; log base fixed to 10 with order preserved; China example traced cell by cell

3Second Rocchio Example and Exam Technique

Dog-cat Rocchio trace with TF only and no fixing; garbled digit strings replaced by one fixed vocabulary order with full centroid means and gaps

4K-Nearest Neighbour Classification of Text

KNN text classification via contiguity, Euclidean and Manhattan gaps, and 1-2-3 neighbour votes on the China set

5Judging Classifiers

Confusion table with accuracy, precision, recall, F1, and receiver operating curve with axes fixed

6Clustering Foundations

Unsupervised grouping goal, elbow method for K, naming with expert review, hard vs soft groups

7K-Means Algorithm Step by Step

K-means moving-average loop with mean sketch, five-point trace, and fly-eagle-go text trace

8Initial Centroids and Cluster Quality Scores

Seed luck with split-merge failure, three seed fixes, and SSE scoring with 0.7 vs 0.8 anchor

9Other Clustering Families and Picking the Right Tool

Clustering families by shape bet with tool-to-setting matches and K-means-only exam scope

10Why Web Search Is Harder Than Classical Retrieval

Web vs classical gap with heterogeneity, BRCA1 mix, four builder puzzles, and GoTo-to-Google money lesson

11Search Engine Parts and Differences from Classical Systems

Engine pipeline stages and five splits from classical retrieval with context-driven Python split

12Static Web Graph and User Behaviour

Static web graph with directed triangles, context restriction vs modulation, user habits, and top-heavy scoring

Undergraduate students studying Information Retrieval

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.

Bernoulli Naive Bayes Smoothing and Worked Numerical

Must-know: Bernoulli smoothing adds two per word for present/absent; posterior multiplies prior with present and absent factors

Top pitfall: Writing the number of classes into the Bernoulli smoothing denominator instead of two for presence against absence

Self-check: Word seen in 2 of 2 class docs scores (2+1)/(2+2)=3/4 under Bernoulli with alpha=1. Why?

Connects to: 11.2, 11.4

Rocchio Centroid Classification with TF-IDF

Must-know: TF-IDF weights, unit-length members, plain-mean centroids, nearest centroid wins

Top pitfall: Fixing the centroid a second time or computing fresh idf on the test set

Self-check: Word in all 4 of 4 docs has idf log(4/4)=0. Why does it add no signal?

Connects to: 11.1, 11.3, 11.4

Second Rocchio Example and Exam Technique

Must-know: TF only with no fixing is valid when written down; nearest centroid wins

Top pitfall: Computing IDF when the ask says TF only, or mixing fixed and raw rows

Self-check: Why does writing TF only, no fixing protect marks even if arithmetic slips?

Connects to: 11.2, 11.4

K-Nearest Neighbour Classification of Text

Must-know: KNN stores rows, scores all gaps at test time, majority of K nearest wins

Top pitfall: Growing K past the local patch or voting on raw strings without TF rows

Self-check: Why is K=2 risky for two classes without a tie rule?

Connects to: 11.2, 11.5

Judging Classifiers

Must-know: Accuracy, precision, recall, F1 from four cells; curve plots TPR vs FPR with top-left ideal

Top pitfall: Swapping TPR and FPR axes or quoting accuracy alone on skewed data

Self-check: TP 8 FP 2 FN 4 TN 86 gives accuracy 0.94 but recall 0.667. Why does accuracy mislead?

Connects to: 11.4, 11.12

Clustering Foundations

Must-know: Small within gaps, large between gaps; elbow bend picks K; experts confirm names; hard vs soft

Top pitfall: Reading blob count as truth without expert and metadata checks

Self-check: Why can three blobs mean two, three, or four real groups?

Connects to: 11.7, 11.8

K-Means Algorithm Step by Step

Must-know: Seed, assign to nearest, refresh means, stop after two calm rounds

Top pitfall: Stopping after one round or assigning to the largest gap

Self-check: Points (1,2),(3,5),(4,6) give centroid (8/3,13/3). Show each slot sum.

Connects to: 11.6, 11.8

Initial Centroids and Cluster Quality Scores

Must-know: Starts trap runs; rerun, tree-cut seeds, or overseed; SSE picks the tighter run at the bend

Top pitfall: Picking K by raw SSE minimum instead of the bend; trusting one start

Self-check: Five groups score 0.7 vs three groups 0.8. Which is kept and why?

Connects to: 11.6, 11.7

Other Clustering Families and Picking the Right Tool

Must-know: Blobs K-means/medoids, trees hierarchical, rings density, networks Louvain/Leiden/WalkTrap, overlaps mixtures; exam numbers only K-means

Top pitfall: Handing rings to K-means or networks to gap tools

Self-check: Four rings: why does K-means slice them while density keeps them whole?

Connects to: 11.6, 11.8

Why Web Search Is Harder Than Classical Retrieval

Must-know: Web is huge, mixed, drifting, copied, paid; BRCA1 mix; GoTo bids vs split page; zero bend ideal

Top pitfall: Letting bids bend ranked results or treating mixed queries as single-intent

Self-check: One string returns papers, patents, adverts, explainers. What must the ranker do?

Connects to: 11.11, 11.12

Search Engine Parts and Differences from Classical Systems

Must-know: Crawl-parse-index-link-rank pipeline; five classical-vs-web splits; Python context split

Top pitfall: Skipping parse and repeat filters or mixing advert order into ranked order

Self-check: Same word Python tops books in a library and snakes near the Amazon. Why?

Connects to: 11.10, 11.12

Static Web Graph and User Behaviour

Must-know: Directed graph, direction-correct triangles, restriction vs modulation, short queries, precision at 1 and 10

Top pitfall: Counting undirected triangles on directed graphs or quoting full-list precision

Self-check: Why does only one directed triangle survive when near-miss triples fail the chase test?

Connects to: 11.5, 11.10, 11.11

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.