Sub topic 12
Naive Bayes in scikit-learn
This chapter assumes you know the naive Bayes decision rule, how priors and likelihoods are estimated, and why smoothing and log probabilities matter. It also assumes you can split data into train and test sets in Python. Here you will map those ideas onto scikit-learn's estimators.
The estimator family
The sklearn.naive_bayes module has one class per likelihood model. All of them share the usual fit, predict, predict_proba and score methods.
| Class | Feature type | Key parameter |
|---|---|---|
| `GaussianNB` | Continuous values | `var_smoothing` |
| `MultinomialNB` | Counts or TF-IDF weights | `alpha` |
| `BernoulliNB` | Binary (present or absent) | `alpha`, `binarize` |
| `ComplementNB` | Counts, imbalanced classes | `alpha` |
| `CategoricalNB` | Integer-coded categories | `alpha` |
Fitting GaussianNB
GaussianNB stores one mean and one variance per class and feature. The example below fits it on the iris data and inspects what it learned.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
model = GaussianNB()
model.fit(X_train, y_train)
print("accuracy:", model.score(X_test, y_test))
print("class priors:", model.class_prior_)
print("means shape:", model.theta_.shape)
print("variances shape:", model.var_.shape)
print("first test row probabilities:", model.predict_proba(X_test[:1]))The fitted attributes match the parameters you estimated by hand. class_prior_ holds the priors. theta_ holds the per-class means, and var_ holds the per-class variances. Both have shape (n_classes, n_features).
Training is a single pass over the data. There is no iterative optimizer and no learning rate, so fitting is fast even on large datasets.
Fitting MultinomialNB
The multinomial model expects non-negative counts. A pipeline can turn raw text into counts and classify them in one object.
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"]))Here alpha=1.0 is Laplace smoothing. Smaller values trust the observed counts more, and larger values pull the likelihoods toward uniform. Inside the model, class_log_prior_ and feature_log_prob_ hold the log quantities, so scoring already happens in log space.
Common errors
- Negative feature values.
MultinomialNBraises aValueErroron negative inputs, for example after standardizing withStandardScaler. Use counts or TF-IDF, or switch toGaussianNB. - Wrong variant for the data. Feeding word counts to
GaussianNBruns without error but fits a poor model. Match the class to the feature type. - Zero variance in
GaussianNB. A feature that is constant within a class has variance zero.var_smoothingadds a small fraction of the largest feature variance to prevent division by zero, so tune it if you see warnings or unstable results. - Fitting the vectorizer on test data. Put
CountVectorizerin the pipeline so it learns its vocabulary from the training split only.
Exercise
You standardize a bag-of-words matrix with StandardScaler and then call MultinomialNB.fit. What happens, and what should you do instead?
Show answer
Standardizing produces negative values, so MultinomialNB raises a ValueError because it requires non-negative features. Skip the scaler and use raw counts or TF-IDF weights. Standardizing would also be unnecessary, since the model works from per-class counts rather than distances.