Sub topic 3
Naive Bayes in scikit-learn
Assume you know basic probability, supervised classification, Python, and train/test splits. In scikit-learn, Naive Bayes models provide fast classifiers with few parameters.
Naive Bayes in scikit-learn
Choose the model that matches the feature type:
| Model | Typical features |
|---|---|
| `GaussianNB` | Continuous measurements |
| `MultinomialNB` | Counts or nonnegative frequencies |
| `BernoulliNB` | Binary present-or-absent features |
Building a text classifier with bag-of-words
A bag-of-words representation converts text into counts of vocabulary words. CountVectorizer creates this representation, and MultinomialNB learns word frequencies for each class.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
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",
"claim free prize", "project meeting tomorrow",
]
labels = ["spam", "ham", "spam", "ham", "spam", "ham"]
x_train, x_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.33, random_state=0, stratify=labels
)
model = make_pipeline(
CountVectorizer(),
MultinomialNB(alpha=1.0)
)
model.fit(x_train, y_train)
print(model.predict(["free meeting now"]))
print(model.predict_proba(["free meeting now"]))The alpha parameter applies additive smoothing. It prevents an unseen word from receiving probability zero.
Evaluating the classifier
Accuracy is useful when classes have similar sizes. For imbalanced data, also inspect precision, recall, and the confusion matrix.
from sklearn.metrics import classification_report
print(classification_report(y_test, model.predict(x_test)))Keep the vectorizer inside the pipeline. This prevents test vocabulary from influencing training.
Limitations, calibration, and imbalanced text
The independence assumption ignores relationships such as “not good.” Despite this, word frequencies often separate topics strongly, so classification can work well. Predicted probabilities may be poorly calibrated: a prediction of 0.9 does not necessarily mean that 90% of such predictions are correct.
Use a validation set and CalibratedClassifierCV when reliable probabilities matter. For imbalanced text, ComplementNB estimates each class using the other classes' word statistics and often handles rare minority classes better than MultinomialNB.
Exercise
Which scikit-learn model is a natural first choice for word-count features?
Show answer
MultinomialNB, usually combined with CountVectorizer in a pipeline.