Sub topic 13
Building a text classifier with bag-of-words
This chapter assumes you know the multinomial naive Bayes model, Laplace smoothing, and basic scikit-learn usage (fit, predict). Here you connect them into a working text classifier.
From text to counts
Naive Bayes needs numeric features, but your data is raw strings. A bag-of-words representation turns each document into a vector of word counts. It keeps how often each word appears and discards word order. This matches the multinomial model, where each word position is an independent draw from a class-specific word distribution.
Inspecting the vectorizer
CountVectorizer learns a vocabulary during fit and maps each document to a row of counts.
from sklearn.feature_extraction.text import CountVectorizer
texts = [
"free prize now",
"meeting at noon",
"free offer now",
"project meeting notes",
]
vec = CountVectorizer()
X = vec.fit_transform(texts)
print(vec.get_feature_names_out())
print(X.shape)
print(X.toarray())The matrix X has one row per document and one column per vocabulary word. It is stored sparse, because most entries are zero.
Training the classifier in a pipeline
Wrap the vectorizer and the model in one pipeline. The vocabulary is then learned from training data only, and the same transformation is applied at prediction time.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
texts = [
"free prize now",
"meeting at noon",
"free offer now",
"project meeting notes",
]
labels = ["spam", "ham", "spam", "ham"]
clf = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))
clf.fit(texts, labels)
print(clf.predict(["free meeting now"]))
print(clf.predict_proba(["free meeting now"]))The test message contains "free" and "now", which appear mostly in spam, and "meeting", which appears only in ham. With alpha=1.0, the spam score uses likelihoods 3/15, 3/15 and 1/15. The ham score uses 1/15, 1/15 and 3/15. Spam wins, and the probabilities come out as about 0.25 for ham and 0.75 for spam. Columns follow clf.classes_, which is sorted alphabetically.
Common errors
- Fitting the vectorizer on all the data. Fit it on the training split only. Otherwise test vocabulary leaks into training.
- Ignoring unseen words.
CountVectorizersilently drops words outside the training vocabulary. This is the correct behavior, but it means a document of entirely new words is scored by priors alone. - Dropping short tokens unknowingly. The default token pattern keeps only tokens of two or more alphanumeric characters, so "a" and "I" disappear.
- Treating
alphaas fixed. Smoothing strength matters most with small data and large vocabularies. Tune it with cross-validation.
Exercise
Why should you use a pipeline instead of calling CountVectorizer.fit_transform on the full dataset before splitting into train and test sets?
Show answer
Fitting the vectorizer on the full dataset lets the vocabulary (and any statistics derived from it) include test documents, which leaks information into training and makes evaluation overly optimistic. A pipeline fits the vectorizer on the training data only, then applies that fixed vocabulary to the test data. It also guarantees the same preprocessing at prediction time.