Sub topic 13
Building a text classifier with bag-of-words
This chapter assumes you know the multinomial naive Bayes model, Laplace smoothing, and log-space scoring from earlier chapters. It also assumes basic scikit-learn use (fit, predict, train_test_split). Here you turn raw strings into count features, train a classifier on them, and check what it learned.
From strings to count vectors
Naive Bayes needs numeric features, and raw text is a string. The bag-of-words representation fixes this by discarding word order and recording only how often each vocabulary word appears in each document. This matches the multinomial model, which treats a document as a bag of independent word draws from a class-specific distribution.
CountVectorizer does the conversion in three steps:
- Tokenize. Lowercase the text and split it with a regular expression. The default pattern keeps runs of two or more word characters, so single-letter tokens such as "a" disappear.
- Build a vocabulary.
fitcollects every distinct token from the training texts and sorts them alphabetically. - Count.
transformreturns a sparse matrix with one row per document and one column per vocabulary word.
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.toarray())The vocabulary has nine words, so X has shape 4 by 9. Most real matrices are far larger and mostly zeros, which is why scikit-learn stores them as sparse matrices. MultinomialNB accepts sparse input directly.
Train and test with a pipeline
Wrap the vectorizer and classifier in a Pipeline. This matters for correctness. The vocabulary must be learned from training texts only. If you fit the vectorizer on the full dataset before splitting, words that appear only in test documents leak into the model's vocabulary. A pipeline fits the vectorizer on the training fold alone, including inside cross-validation.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
texts = [
"win a free prize now",
"free offer click now",
"claim your free cash prize",
"limited offer win cash now",
"click to claim free gift",
"urgent offer win free money",
"cash prize waiting click now",
"free gift card offer today",
"meeting moved to noon",
"project notes attached",
"lunch at noon tomorrow",
"please review the project plan",
"notes from the team meeting",
"schedule a call about the project",
"can we move the meeting today",
"send me the report before lunch",
]
labels = ["spam"] * 8 + ["ham"] * 8
X_train, X_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.25, random_state=0, stratify=labels
)
clf = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))
clf.fit(X_train, y_train)
print(classification_report(y_test, clf.predict(X_test), zero_division=0))
print(clf.predict(["claim a free prize", "notes for the project meeting"]))With only four test documents, the numbers are anecdotal. The code shows the workflow, not a reliable accuracy estimate. Real evaluation needs hundreds or thousands of labeled documents and, ideally, cross-validation.
What happens to unseen words
At prediction time, transform ignores any word not in the training vocabulary. In the multinomial model this is the correct behavior. A word with no learned likelihood has no basis for favoring one class over another, so it contributes nothing to the scores. Smoothing handles a different case: a word that is in the vocabulary but never occurred in some class. That word still gets a small nonzero probability for the class, so the class's score is not driven to negative infinity.
A document made entirely of unseen words becomes a row of zeros. Its scores then reduce to the log priors, and the model predicts the more common class.
Inspecting what the model learned
The fitted classifier stores log likelihoods in feature_log_prob_. It has one row per class, in the order of classes_, and one column per vocabulary word. Subtracting the rows gives a log-odds score for each word. This shows which words push a document toward spam.
import numpy as np
vec = clf.named_steps["countvectorizer"]
nb = clf.named_steps["multinomialnb"]
words = vec.get_feature_names_out()
spam_idx = list(nb.classes_).index("spam")
ham_idx = list(nb.classes_).index("ham")
log_odds = nb.feature_log_prob_[spam_idx] - nb.feature_log_prob_[ham_idx]
order = np.argsort(log_odds)[::-1]
print("most spam-like:", [words[i] for i in order[:5]])
print("most ham-like:", [words[i] for i in order[-5:]])This kind of inspection is a strength of naive Bayes. Each word's contribution to the score is a separate additive term, so you can read off exactly why a document was classified as it was. Look for tokens that reflect dataset quirks instead of meaning, such as email header fragments or a signature name that appears in only one class.
Tuning the vectorizer and alpha
Most of the accuracy you can gain comes from the features, not the classifier. These CountVectorizer options are the usual levers:
| Option | Effect | Typical use |
|---|---|---|
| `stop_words="english"` | Drops common function words | Removes noise on topic classification |
| `min_df=2` | Drops words seen in fewer than two documents | Shrinks the vocabulary and removes typos |
| `ngram_range=(1, 2)` | Adds two-word phrases as features | Captures "not good" and similar phrases |
| `binary=True` | Records presence instead of counts | Short texts, or feeding `BernoulliNB`-style signals |
| `lowercase=False` | Keeps case | When case carries meaning, such as names or codes |
Tune these together with alpha, using cross-validation over the whole pipeline. Parameter names use the step name, a double underscore, then the parameter.
from sklearn.model_selection import GridSearchCV
param_grid = {
"countvectorizer__ngram_range": [(1, 1), (1, 2)],
"countvectorizer__min_df": [1, 2],
"multinomialnb__alpha": [0.1, 0.5, 1.0],
}
search = GridSearchCV(clf, param_grid, cv=3, scoring="f1_macro")
search.fit(X_train, y_train)
print(search.best_params_)
print(search.best_score_)Smaller alpha values trust the observed counts more. Larger values pull every likelihood toward uniform. On large corpora the best alpha is often well below 1. Treat it as a hyperparameter instead of defaulting to Laplace's value of 1.
Common errors
- Fitting the vectorizer outside the pipeline. This leaks test vocabulary and inflates scores. Keep the vectorizer in the pipeline.
- Passing a single string.
clf.predict("free prize")iterates over characters. Pass a list:clf.predict(["free prize"]). - Negative features.
MultinomialNBraises an error on negative values. This happens if you scale or center features before it. Counts and TF-IDF weights are fine. - Confusing the models. Counts and TF-IDF suit
MultinomialNB. Presence or absence features suitBernoulliNB, which also penalizes words that are missing from a document. Continuous measurements suitGaussianNB. - Trusting
predict_probaat face value. Long documents produce probabilities near 0 or 1 because many correlated words each add evidence. Use the ranking, or calibrate the output as a later chapter shows.
Exercise
A teammate fits CountVectorizer on all 1,000 labeled messages, then splits into train and test sets and reports 97 percent test accuracy. Explain the problem and how to restructure the code.
Show answer
The vocabulary was built using the test messages, so information from the test set leaked into training. The score is likely optimistic. Split the raw texts first, then use make_pipeline(CountVectorizer(), MultinomialNB()) so that fit learns the vocabulary from the training texts only. The same pipeline can go into cross_val_score or GridSearchCV, which refit the vectorizer on each training fold.
Exercise
After training, a document containing only words that were never in the training vocabulary is classified as "ham". Why does the model pick "ham", and what does this say about the prediction's reliability?
Show answer
The unseen words are dropped, so the count row is all zeros and each class's score equals its log prior. The model returns the class with the larger prior, here "ham" (the more common class in the training data). The prediction carries no evidence from the document, so it should not be trusted. In production, flag documents with no known vocabulary for review.