Text Classification with Naive Bayes and Vector Space Models
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
- Retrospective search versus prospective filtering with standing queries — covered in Lecture 1 (Two Kinds of Information Need)
- Text preprocessing with stop-word removal, stemming, and lemmatization — covered in Lecture 1 (From Raw Document to Ranked Output)
- Term weights with TF-IDF and cosine similarity for ranking — covered in Lecture 2 (The Vector Space Model)
- Boolean exact-match with present-or-absent terms — covered in Lecture 2 (The Boolean Model)
- Ranking by likelihood of relevance — covered in Lecture 2 (The Probabilistic Model)
10.1 Prospective Search and Standing Queries
10.1.1 Retrospective use and prospective need
Everything learned so far about document form, term weights, and similarity can be reused for a new task. Instead of ranking documents against a query, we use the same document forms to assign a class label to each document. This contrast between retrospective versus prospective search with standing queries sets the frame for the full lecture.
Think of a librarian with two jobs. In one job, a visitor asks once and the librarian points to the right shelf. In the other job, the librarian watches the door all day and taps you the moment a book you care about arrives. The first job is retrospective. The second job is prospective, and it needs a standing query that never sleeps.
Retrospective search means a query is run once against an existing collection. A user types words, the system ranks stored documents, and the job ends. Ad hoc search works this way. The collection is fixed at query time, and the answer is a ranked list.
Prospective search means the query stays active while new documents keep arriving. An analyst who must watch news about an attack by America, or an attack on America, or conflict involving Iran and America, cannot search only once. The story is still going on. The need is for a standing query that runs without end and flags each fresh article on the topic as soon as it arrives.
A standing query is a query stored by the system and run again for each new document. A retrospective query is run once against old documents. A prospective query is a standing query run forward in time against a stream of new documents. Routing and filtering are other names for this prospective use.
A standing query is much like a handwritten classifier. For each incoming document it decides relevant versus non-relevant. Google Alerts and live notification filters are common cases of this idea. The rule can start as simple Boolean logic, for example multicore AND computer AND chip, and it grows over time as new phrasing appears, for example multicore processors instead of multicore chips.
A useful picture is a mail sorting desk. Retrospective search is reaching into a full mailbag for one request. Prospective search is sitting beside the slot where new letters drop and pushing each letter into the right tray the moment it lands. The desk, the trays, and the sorting habit stay the same. Only the direction of time changes.
10.1.2 Annotated text and class labels
Prospective filtering needs annotated text. Annotated text means text where some person has already marked which documents are relevant and which are not. Each mark is a plain tag on the full document, not a score inside the text. Other names for the same idea are gold standard labels and class labels. Gold here means trusted by agreement, not made of metal.
When class labels are given in advance and the system learns from them, the study is supervised. Supervised learning means learning from items that already carry the right answer, so the system can check its guesses during training. This point was confirmed by class discussion. Spam versus no-spam mail filtering is the classic case. The system sees many mails already marked as spam or no-spam, learns red-flag signs, and then marks new mail.
The supervision habit matters because it decides what the system can learn. With labels, the system can count which words lean toward which side. Without labels, it can only group by surface likeness and hope the groups match the real need. Labels turn a vague wish into a measurable task.
Real-world use: Google Alerts is a standing query. A user defines a topic once, and the service flags each new matching page or news item over time. Personal mail sorting into folders such as bills, announcements, and family mail uses the same idea with more than two trays.
10.1.3 Spam signs as a first example
Spam detection shows what the model must notice. Red flags include words tied to money, words that press for quick action such as urgent and today, often written in capital letters, and lures tied to real estate. Suspicious links are another flag. A mail from an address never seen before in the inbox is also suspect.
An urgent cue is a word or style that pushes fast action, for example URGENT or act today in capitals. A suspicious link is a web address that does not match the claimed sender or service, for example a bank name in the text but a strange domain in the link. A sender signal is the past history of the From address, such as never seen before versus often seen and trusted.
An everyday comparison helps. Think of a security guard at a building door. The guard learns faces, badges, tone of voice, and the look of delivery boxes. One strange badge alone proves little. Three odd signs at once raise the alarm. Spam scoring works the same way. No single word decides. The joint weight of money words, urgent style, strange links, and unknown senders decides.
The model must learn these signs from labeled mail and then decide for each new mail whether it is spam. Training counts how often each sign appears in spam versus no-spam. Scoring adds those weights for a new mail and picks the side with more proof.
Scope: This spam sketch uses only surface signs that are easy to count. It does not yet use sequence, meaning, or sender reputation graphs. Those richer signs help in real work but need more data and more care. Assumption: Training mail looks like future mail. If spammers change wording or links, the old weights age fast and the filter must be retrained on fresh labeled mail.
Visual habit: picture two piles of mail dots on a table. The left pile is spam, the right pile is no-spam. Each dot is one mail. Mails with money words and urgent caps drift left. Mails from known friends with plain text drift right. The middle zone holds mixed mails where one more sign tips the choice. The takeaway is that class groups form loose clouds with a gray border, not two neat boxes.
Beginners often think one magic word proves spam. It does not. Money words appear in real bills too. Urgent appears in real school notes too. A second trap is trusting the From name alone. Names are easy to fake, so the link target and past address history must also be checked.
Real-world: spam versus no-spam mail filtering is the standard first use of text classification. Safe search filtering of explicit pages, language tagging of documents, and sentiment grouping of reviews into positive, negative, or neutral all reuse the same label-then-learn pattern.
10.1.4 Student Questions and Answers
Q: What type of study is this when class labels are already given as relevant or non-relevant? A: It is supervised study. The labels guide learning, and classification of new items uses what was learned from labeled items. The given relevant and non-relevant tags are the supervision signal.
Q: What other text classification uses come to mind besides spam? A: News grouping into finance or business, Google News topic routing, sentiment grouping into positive, negative, or neutral, recommendation, and routing of news articles into topics all count as text classification. Each use has fixed labels, labeled training items, and new items to place.
Retrospective search answers one ask against old documents. Prospective search keeps a standing query alive against a stream and files each new document as relevant or not. Labeled examples make that filing supervised, with spam filtering as the first concrete case. That filing habit leads straight to the formal task of picking a class label for a bag of words.
10.2 Formal Task and Document Features
10.2.1 Instance, classes, and bag of words
How do we turn filing mail into math that a machine can run. The formal instance classes bag of words features view gives that math in three short lines.
If sorting mail is the job, what is one letter, what are the trays, and what does the sorter get to look at. One letter is the instance. The trays are the classes. The words and marks on the letter are the features.
A document is one item to label, written . An instance space is the set of all items we may need to label, written . We say belongs to . The phrase in plain words was a description of an instance D that belongs to X. For text, the central choice is how to show a document, and the answer used here is to treat each document as a high-dimensional bag of words. High-dimensional means many thousands of distinct words, each one a separate axis. Bag means order is dropped and only counts are kept.
We are given a fixed set of classes . Here each with a small raised number is one class name, is the count of classes, and belongs to the positive whole numbers. Our job is to pick the class variable that fits best for that bag of words, token set, or document. Here is the label variable, and takes one value from the set of class names. In short, the formal task is: given instance in space with classes , choose label .
An instance space is the set of all items we may need to label. We write it as . A class variable is the label we want to predict. We write it as . A bag of words is a vector that records how many times each word type appears and forgets order. A token is one running word place in a document, while a type is one distinct word in the vocabulary.
Think of a fruit stall. One fruit is the instance . The stall with all fruit is the space . The trays marked apple, orange, and neither are the classes . The label stuck on the fruit is . The sorter is allowed to look at color, weight, and smell. Those looks are the features. Where the fruit analogy breaks: fruit signs are few and stable, while word signs are many thousands and shift with topic and time.
A tiny number case helps. Say the vocabulary has only three types: bank, river, money. Then is all count triples, and one document with bank twice and money once is . With classes finance and nature, the job is to pick in for that triple. Real tasks use tens of thousands of axes instead of three, but the picking habit is the same.
10.2.2 Which features can a classifier look at
Bag of words is only one source of signs. For scientific articles, useful signs include title words, author names, affiliation strings, and keyword lists. For mail, useful signs include links inside the mail, sender address, punctuation use, capitalization, and matches against known word lists.
A feature is one measurable sign the classifier may use. A bag-of-words feature records word counts. A metadata feature records facts about the document such as title, authors, affiliation, sender, links, punctuation, capitals, or keyword lists. Title words often carry more weight than body words because authors place topic hints there.
For the classroom examples in this topic, only bag of words is used. That means the only features are the words themselves. In real tasks, all other document traits should also be used. The simplification keeps the first math and examples easy to follow. It is not advice to drop other signs in real work.
Picture a doctor folder. Body words are the nurse notes. Title, authors, affiliation, and keywords are the cover sheet with name, lab, and prior tags. A sorter who reads only the nurse notes can still do a lot. A sorter who also reads the cover sheet does better, since the cover often names the disease area in a few words.
Scope: Bag-of-words form fits when topic words carry the class signal and order carries little extra signal. It fits topic, spam, and sentiment tasks at first pass. Assumption: Training and test documents share the same feature mix. If test mail hides links as images or papers drop keywords, a model trained on those fields loses signal and must be retrained on the new mix.
A common trap is to keep every string as a feature and hope for the best. Raw strings include noise such as headers, copy-paste disclaimers, and random codes. A second trap is to drop metadata to keep code short. Title, sender, and link signs are cheap and often beat the thousandth extra body word.
Real-world: scientific article grouping can use title, authors, affiliation, and keywords alongside body words. Mail filtering can use links, sender address, punctuation, capitals, and word lists. Language tagging of French versus English can use short character chunks alongside word signs.
10.2.3 Student Questions and Answers
Q: Apart from bag of words, what features can serve for scientific articles? A: Title, author names, affiliation, and keywords can all serve as features, alongside the body words. Those fields name the topic in a compact form and add signal beyond word counts.
Q: When tokens are named here, does that mean after stop-word removal and work on unique words? A: Yes for good results in practice. Pre-processing with stop-word removal, stemming or lemmatization, and word-class tagging should be done first. Tokens here mean cleaned types after those steps. Since grammar and word order are already ignored, leaving other noise in place would hurt scores further. Stop-word removal drops glue words, stemming and lemmatization map variants to one base, and tagging keeps the useful word class.
Exam note: State the formal task in one line: given instance in space , pick label from to using bag-of-words plus metadata features such as title, authors, affiliation, keywords, links, and sender signs. Clean tokens with stop-word removal, stemming or lemmatization, and tagging before counting. That formal setup leads to the next choice of which words to keep.
10.3 Feature Selection
10.3.1 Why keep only some words
Why carry a full sack when a small pouch holds the tools. Feature selection with chi-square and mutual information keeps the words that carry class signal and drops the rest, which cuts redundancy and noise.
A spam filter that watches every distinct word must watch tens of thousands of axes. Most of those axes are glue words or one-off codes. Keeping them slows training, fills memory, and lets the model learn quirks of the training batch that fail on new mail.
Not every word matters. Using all words makes the feature set huge. A huge set raises time cost, space cost, and training time. It also keeps noise and raises the risk of overfitting.
Overfitting means the model fits training quirks that do not hold for new data. We write no symbol for it because it names a behavior. A model that memorizes a training typo as a spam sign overfits. Noise means useless or misleading variation, such as random IDs in a footer. Feature selection saves time and space, cuts training time, removes noise, and helps avoid overfitting.
The same need arose with structured tables, where rows are cases and columns are features with a class label, and where methods such as principal component analysis cut size. Text data start without a table, so features must first be named to give the data shape, and then the feature count must be cut to keep the model fast and clean.
A food analogy helps. A cook keeps salt, oil, and rice within reach and stores rare spices away. The meal still tastes right, and the counter stays clear. Feature selection does the same for words. It keeps strong topic signs on the counter and stores weak or duplicate signs away. Where the analogy breaks: a cook knows the menu in advance, while a classifier must learn from counts which words are salt and which are dust.
10.3.2 Chi-square and mutual information
Two selection methods are named for this setting. One is the chi-square measure. The other is the mutual information score. Both test strength of link under known true chances, but they score it in different ways.
Mutual information says how much knowing a word tells us about the class. The plain-words quote kept alongside is how much knowing the word tells us about the class. We write the score for word and class as . Here is a word type, is a class name, and is a number that is large when the word and the class co-occur more than chance would give. A large means the word is a strong pointer to the class.
In full form, with marking presence or absence of the word and marking membership or not in the class:
Here is the joint chance of the word state and the class state, is the chance of the word state alone, is the chance of the class state alone, and is the natural log. When word and class meet more often than chance, the ratio inside the log is above one and adds positive weight. When they meet only at chance level, the ratio is near one and adds near zero.
Chi-square tests strength of link under known true chances. It asks whether two features share more information than chance would allow, or in plain terms whether two columns carry the same news and one is redundant. Fisher's exact test is named as another test used the same way for structured data.
Chi-square compares observed counts with expected counts under no link:
Here is the counted co-occurrence in the training table, is the count chance alone would give, and the sum runs over the four cells of the word-by-class table. A large means the link is strong and the word is worth keeping.
These two, chi-square and mutual information, are the top two named here for measuring strength of link when true chances are taken as known. Full detail on selection is not covered further. The point to keep is that selection exists and these are two common routes. In real work, the top few hundred or few thousand words by either score often keep most of the signal while cutting most of the cost.
10.3.3 Experts, redundancy, and a body-mass example
A domain expert can name useful features, but an expert can miss links. The body-mass case makes the point. Weight and height alone look separate. A person can have many pairings of the two. Yet weight and height together form body mass index:
Here is weight as a number in mass units, is height as a number in length units, and is the index value. In plain words the quote was weight and height together is used to make the body mass index. If the index is kept, weight and height alone may add the same news twice. That is redundancy. The trio of weight, height, and body mass index shows redundant features in one small table: two raw columns plus one joint index where the third repeats news already held by the first two.
Take numbers. A patient with and gives:
Here is the index value in mass per squared length. Once is stored, keeping both and as separate strong signs for the same health label can double-count the same body-size news. A selection test spots that overlap and drops one side.
In the same way for papers, title, authors, and keywords may overlap. With articles labeled article 1, article 2, and so on, a test can ask whether two columns move together or add fresh news. Chi-square is one test that answers that question. A word that rides along with another word adds cost without adding proof and should go.
Picture a scatter plot with weight on the x-axis and height on the y-axis. Dots form a loose upward cloud. Color the dots by high versus normal index value. The colors split along a curve, not along a straight vertical or horizontal line. The takeaway is that the joint index draws the boundary that neither single axis draws alone, so keeping all three axes double-counts one shape.
Scope: Selection scores rank single words by link to the class. They do not spot pairs that are weak alone but strong together. Assumption: Training counts mirror future counts. If a new topic brings fresh words, the old kept set misses them and the ranking must be rerun on fresh labeled text.
One trap is to keep too few words and starve the model. Glue words go, but rare topic words must stay. A second trap is to trust an expert list alone. Experts name neat signs and miss hidden doubles such as title words that repeat keyword tags. Let counts check the expert list.
Real-world: patient table with weight, height, body mass index, and lab values shows how two raw columns can be redundant once their joint index is kept. Mail filters that keep both urgent and URGENT as separate strong signs meet the same double-count trap after lowercasing.
Keep words that tell class news and drop words that repeat it. Mutual information and chi-square rank that news, while the weight plus height plus body mass index trio shows why redundant doubles must go. With a lean feature set in hand, the next choice is how labels get assigned at all.
10.4 Three Ways to Assign Labels
10.4.1 Manual labeling by people
Who puts the first labels on the pile. Manual annotation with rule-based and learned models compared through training cost and scale gives three answers, and hand work by people is the first.
Ten news files sit on a desk. Three trays say sports, study or education, and politics. A person reads each file and drops it in the right tray. That drop is annotation, and the tray tag is the gold label others will learn from.
The most plain route is human labeling. With 10 news documents to place into sports, study or education, and politics, a person reads each document and drops it into the right bin. Labeling documents this way is called annotating. Annotation means a person reads an item and attaches the trusted class tag.
This route is very exact when experts do it. Yahoo early web tags were hand assigned. Radiology shows the cost. One patient magnetic-resonance scan can hold 400 to 500 slice images across side, top, and front views. An expert must view the slices and mark tumor versus no tumor. A cited charge is 20 dollars per patient for this marking work. The radiology 400 slices at 20 dollars case shows hand labels cost a lot: expert eyes give trusted tags, but each patient stack bills expert minutes.
Manual work is flawless in small doses but it cannot be scaled or generalized with ease, and it costs a lot because expert time costs a lot. Marking 10 documents looks cheap. Marking scans for a whole hospital does not. Hand labels also drift when two experts read border cases in different ways, so guides and double reads are needed for trust.
Real-world: early Yahoo topic tags were hand assigned. Radiology tumor marking on magnetic-resonance slices is still hand assigned for first training sets that later train learned models.
10.4.2 Rule-based classifiers
The second route is rules. An expert writes if-then rules over a fixed word set, and new documents follow those rules. This works like a charm while incoming data keep the same shape.
A rule-based classifier is a hand-written list of if-then tests on words or fields. A training set is not needed to run it, since the rules are the model. Example: if a mail holds urgent plus money plus a strange link, then mark spam.
A concrete rule helps. If title holds pound or pence and body holds transfer plus fee, then mark finance scam. If sender is in the contact book and no link is present, then mark no-spam. Each rule is easy to read and easy to fix in isolation.
The weak point is change. When an unseen or rare condition arrives, the rules fail. Then all rules need rework. Rule upkeep never ends because real data always bring fresh phrasing nobody fixed in advance. Since experts charge high fees, repeated rebuilds cost a lot. Rules also clash. Two rules can fire at once with different labels, so a priority order must be added and maintained.
Scope: Rules fit small and stable sets where the word scope stays fixed and no learning model is worth training. Assumption: Future documents use the same words in the same senses. If topics shift or spammers swap terms, the fixed word set goes stale and precision drops until rules are rewritten.
Rules fit small and stable sets where the word scope stays fixed and no learning model is worth training. When data are large or rules need frequent change, rules are not the best choice. A law office that routes a fixed set of form types can live on rules. A news stream with daily new names cannot.
10.4.3 Learned models and training data
The third route is learned classification models. This section links manual annotation, rule-based models, learned models, and training data in one flow. The scope here follows textbook chapter 13. The methods named for this course are Naive Bayes, Rocchio, and K nearest neighbors. Support vector machines are named but marked as not covered. Rocchio and K nearest neighbors use vector-space form. Naive Bayes uses chance.
A learned model sets its own weights from labeled examples. Training uses labeled items to set model values. Testing uses unseen items to check labels. Under supervised learning, grouping with labels is called classification, not clustering. K-means is clustering, not classification, because it groups without labels.
All these methods need training data with gold-standard labels. Training uses labeled items to set model values. Testing uses unseen items to check labels. Under supervised learning, grouping with labels is called classification, not clustering. K-means is clustering, not classification, because it groups without labels. Logistic regression is noted in discussion but it fits continuous-variable form and is not the focus when labels are plain categories.
A picture used in class shows the flow. A large corpus feeds bag-of-words form plus class labels. Top-level bins include regions, industries, and subject areas. Regions split into UK and China. Industries split into poultry and coffee, among others. The model trains on the corpus and labels, then a new document is funneled into one topic bin such as a region bin, an industry bin, or a subject-area bin, including sub-region bins.
Think of school. Hand labels are a tutor marking ten essays by hand. Rules are a wall chart that says if essay holds these three phrases then grade B. Learned models are a student who reads a hundred marked essays, learns the marking habit, and then marks the next essay alone. The student still needs the tutor's first marks to learn, just as learned models still need manual annotation for training data.
Search uses show the same idea. Language tagging of French versus English, spam versus no-spam, and sentiment grouping all run text through a classifier first.
Beginners often mix classification with clustering. Labels make the split. If labels guide training, the task is classification. If no labels exist and groups must be found, the task is clustering. A second trap is to test on training items. Scores then look high but fail on new items, so a held-out test set is a must.
Real-world: Google News first groups articles by topic such as sports, cinema, and politics through classification, then ranks documents inside each group through search. PubMed topic routing, product review sentiment, and language routing before deeper analysis follow the same train-then-file pattern.
Hand labels give truth at high cost, rules give speed on fixed wording but age fast, and learned models trade an upfront labeled training set for broad use on new wording. Manual annotation feeds training, training sets weights, and testing checks new items. With that trade in place, the next step is the chance-based learner that turns counts into class scores.
10.5 Naive Bayes Core
10.5.1 Bayes rule for a document
How do we turn word counts into a class bet that can be ranked. Bayes posterior with token product and MAP log priors plus smoothing gives that bet in four linked steps.
A detective starts with a hunch about each suspect, then updates the hunch as each clue arrives. The prior is the first hunch. Each word is a fresh clue. The posterior is the updated hunch after all clues. That update habit is Bayes rule for text.
Bayesian methods learn and classify with the rules of chance. The model tells a generative story, which means a story of how the data were made. Each class has a prior chance believed before seeing proof. After seeing an item, the model gives a posterior chance.
The plain-words quote for the core rule was probability of class for a given document is proportional to probability of document for the given class and prior probability of the class. The form is:
Here is a class name, is one document, is the prior chance of the class, is the likelihood or chance of seeing that document when the class is , and is the posterior chance that the document belongs to . The sign means is proportional to, so the right side gives the ranking order without the shared scale factor.
The missing bottom term is the proof or chance of the document. In plain words the quote was probability of document is removed because it is the same for all classes. The full Bayes form is:
Here is the chance of the document under all classes. Since does not change when changes, it only scales values to a common base, so for ranking classes it can be left out. That is why the sign is proportional-to rather than equal. Dropping a shared scale keeps the winner the same while saving work.
10.5.2 From one document chance to a token product
A document is not one token. It is a bag with tokens, written . Here each is one token place in the document, is the place index from to , and is the count of token places in . A token place is one slot in the running text. A token type is one distinct word in the vocabulary.
The plain-words quote for the extension was considering all tokens in that document starting from first token to length number of tokens. The joint chance of all tokens needs a usable form. The step taken is a product over places:
Here is the chance of the token in place when the class is , and the large sign means multiply from through . In plain words, it is simply product of token one, token two, token three and so on. Then the posterior form becomes:
Here the product gives how much proof the tokens add for class . For sentiment work with positive, negative, and neutral classes, the same product is scored for each class, and the class with the largest value is picked. That Bayes posterior token product MAP log priors smoothing chain starts here and ends in log sums.
An N-gram view helps place this choice. A unigram uses one token at a time, written as one slot . A bigram uses pairs such as information retrieval. A trigram uses triples such as new york city. Here only unigrams are used. Bigrams and trigrams are left out because data size would limit them. Pairs need far more counts to fill, and training text is never large enough to fill them well.
10.5.3 Highest-score rule and prior weight
The decision rule is called maximum a posteriori, shortened to MAP. Among candidate classes, pick the one most likely after weighing prior odds and token proof. The form is:
Here is the picked class, and means the class that gives the largest posterior value. In plain words, we pick the single most likely one after weighing both prior and token probability. Maximum likelihood by contrast picks the class with the largest token product alone and ignores the prior. MAP keeps both.
A common doubt is what happens when words give no clear sign. Take the sentence We are in Bangalore. None of its four words leans to positive, negative, or neutral. The product term is then tiny or flat, and the whole choice falls back on the prior . If the positive class is common in training, the sentence will be marked positive for that reason alone, not because its words earned it. The Bangalore sentence where prior decides when token proof is weak is the key warning for this rule.
Exam note: when token proof is weak, the prior decides. Keep training classes varied so likelihood can do real work. If likelihood adds little, revisit data shape and class mix. Prior math over and smoothed likelihoods decide the label when token proof is weak, so both must be stated in number work.
The coin story makes MAP plain. A fair coin gives heads or tails with equal chance:
Five heads in a row can still be chance, so equal chance stays a fair call. After 100,000 flips all heads, the coin looks biased. Equal chance no longer fits. Maximum likelihood fits the equal-chance case where all guesses start even. MAP fits the uneven case where each guess carries its own prior weight. The fair coin versus biased coin contrast explains MAP for uneven classes: text classes are uneven, so MAP is the right rule. A news stream with 90 sports items and 10 politics items should not treat both trays as even before reading words.
10.5.4 Conditional independence between words
Scoring whole word chains straight would need one value for every combo: first token alone, first plus second, first plus second plus third, then the same starting from the second token, and so on. With papers of a few thousand words, or IEEE papers of 5000 to 10000 words, Springer papers of 2000 to 3000 words, and open archives with very long items, token counts cannot be capped. Combo counts blow up, training data fall short, and the gap is called data sparseness. Data sparseness means too many possible combos and too few training hits to fill them.
Naive Bayes answers with conditional independence. Given the class, words occur independently of each other. In plain words the quote was for a given class, the words occur independently of each other. Formally, the joint chance splits into a product of single-word chances once the class is fixed, which is the product form shown above. That claim is not true for real language. Pairs such as scientific and literature, information and retrieval, artificial and intelligence, or machine and learning often travel together. The trade is still taken because it cuts the load from combos to one value per word per class.
The likelihood then stays a product of single-word terms, as shown above. Training burden drops from combo counts to one count per type per class. Pair and triple links are left out for now. Later models such as bigrams add some links back at higher cost, but the unigram baseline stays because it trains fast and scores well on topics.
Picture word dots on a class tray. Without independence, the model must learn the shape of every word cluster. With independence, the model learns each word axis alone and multiplies the axes. The picture is less rich but far cheaper, and on topic tasks the cheap picture still sorts well.
10.5.5 Log sums and floating-point underflow
Multiplying many small token chances gives a still smaller number, at times near zero on a computer. That trap is called floating-point underflow. Floating-point underflow means the product is so small that the machine rounds it to zero and wipes out all word proof. If it hits, all token work is wasted because the final MAP value collapses to the prior alone.
The standard fix is the log trick. Since , products turn into sums. Log is monotonic, so the class with the top score stays the top class. The plain-words quote was log a times b is equal to log a plus log b. The scored form is:
Here is the prior weight for the class, each is the weight saying how good a sign that word is for that class, and the sum is the total proof score. The class with the most proof wins. In plain words, each log conditional is a weight and the prior is a weight for the class. Sums are also faster than long products. The log sum MAP score with prior plus token log weights keeps the same winner as the product form while staying in a safe number range.
A tiny number check helps. Three token chances , , and multiply to . Their logs add to about . Both forms rank the same, but the sum never nears zero. With fifty such tokens, the product would vanish while the sum would sit near , still easy to compare across classes.
10.5.6 Priors, likelihoods, and Laplace smoothing
The prior in text work is a doc ratio:
Here is the count of training documents in class , and is the count of all training documents. In plain words, number of documents belonging to that class and total number of documents. For sentiment work with three classes, the positive prior is positive docs over all docs, and so on. A class with of docs has prior .
The likelihood for each token uses term counts with repeat hits counted. A word seen 10 times counts as 10, not 1. The plain-words quote was total number of occurrences of terms, including multiple occurrence. The raw form is:
Here is the count of term in class , ranges over word types, and the bottom sum is all term hits in class with repeats kept. Words are also treated as positionally independent. A word counts the same in a title, abstract, or closing part. No spot gets extra weight.
Raw ratios break on unseen words. The China demo shows why. Training has a China class with words Beijing and Taipei and join and WTO. If WTO never occurs in that class, its top count is zero. Zero over anything is zero. Zero times anything is zero. One missing word then zeroes the whole document score, no matter how strong the other words are. The plain-words quote was zero multiplied by anything is going to be zero.
Laplace smoothing fixes the zero by adding one. The smoothed form is:
Here is the count of distinct words in the training vocabulary. In plain words, add one in the numerator and add below to balance it. Every term now adds at least a tiny score. The zero wipe-out ends. One added hit per type is a uniform prior that fades as real counts grow.
Exam note: expect number work on priors with over and on smoothed likelihoods with plus one over plus . Show repeats counted and as vocabulary size for multinomial form. Prior math over plus Laplace smoothed likelihoods with plus decide the label when token proof is weak, so write both steps in full.
10.5.7 Training, testing, and cost
Naive Bayes runs in three steps. First, estimate all values from labeled text with add-one smoothing. Next, for a new document and each class, add the log prior and the log token chances. Then assign the class with the largest sum.
Purpose first: the procedure turns labeled counts into fast class scores. Inputs are labeled training documents plus the vocabulary. Outputs are priors plus likelihoods, then one label per test document. Steps in order: extract vocabulary, count documents per class for priors, convert documents to token counts, count tokens per class for likelihoods with smoothing. The rationale for each count is direct: priors need doc shares, likelihoods need word shares. Testing extracts tokens from the new document with the same token routine, scores each class by sums, and returns the max.
Training code is mostly counting. Named steps are extract vocabulary, count documents, convert documents, and count tokens. These are data-shaping and sum steps that build priors and likelihoods. Testing extracts tokens from the new document with the same token routine, scores each class by sums, and returns the max.
Time cost is linear. Training time grows with total training size because it only counts and then sets values from counts. Testing time grows with test length plus class count and relevant terms because it only sums. No quadratic term appears. That is why turnaround is fast and storage stays low. In standard notation, training is linear in collection size and testing is linear in test length times class count, which matches the vector method training cost shown later.
Scope: This linear cost holds for the unigram form with a fixed vocabulary. Assumption: Token routine is the same in training and testing. If testing skips stop-word removal or uses a new stemmer, counts mismatch and scores drift.
Real-world: fast linear training fits live filters where many mails or news items must be scored quickly. Spam folders, news topic routers, and sentiment dashboards all score streams of short items under tight time limits.
Two traps show up often. First, training on one genre and testing on another, such as training on long papers and testing on short mails, shifts word shares and priors. Second, forgetting smoothing on one class. One zero then kills that class on any document holding the unseen word, so smoothing must cover every type in every class.
10.5.8 Student Questions and Answers
Q: Can one example be shown to make the token product plain? A: Yes. The China set with priors, per-word likelihoods, and a five-token test is worked in full next, first with multinomial counts and then with presence-only counts. The five-token test holds Chinese three times plus Tokyo and Japan.
Q: If tokens give almost no sign, as in We are in Bangalore for sentiment, what decides the label? A: The prior decides. The product is flat or tiny, so the class most seen in training wins. When token proof is weak, varied documents and real token proof matter, since the Bangalore sentiment case with no clear sign falls back to priors.
Q: Why move from products to log sums when underflow threatens? A: Products of many small floats shrink toward zero and cost more time. Logs turn products into sums and keep the same winner because log is monotonic. The log sums avoid underflow and keep scoring fast.
Bayes posterior times prior gives the ranking, the token product makes documents scorable, MAP picks the top class, independence keeps counts small, logs keep numbers safe, and Laplace smoothing keeps zeros away. Priors over plus smoothed likelihoods carry number tasks. That full core is now ready for the China numbers that show counts versus presence.
10.6 Worked China Example: Multinomial and Bernoulli
10.6.1 Multinomial setup and priors
Training has four documents. Three belong to China class, one belongs to non-China class. The test document, called document 5, holds Chinese, Chinese, Chinese, Tokyo, Japan. So Chinese occurs three times, Tokyo once, Japan once. This China multinomial Bernoulli presence absent scores case is the running number task for the lecture.
Training table in brief: doc 1 holds Chinese Beijing Chinese and is China. Doc 2 holds Chinese Chinese Shanghai and is China. Doc 3 holds Chinese Macao and is China. Doc 4 holds Tokyo Japan Chinese and is non-China. Test doc 5 holds Chinese Chinese Chinese Tokyo Japan with label to guess.
Priors use doc counts:
Here means China class, means non-China class, 3 is China docs, 1 is non-China docs, and 4 is all docs. In plain words the exchange was three by four and one by four. The China multinomial priors three over four with 6 over 14 likelihoods start from this split.
Vocabulary size is 6 distinct words across training: Chinese, Beijing, Shanghai, Macao, Tokyo, Japan. Total hits in China class are 8 with repeats. Total hits in non-China class are 3 with repeats. Repeats matter here because multinomial counts hits, not docs.
10.6.2 Multinomial likelihoods and posterior
For China class, Chinese hits are 5 with repeats. With add-one smoothing:
Tokyo is unseen in China class, Japan is unseen in China class:
For non-China class, Chinese hits are 1, Tokyo hits are 1, Japan hits are 1, with class total 3:
Posterior scores use prior times likelihoods, with Chinese cubed because it occurs three times in the test:
Step the first score down. Write as which is about . Cube it to about . Multiply by to get about . Multiply by the second to get about . Multiply by to get about 0.0003. Step the second score down. Write as about . Raise to the fifth power for three Chinese plus Tokyo plus Japan to get about . Multiply by to get about 0.0001. The first score is about 0.0003. The second is about 0.0001. The max wins, so document 5 is marked China class. Log form would give the same winner through sums, with the China sum near and the non-China sum near on natural logs.
The multinomial China number task near 0.0003 versus 0.0001 shows the full chain: priors 3 over 4 and 1 over 4, likelihoods 6 over 14 with 1 over 14, and 2 over 9, ending in a China win. Frequency drives the win because three copies of a strong sign outweigh single copies of weak signs.
10.6.3 Why China wins despite Tokyo and Japan
All three test words occur in non-China training, while only Chinese strongly marks China training. It feels natural to guess non-China. Yet the test is marked China.
The reason is weight. Chinese at 6 over 14, cubed for three hits, outweighs Tokyo and Japan at 1 over 14 each. In plain words, Chinese has been overweighing the rest of the two. The Chinese overweighing Tokyo Japan pattern explains the China win: one strong word seen three times beats two weak words seen once each. Frequency matters in the multinomial view. Repeats count, so three copies of a strong sign beat one copy each of two weak signs.
A marble bag picture helps. The China bag holds many Chinese marbles and almost no Tokyo or Japan marbles. Drawing Chinese three times in a row points to the China bag even when Tokyo and Japan each appear once. The non-China bag holds all three words in equal small shares, so its three Chinese draws look less likely. Where the picture breaks: bags assume each draw is fresh, while real words travel in fixed phrases.
Scope: This count-based win holds when repeat hits carry meaning, such as topic words or sentiment words. Assumption: Training shares mirror test shares. If test docs are much longer than training docs, raw products tilt toward the class with larger likelihoods and length effects must be checked with logs and priors.
10.6.4 Bernoulli view with presence only
The multinomial result can feel wrong when presence feels more key than count. The Bernoulli view answers that need. It asks whether a term occurs at least once in a document, not how many times it occurs. The plain-words quote was fraction of documents in class which contains the term at least once.
The Bernoulli model estimates as the share of class docs holding the term at least once. It uses binary occurrence, ignoring the number of occurrences. Multinomial estimates as the share of tokens in the class that are the term. When classifying, Bernoulli scores both present and absent vocabulary, while multinomial scores only words present in the test.
This matches the old Boolean search idea of present versus absent. Use 1 for present, 0 for absent, or true for present and false for absent. If counts matter, stay with multinomial. If presence matters, use Bernoulli. Neither is always better. The task decides.
Real-world: law search for whether a given section is present in a document fits presence-only scoring. Mail spam work and product-defect flags can also fit presence. Gene-tag search such as BRCA1 in written reports can fit presence, though presence alone does not prove disease. Review sentiment, buyer guidance, quantum-paper search where many hits of quantum or complexity raise value, and PubMed topic search fit count-based scoring.
A key behavior gap is that Bernoulli also scores absent terms. Multinomial scored only Chinese, Tokyo, and Japan because only those occur in the test. Bernoulli also scores Beijing, Shanghai, and Macao as absent from the test. In plain words, absent terms also matter to scores. The Bernoulli presence scores 4 over 5 and 2 over 3 with absent terms show this gap in numbers next.
10.6.5 Bernoulli numbers and flipped label
Priors stay the same:
Bernoulli smoothing uses doc counts. For China class with 3 docs, the form for a word is counts of China docs holding plus one over China docs plus two:
Here is the count of class docs holding at least once, is the count of docs in class , the plus one is add-one smoothing, and the plus two stands for the two outcomes present or absent. In plain words, we have only two outcomes, so B is 2 for the binary case. This matches the standard form where add-one smoothing with covers occurrence and nonoccurrence, in direct analogy to the multinomial form with as vocabulary size. The bottom term is class docs plus two outcomes, not vocabulary size.
Chinese occurs in all 3 China docs:
Tokyo and Japan are absent from all 3 China docs, so each gets:
To state it cleanly, both Tokyo and Japan in China class are , since neither appears in China training. Beijing, Shanghai, and Macao each occur in 1 of 3 China docs, so each gets:
The same 2 over 5 holds for Shanghai and Macao in China class.
For non-China class with 1 doc, Chinese, Tokyo, and Japan each occur in that 1 doc:
The same 2 over 3 holds for Tokyo and Japan. Beijing, Shanghai, and Macao are absent from the non-China doc:
The same 1 over 3 holds for Shanghai and Macao.
Bernoulli final scores multiply prior by present-word chances and by one-minus-chance for absent words. For present words use . For absent words use . For the China class:
That product is about 0.005. For the non-China class:
That product is about 0.022. The non-China score is larger, so the same test document now scores higher for non-China class. Sense-check: presence-only scoring lets Tokyo plus Japan pull toward non-China, since 2 over 3 beats 1 over 5, while Chinese at 4 over 5 versus 2 over 3 is not different enough to hold the China win.
Final Bernoulli scores multiply prior by present-word chances and by one-minus-chance for absent words. For present words use . For absent words use . With this full product over both present and absent vocabulary, the same test document now scores higher for non-China class. The earlier hunch that Tokyo plus Japan should pull toward non-China comes true under presence-only scoring.
10.6.6 Student Questions and Answers
Q: How is Chinese in China class 3 plus 1 rather than 4 plus 1 or 5 plus 1 when repeats exist? A: Bernoulli counts documents, not hits. Chinese is present in document 1, present in document 2, and present in document 3, so the count is 3. Repeat hits inside one document do not raise it. That is the gap between multinomial and Bernoulli, where multinomial would count 5 hits plus 1.
Q: Why add 2 below in Bernoulli denominator rather than vocabulary size? A: The bottom term here is about class docs and the two outcomes present or absent, not about all unique words. For China class it is 3 docs plus 2. For non-China class it is 1 doc plus 2. The denominator wording is class docs plus two outcomes, with B equal to 2 for occurrence and nonoccurrence. A plainer worked case with these numbers pins this wording down.
Q: When should presence-only be picked over count-based scoring? A: Pick presence when the key fact is whether a sign occurs at least once, as with a law section or a defect flag. Pick counts when more hits mean more weight, as with sentiment words, product reviews, buyer guidance, and topic words in papers. Gene tags such as BRCA1 and PubMed topics follow the same split.
Q: Does the Bernoulli view weigh absent words too? A: Yes. Terms missing from the test, such as Beijing, Shanghai, and Macao, still shape the score through one-minus-chance terms. That absent-words flip is the main behavior gap from multinomial scoring, where absent terms add nothing.
Multinomial counts hits and lets three Chinese tokens carry the day near 0.0003 versus 0.0001. Bernoulli counts docs, adds 2 below for present or absent, scores absent words too near 0.005 versus 0.022, and flips the same test to non-China. Pick counts when repeats matter and presence when one hit is enough.
10.7 Vector Space Classification with Rocchio and Nearest Neighbors
10.7.1 Vectors and the contiguity idea
How do we sort by place instead of by chance. Vectors with contiguity plus Rocchio centroids and nearest neighbors give the place-based answer.
Think of pins on a map. Restaurants cluster near food streets. Schools cluster near housing blocks. A new pin takes the label of its street. Documents as points work the same way when like topics sit near each other.
Documents can be drawn as vectors. Take two terms, AI and ML, as the x and y axes. Three documents hold (2, 1), (1, 3), and (3, 0). The first holds 2 AI hits and 1 ML hit. The second holds 1 AI hit and 3 ML hits. The third holds 3 AI hits and 0 ML hits. So each document is a point with one number per term. The AI ML vectors 2 1 and 1 3 with centroid gaps case starts from these three points. Cosine scores can then say which documents sit close.
A document vector is one point with one number per term, often TF-IDF weights with length normalization. Contiguity means documents in one class occupy a connected patch of space. In plain words, documents in the same class occupy contiguous regions. The vectors contiguity Rocchio centroids nearest neighbors chain starts from this patch idea.
Vector classification puts each labeled document as a point in that space. The contiguity idea says documents in one class occupy a connected patch of space. In plain words, documents in the same class occupy contiguous regions. If similar items form round groups and unlike groups stand apart with no overlap, lines can split the space and each patch can take one class name. A figure with China, Kenya, and UK shows three well-split patches. A new point takes the label of the patch it lands in.
Good form is required. If stop words stay, or weights are poor, like items scatter instead of grouping. Scattered points with no contiguity cannot be split cleanly, since scattered points show no round shape, lines cannot split them cleanly, and labels fail. In plain words, when the data is poorly represented, the same documents might scatter, and then there is no contiguity. Length normalization plus TF-IDF weights fix much of this scatter by putting long and short docs on one sphere before gaps are measured.
10.7.2 Rocchio centroids and boundaries
Rocchio splits space with one center per class. The center is called the centroid. Other names used are center of gravity and barycenter. It is the mean spot of that class.
For class with document set , term vectors , and class size :
Here is the weight vector of document , often TF-IDF weights, is the centroid vector of class , and is the count of training documents in that class. In plain words, average of all vectors and mass weighted average. The Rocchio centroid mean over document vectors is the class prototype.
A board figure shows why vector lengths vary. Documents 1 through 5 are drawn with varied arrow lengths because length normalization was not applied. Normalized vectors would all have unit length. Red marks the centroid of documents 1 to 3. Blue marks the centroid of documents 4 and 5. Purple marks new document 6. The angle from document 6 to the second centroid is smaller than to the first, so document 6 takes the second class. Angle is the natural sign, so cosine is the common pick for that angle check.
Decision lines sit halfway between centers. If A1 is a boundary point between centroid 2 and centroid 3, the gap from centroid 2 to A1 must match the gap from centroid 3 to A1. The same match holds for B1 and B2 points. In plain words, points on the line are equidistantly placed. After lines are set, each query point takes the side it falls on. For length-normalized vectors, cosine closeness and Euclidean gap rank the same way, so the text moves between gap words and cosine words without changing the pick.
Real-world: length normalization plus TF-IDF weights keeps long and short documents on fair footing before centroid gaps are measured. Without it, a long doc with many repeats would sit far from the origin and pull its centroid outward for no topic reason.
10.7.3 Rocchio steps and cost
Training loops over classes and stores only centroids. Testing scores a new vector against each centroid and returns the nearest. In plain words, compute the centroid for each and then see which is closest by taking the minimum. Purpose: replace many training points with one center per class. Inputs: labeled TF-IDF vectors. Outputs: one centroid per class plus a label rule. Steps: normalize vectors, sum by class, divide by class size, store centers. Trace on the AI ML trio: class A holds (2, 1) and (1, 3) with mean (1.5, 2.0). Class B holds (3, 0) alone with mean (3.0, 0.0). A new point (2, 2) sits nearer to (1.5, 2.0) than to (3.0, 0.0) and takes class A.
Tiny Rocchio trace with the AI ML vectors 2 1 and 1 3 plus centroid gaps: class 1 mean of (2, 1) and (1, 3) is (1.5, 2.0). Class 2 mean of (3, 0) is (3.0, 0.0). Gap from (2, 2) to class 1 center is about 0.5. Gap to class 2 center is about 2.24. The nearer center wins, so class 1 wins. Sense-check: the new point shares both AI and ML weight, like class 1, while class 2 lacks ML entirely.
Closeness can use cosine scores or gaps. For vectors, angle is the natural sign, so cosine is the common pick. On a flat drawing the same choice looks like a gap measure. Length normalization plus cosine is the stressed pairing. Normalize lengths and assign nearest centroid label is the test habit: score cosine closeness to each centroid and take the nearest.
Time cost is linear in training and testing, like Naive Bayes. Training adds vectors per class in time linear in collection size. Testing compares the test vector to each centroid in time linear in class count times test terms. In standard form, training is linear in collection size and testing is order of class count times test types. Only lengths, sums, and means are used. No complex math appears. Accuracy gaps appear when class shapes turn complex, such as two far clusters sharing one label.
A TF-IDF plus normalized Rocchio case with yes and no classes was handed out for self work, with centroid math and a practice task. The habit is the same: normalize, average by class, score cosine to each center, pick the nearest.
10.7.4 Rocchio versus nearest-neighbor trade
Rocchio is plain and fast but weak when classes spread thinly or miss round shapes. K nearest neighbors assigns the majority label among the K closest training points. It costs more at scoring time but handles odd and non-round shapes. In plain words, it assigns the majority class of the K nearest neighbors and handles the non-spherical data. The Rocchio centroid mean and nearest centroid with TF-IDF cosine versus neighbor vote contrast is the exam one-liner for this trade.
The pick is a trade between speed and shape freedom. To keep scoring light and data shape clean, use Rocchio. To allow messy shapes and weaker pre-processing, use nearest neighbors. Rocchio needs round groups with like radii. Nearest neighbors follows local streets and bends with the data, at the price of keeping all training points and scoring each new item against them.
Choosing K adds its own cost. The elbow route plots error on the y-axis against K on the x-axis and reruns the method for many K values, at times 10 or 12 runs, before settling near a bend such as K equal to 3. If K is already given, scoring is just gap checks plus a vote. Rocchio is linear and light. Nearest-neighbor cost hinges on gap type and on K search. Plain gaps such as Manhattan stay cheap, while wider gaps raise cost. Full K search with an elbow plot over many K values adds runs. In standard form, kNN test time is linear in training size times average lengths, while Rocchio test time is linear in class count times test terms, so kNN trails badly on large training sets.
Scope: Rocchio fits single round clusters per class with like spread. kNN fits lumpy, curved, or split classes. Assumption: Contiguity holds under the chosen weights and normalization. If it fails, both methods fail until features or weights are fixed.
Visual: picture Voronoi cells around each training point for 1-nearest neighbor. Each cell holds points nearer to its owner than to any other. Borders are straight cuts halfway between neighbors. With K above 1, those cells merge into larger majority zones with wavy edges that follow local density. The takeaway is that kNN draws bendy local borders while Rocchio draws straight global cuts between centers.
One trap is to run kNN on raw counts without normalization. Long docs then dominate gaps for length reasons, not topic reasons. A second trap is to pick K by gut feel. Too small a K copies noise. Too large a K washes out small classes. Run the elbow plot of error versus K and pick near the bend.
Exam note: be ready to state the trade in one line. Rocchio is fast with centroids but needs round groups. Nearest neighbors is more flexible but slower at scoring and needs K to be set. The elbow plot of error versus K to pick K plus TF-IDF cosine with normalization are the must-show steps.
10.7.5 Student Questions and Answers
Q: Once both centroids are known, do we just pick the nearest centroid for the new point with length normalization and cosine scores? A: Yes. Normalize lengths, score cosine closeness to each centroid, and assign the nearest centroid label. Angle is the sign that two vectors point the same way, so the smaller angle wins.
Q: In Rocchio work, should gaps or cosine scores be used to compare two vectors? A: Both point the same way here. Since both Rocchio and nearest neighbors use vector form, angle is the natural sign and cosine is the best angle measure. Gaps or cosine scores to compare two vectors rank the same for normalized vectors. On a flat plot the same choice reads as a gap.
Q: Which costs less, Rocchio or K nearest neighbors? A: Rocchio is linear and light. Nearest-neighbor cost hinges on gap type and on K search. Rocchio tests against a few centroids while kNN tests against the full training set. Plain gaps such as Manhattan stay cheap, while wider gaps raise cost. Full K search with an elbow plot over many K values adds runs, often 10 or 12 runs to find the bend near K equal to 3.
Q: Where does the main extra work in K nearest neighbors come from? A: From picking K. After K is fixed the vote is easy. Finding K with an elbow plot of error versus K forces repeat runs before the bend value is picked. Large training sets also raise each single test cost, since each test gap check scans many stored vectors.
Vectors place docs as points, contiguity groups like points, Rocchio averages each group into a centroid and cuts halfway between centers, and kNN votes among local neighbors for bendy borders. Use Rocchio for speed on round groups and kNN for shape freedom at higher test cost. That place-based view closes the lecture arc from standing queries to chance scores to map spots.
Exam Guidance Summary
No fixed mark split was given in this topic. The stress was on method know-how plus number work. Use this list as a final check before practice tasks.
- Expect prior math as over and smoothed likelihoods with plus one over plus . Prior math over and smoothed likelihoods decide the label when token proof is weak, so write both steps with repeats counted.
- Expect a short number task on multinomial Naive Bayes like the China case with priors 3 over 4 and 1 over 4, likelihoods 6 over 14 with 1 over 14, and 2 over 9, ending near 0.0003 versus 0.0001. Show Chinese cubed for three hits and state that China wins in the multinomial view.
- Expect a Bernoulli contrast that counts documents not hits, uses plus 2 below for present or absent, and scores absent words through one-minus-chance terms. The Bernoulli contrast ends near 0.005 versus 0.022 with a flip to non-China. Remember and as the presence-only pattern.
- Expect a one-line MAP versus maximum-likelihood contrast with the fair-coin versus biased-coin story. MAP carries prior weight for uneven classes. Maximum likelihood starts even and fits fair coins.
- Expect a Rocchio centroid definition as class mean and a nearest-centroid choice with TF-IDF plus normalization and cosine scores. State the Rocchio centroid mean and nearest centroid with TF-IDF cosine versus neighbor vote trade in one line.
- Expect the Rocchio versus nearest-neighbor trade as speed versus shape freedom, plus elbow plotting of error versus K to pick K. Name K equal to 3 as a typical bend after runs at many K values.
- Two practice items to close on your own: rerun the Bernoulli bottom-term case with 3 docs plus 2 and 1 doc plus 2, and state the kNN test cost as linear in training size versus Rocchio test cost as linear in class count.
Exam note: Lead each answer with the core formula, then numbers, then the one-line reason. Priors plus smoothing, China numbers 0.0003 versus 0.0001, Bernoulli absent-word flip, coin story for MAP, centroid mean with cosine, and speed versus shape trade with elbow K form the full must-know set.
Key Industry Applications
- Google Alerts and live filters act as standing queries over fresh news. A topic defined once flags each new matching page without rerunning a one-off search.
- Spam versus no-spam mail filtering uses red-flag words, links, sender signs, caps, and punctuation. Money words, urgent style, strange link targets, and unseen addresses add joint weight.
- Google News groups articles into sports, cinema, politics, finance, and business before ranking inside each group. Classification first narrows the set, then ranking orders within the topic.
- Sentiment grouping of reviews into positive, negative, or neutral guides buyer advice and recommendation. Prior shares matter when review words carry weak signal, as in short neutral lines.
- Language tagging of French versus English routes documents before deeper steps. Short character and word signs give fast early splits.
- Law-section presence checks and defect flags fit presence-only Bernoulli scoring. One hit is enough to matter, so binary occurrence beats hit counts.
- Gene-tag search such as BRCA1 in written reports and anomaly flags fit presence signs, with care because presence alone does not prove disease. A tag hit routes the report for expert review rather than deciding the case.
- Quantum, complexity, and PubMed topic search where repeat hits add weight fit count-based multinomial scoring. More hits mean more proof, so frequencies stay in the score.
- Radiology tumor marking on 400 to 500 magnetic-resonance slices per patient supplies gold labels at about 20 dollars per patient, showing why hand labels cost a lot. Those hand-marked stacks seed training sets for learned models that later score new scans.
- IEEE papers of 5000 to 10000 words and Springer papers of 2000 to 3000 words show why linear training and testing matter. Counting plus sums scale to long papers where combo models would stall.
Standing queries watch streams, chance scores file by words, and map spots file by place. Spam, news routing, sentiment, language tags, law presence, gene tags, topic search, and radiology labels each pick the scoring habit that matches whether one hit or many hits carry the proof.
IR Lecture 10 notes · Text Classification with Naive Bayes and Vector Space Models
Sections Breakdown
Retrospective search answers once on a fixed store; prospective search keeps a standing query on a stream, learned from annotated labels with spam as first case
Formal task picks label Y from C1 to CN for instance D in space X using bag-of-words plus title, author, affiliation, and mail metadata features
Feature selection keeps class-bearing words by chi-square and mutual information I(t,c) and drops redundant doubles shown by weight, height, and BMI
Manual annotation, rule-based models, and learned models compared through training data needs, cost, and fit for shifting wording
Naive Bayes core builds Bayes posterior token product MAP log priors smoothing chain with priors Nc over N and Laplace smoothing plus B
China example worked in multinomial hit counts and Bernoulli doc presence with absent terms, showing count win versus presence flip
Vector classification from contiguity to Rocchio centroids mu(c) with cosine to kNN votes, trading speed on round groups for shape freedom
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.
Prospective Search and Standing Queries
Must-know: Retrospective is one query on old docs; prospective keeps a standing query on a stream and files each new doc as relevant or not
Top pitfall: Thinking one magic word proves spam; joint weight of words, style, links, and sender history decides
Self-check: What is a standing query and how does Google Alerts show it?
Connects to: 10.2
Formal Task and Document Features
Must-know: Given instance D in space X, pick label Y from C1 to CN using bag-of-words plus metadata features
Top pitfall: Keeping every raw string as feature or dropping cheap metadata such as title and sender
Self-check: Name four metadata features for scientific articles besides body words.
Connects to: 10.1, 10.3
Feature Selection
Must-know: Rank words by I(t,c) and chi-square and drop redundant doubles such as weight plus height once BMI is kept
Top pitfall: Keeping too few words and starving the model, or trusting an expert list without count checks for doubles
Self-check: What does a large I(t,c) mean for word t and class c?
Connects to: 10.2, 10.5
Three Ways to Assign Labels
Must-know: Manual annotation gives gold labels at high cost; rules suit fixed wording; learned models need training data and suit shifting wording
Top pitfall: Mixing classification with clustering; testing on training items and reporting inflated scores
Self-check: Why is K-means clustering and not classification?
Connects to: 10.3, 10.5
Naive Bayes Core
Must-know: MAP picks argmax posterior; prior Nc over N plus Laplace smoothing with plus B decide label when token proof is weak; logs prevent underflow
Top pitfall: Forgetting smoothing for one class so a single unseen word zeroes the full score; training on papers and testing on mails
Self-check: Why do logs keep the same MAP winner while avoiding underflow?
Connects to: 10.4, 10.6
Worked China Example: Multinomial and Bernoulli
Must-know: Multinomial counts hits near 0.0003 vs 0.0001 for China win; Bernoulli counts docs with plus 2 below and absent terms near 0.005 vs 0.022 flipping to non-China
Top pitfall: Counting repeat hits in Bernoulli or using vocabulary size below instead of plus 2; forgetting absent-word terms
Self-check: Why does the same test flip from China to non-China between models?
Connects to: 10.5, 10.7
Vector Space Classification with Rocchio and Nearest Neighbors
Must-know: Rocchio centroid mean with TF-IDF cosine and nearest centroid versus kNN majority vote; Rocchio fast on round groups, kNN flexible but slower
Top pitfall: Running kNN on raw counts without normalization; picking K by gut feel instead of elbow plot near K equal to 3
Self-check: When should gaps or cosine be used and why is angle the natural sign?
Connects to: 10.5, 10.6
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.