Text Classification
The Naïve Bayes algorithm
IP notice: most slides from: Chris Manning, plus some from William Cohen, Chien Chin Chen, Jason Eisner, David Yarowsky, Dan Jurafsky, P. Nakov, Marti Hearst, Barbara Rosario
Università di Pisa
Outline
Is this spam?
Author identification
James Madison
Alexander Hamilton
Generated by ChatGPT?
"AI Text Classifier” by OpenAI (https://openai.com/blog/new-ai-classifier-for-indicating-ai-written-text)
GPTZero by Edward Tian, Princeton University (https://gptzero.me/)
Positive or negative movie review?
What is the subject of this article?
MeSH Subject Category Hierarchy
?
MEDLINE Article
More Applications
e.g., "finance," "sports," "news>world>asia>business"
e.g., "editorials" "movie-reviews" "news“
e.g., “like”, “hate”, “neutral”
e.g., “contains adult language” : “doesn’t”
Text Classification: definition
f: D → C
Slide from William Cohen
Document Classification
Slide from Chris Manning
Multimedia
GUI
Garb.Coll.
Semantics
ML
Planning
planning
temporal
reasoning
plan
language...
programming
semantics
language
proof...
learning
intelligence
algorithm
reinforcement
network...
garbage
collection
memory
optimization
region...
“planning
language
proof
intelligence”
Training
Data:
Test
Data:
Classes:
(AI)
(Programming)
(HCI)
...
...
Classification Methods: Hand-coded rules
Slide from Chris Manning
Classification Methods: Supervised Machine Learning
Classification Methods: Supervised Machine Learning
Naïve Bayes Intuition
Naïve Bayes Intuition
Bag of words representation
Slide from William Cohen
ARGENTINE 1986/87 GRAIN/OILSEED REGISTRATIONS
BUENOS AIRES, Feb 26
Argentine grain board figures show crop registrations of grains, oilseeds and their products to February 11, in thousands of tonnes, showing those for future shipments month, 1986/87 total and 1985/86 total to February 12, 1986, in brackets:
The board also detailed export registrations for subproducts, as follows....
Categories: grain, wheat
Bag of words representation
xxxxxxxxxxxxxxxxxxx GRAIN/OILSEED xxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxx grain xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx grains, oilseeds xxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxx tonnes, xxxxxxxxxxxxxxxxx shipments xxxxxxxxxxxx total xxxxxxxxx total xxxxxxxx xxxxxxxxxxxxxxxxxxxx:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx....
Categories: grain, wheat
Slide from William Cohen
The Bag of Words Representation
Representing text for classification
Slide from William Cohen
ARGENTINE 1986/87 GRAIN/OILSEED REGISTRATIONS
BUENOS AIRES, Feb 26
Argentine grain board figures show crop registrations of grains, oilseeds and their products to February 11, in thousands of tonnes, showing those for future shipments month, 1986/87 total and 1985/86 total to February 12, 1986, in brackets:
The board also detailed export registrations for subproducts, as follows....
f(
)=c
?
What is the best representation for the document d being classified?
simplest useful
Bag of words representation
xxxxxxxxxxxxxxxxxxx GRAIN/OILSEED xxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxx grain xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx grains, oilseeds xxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxx tonnes, xxxxxxxxxxxxxxxxx shipments xxxxxxxxxxxx total xxxxxxxxx total xxxxxxxx xxxxxxxxxxxxxxxxxxxx:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx....
Categories: grain, wheat
grain(s) | 3 |
oilseed(s) | 2 |
total | 3 |
wheat | 1 |
maize | 1 |
soybean | 1 |
tonnes | 1 |
... | ... |
word
freq
Slide from William Cohen
Formalizing Naïve Bayes
Bayes’ Rule
Allows us to swap the conditioning
Sometimes easier to estimate one kind of dependence than the other
Conditional Probability
P(B|A) = P(A ∩ B) / P(A)
S
A
B
Deriving Bayes’ Rule
Bayes Rule Applied to Documents and Classes
Slide from Chris Manning
The Text Classification Problem
Γ(T) = γ
Slide from Chien Chin Chen
Multinomial Naïve Bayes Classifiers
We represent an instance D as a vector of features.
Task: Classify a new instance D into one of the classes cj ∈ C
Slide from Chris Manning
The probability of a
document d being in class c.
Bayes’ Rule
We can ignore the denominator
Naïve Bayes Assumption
P(cj)
P(x1,x2,…,xn|cj)
Naïve Bayes Conditional Independence Assumption:
Slide from Chris Manning
The Naïve Bayes Classifier
P(X1, …, X5 | C) = P(X1 | C) ∙ P(X1 | C) ∙ … P(X5 | C)
Flu
X1
X2
X5
X3
X4
fever
sinus
cough
runnynose
muscle-ache
Slide from Chris Manning
Multinomial Naive Bayes Text Classification
Features are just the words in the document.
Slide from Chris Manning
Learning the Model
Simplest: Maximum Likelihood Estimate
C
X1
X2
X5
X3
X4
X6
Slide from Chris Manning
Problem with Max Likelihood
P(X1, …, X5 | C) = P(X1 | C) ∙ P(X2 | C) ∙ … P(X5 | C)
Flu
X1
X2
X5
X3
X4
fever
sinus
cough
runnynose
muscle-ache
Slide from Chris Manning
Smoothing to Avoid Overfitting
Bayesian Unigram Prior:
Slide from Chris Manning
# of values of Xi
overall fraction in data where Xi=xi,k
extent of
“smoothing”
Laplace:
Naïve Bayes: Learning
docsj ← subset of documents for which the target class is cj
Textj ← single document containing all docsj
for each word wk in Vocabulary
nkj ← number of occurrences of wk in Textj
nj ← number of occurrences in Textj
Slide from Chris Manning
Naïve Bayes: Classifying
Slide from Chris Manning
i.e. discard unknown words
Underflow Prevention: log space
Slide from Chris Manning
Naïve Bayes Generative Model for Text
spam
ham
Slide from Ray Mooney
Choose a class c according to P(c)
Then choose a word from that class with probability P(x|c)
Essentially model probability of each class as class-specific unigram language model
$
science
homework
Friday
exam
computer
May
PM
test
March
score
spam
ham
spam
spam
ham
spam
ham
ham
spam
Category
nude
deal
Nigeria
hot
Viagra
lottery
!!
!
win
Viagra
!
Viagra
deal
hot
!!
Naïve Bayes and Language Modeling
Each class = Unigram language model
w | P(w | c) |
I | 0.1 |
love | 0.1 |
this | 0.05 |
fun | 0.01 |
film | 0.1 |
I | love | this | fun | film |
0.1 | 0.1 | 0.05 | 0.01 | 0.1 |
P(s | c) = 0.0000005
Naïve Bayes Language Model
Two classes: in language, out language
In Language | |
I | 0.1 |
love | 0.1 |
this | 0.05 |
fun | 0.01 |
film | 0.1 |
Out Language | |
I | 0.2 |
love | 0.001 |
this | 0.01 |
fun | 0.005 |
film | 0.1 |
I | love | this | fun | film |
0.1 | 0.1 | 0.05 | 0.01 | 0.1 |
0.2 | 0.001 | 0.01 | 0.005 | 0.1 |
P(s | in) > P(s | out)
Naïve Bayes Classification
Win lotttery $ !
?? ??
Slide from Ray Mooney
spam
ham
$
Friday
exam
computer
May
PM
test
March
score
spam
ham
spam
spam
ham
spam
ham
ham
spam
Category
nude
deal
Nigeria
hot
Viagra
lottery
!!
!
win
Viagra
!
Viagra
deal
hot
!!
NB Text Classification Example
Vocabulary V = {Chinese, Beijing, Shanghai, Macao, Tokyo, Japan} and |V| = 6.
P(c) = 3/4 and P(~c) = 1/4
P(Chinese|c) = (5+1) / (8+6) = 6/14 = 3/7
P(Chinese|~c) = (1+1) / (3+6) = 2/9
P(Tokyo|c) = P(Japan|c) = (0+1)/(8+6) =1/14
P(Chinese|~c) = (1+1)/(3+6) = 2/9
P(Tokyo|~c) = p(Japan|~c) = (1+1)/(3+6) = 2/9
P(c|d) = 3/4 * (3/7)3 * 1/14 * 1/14
≈ 0.0003
P(~c|d) = 1/4 * (2/9)3 * 2/9 * 2/9
≈ 0.0001
Slide from Chien Chin Chen
Set | Doc | Words | Class |
Train | 1 | Chinese Bejing Chinese | c |
| 2 | Chinese Chinese Shanghai | c |
| 3 | Chinese Macao | c |
| 4 | Tokyo Japan Chinese | ~c |
Test | 5 | Chinese Chinese Chinese Tokyo Japan | ? |
Naïve Bayes Text Classification
Naïve Bayes algorithm – training phase.
Slide from Chien Chin Chen
TrainMultinomialNB(C, D)
V = ExtractVocabulary(D)
N = CountDocs(D)
for each c in C
Nc = CountDocsInClass(D, c)
prior[c] = Nc / Count(C)
textc = TextOfAllDocsInClass(D, c)
for each t in V
Ftc = CountOccurrencesOfTerm(t, textc)
for each t in V
condprob[t][c] = (Ftc+1) / ∑(Ft’c+1)
return V, prior, condprob
Naïve Bayes Text Classification
Naïve Bayes algorithm – prediction phase.
Slide from Chien Chin Chen
ApplyMultinomialNB(C, V, prior, condProb, d)
W = ExtractTokensFromDoc(V, d)
for each c in C
score[c] = log prior[c]
for each t in W
score[c] += log condprob[t][c]
return argmaxc score[c]
Evaluating Categorization
Slide from Chris Manning
Measuring Performance
Trade off precision vs. recall by setting threshold
Measure the curve on annotated dev data (or test data)
Choose a threshold where user is comfortable
Slide from Jason Eisner
Measuring Performance
Slide from Jason Eisner
low threshold:
keep all the good stuff,�but a lot of the bad too
high threshold:
all we keep is good,
but we don’t keep much
OK for spam filtering and legal search
OK for search engines (maybe)
would prefer to be here!
point where
precision=recall
(often reported)
The 2-by-2 contingency table
| Correct | Incorrect |
Selected | True Positive | False Positive |
Not selected | False Negative | True Negative |
Precision and Recall
A Combined measure: F
Multiclass Classification
Micro- vs. Macro-Averaging
Micro- vs. Macro-Averaging: Example
54
| Truth: yes | Truth: no |
Classifier: yes | 10 | 10 |
Classifier: no | 10 | 970 |
| Truth: yes | Truth: no |
Classifier: yes | 90 | 10 |
Classifier: no | 10 | 890 |
| Truth: yes | Truth: no |
Classifier: yes | 100 | 20 |
Classifier: no | 20 | 1860 |
Class 1
Class 2
Micro Ave. Table
More Complicated Cases of Measuring Performance
Slide from Jason Eisner
Which articles are most Sports-like?
Which articles / webpages most relevant?
Evaluation Benchmark
Evaluation: Classic Reuters-21578 Data Set
57
Common categories
(#train, #test)
Reuters Text Categorization data set
58
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" OLDID="12981" NEWID="798">
<DATE> 2-MAR-1987 16:51:43.42</DATE>
<TOPICS><D>livestock</D><D>hog</D></TOPICS>
<TITLE>AMERICAN PORK CONGRESS KICKS OFF TOMORROW</TITLE>
<DATELINE> CHICAGO, March 2 - </DATELINE><BODY>The American Pork Congress kicks off tomorrow, March 3, in Indianapolis with 160 of the nations pork producers from 44 member states determining industry positions on a number of issues, according to the National Pork Producers Council, NPPC.
Delegates to the three day Congress will be considering 26 resolutions concerning various issues, including the future direction of farm policy and the tax law as it applies to the agriculture sector. The delegates will also debate whether to endorse concepts of a national PRV (pseudorabies virus) control and eradication program, the NPPC said.
A large trade show, in conjunction with the congress, will feature the latest in technology in all areas of the industry, the NPPC added. Reuter
</BODY></TEXT></REUTERS>
Confusion matrix c
Docs in test set | Assigned UK | Assigned poultry | Assigned wheat | Assigned coffee | Assigned interest | Assigned trade |
True UK | 95 | 1 | 13 | 0 | 1 | 0 |
True poultry | 0 | 1 | 0 | 0 | 0 | 0 |
True wheat | 10 | 90 | 0 | 1 | 0 | 0 |
True coffee | 0 | 0 | 0 | 34 | 3 | 7 |
True interest | - | 1 | 2 | 13 | 26 | 5 |
True trade | 0 | 0 | 2 | 14 | 5 | 10 |
Development Test Sets and Cross-validation
Training set
Development Test Set
Test Set
Test Set
Training Set
Training Set
Dev Test
Training Set
Dev Test
Dev Test
Training size
The more the better! (usually)
Results for text classification*
*From: Improving the Performance of Naive Bayes for Text Classification, Shen and Yang,
Test error vs training size on two classes
Slide from Nakov/Hearst/Rosario
Violation of NB Assumptions
Slide from Chris Manning
Naïve Bayes is Not So Naïve
Goal: Financial services industry direct mail response prediction model: Predict if the recipient of mail will actually respond to the advertisement – 750,000 records.
Irrelevant Features cancel each other without affecting results
Instead Decision Trees can heavily suffer from this.
Decision Trees suffer from fragmentation in such cases – especially if little data
Slide from Chris Manning
Naïve Bayes is Not So Naïve
If assumed independence is correct, then it is the Bayes Optimal Classifier for problem
Learning with one pass of counting over the data; testing linear in the number of attributes, and document collection size
Can be trained incrementally, on new examples
SPAM Filtering: SpamAssassin
Slide from Chris Manning
SpamAssassin Tests
Conclusions