Sub topic 12
Naive Bayes in scikit-learn
This chapter assumes you know the naive Bayes decision rule, Laplace smoothing, and log-space scoring from earlier chapters. It also assumes basic NumPy and a train/test split. Here you map those ideas onto scikit-learn's API, learn which attributes expose the fitted parameters, and learn the errors people hit most often.
The estimator family
The sklearn.naive_bayes module has five classifiers. They share one interface and differ in how they model P(x_j | y).
| Class | Feature type | Likelihood model | Main hyperparameter |
|---|---|---|---|
| `GaussianNB` | Continuous | Normal per class and feature | `var_smoothing` |
| `MultinomialNB` | Non-negative counts or weights | Multinomial over features | `alpha` |
| `BernoulliNB` | Binary indicators | Bernoulli per feature | `alpha`, `binarize` |
| `ComplementNB` | Counts, imbalanced classes | Statistics of the complement of each class | `alpha`, `norm` |
| `CategoricalNB` | Integer-coded categories | Categorical per feature | `alpha`, `min_categories` |
All five provide fit, predict, predict_proba, predict_log_proba, and score. predict_log_proba returns normalized log posteriors. Prefer it when you compare very small probabilities.
Fitting GaussianNB and reading its parameters
GaussianNB estimates a mean and a variance for every class and feature. It exposes them directly, so you can check the fit against the formulas.
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 attributes map onto the model as follows:
class_prior_holds P(y), estimated from class frequencies.theta_holds the per-class feature means, with shape(n_classes, n_features).var_holds the per-class feature variances, with the same shape.classes_gives the label order for every column ofpredict_proba.
var_smoothing adds a fraction of the largest feature variance to every variance. The default is 1e-9. This is not Laplace smoothing. It keeps a feature that is constant within a class from producing a zero variance and an infinite density. If the model overfits or behaves oddly on noisy features, raising it to 1e-6 or higher acts as a regularizer.
Fitting MultinomialNB and reading its parameters
MultinomialNB stores log quantities, which matches the log-space scoring you derived earlier.
class_log_prior_is log P(y), with shape(n_classes,).feature_log_prob_is log P(xj | y) after smoothing, with shape `(nclasses, n_features)`.class_count_andfeature_count_are the raw counts used for the estimates.
Prediction is effectively X @ feature_log_prob_.T + class_log_prior_, followed by an argmax. Because it is a matrix product, prediction on sparse count matrices is fast.
The next example reads the learned words back out of a model:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = [
"free prize now",
"meeting at noon",
"free offer now",
"project meeting notes",
]
labels = ["spam", "ham", "spam", "ham"]
vec = CountVectorizer()
X = vec.fit_transform(texts)
nb = MultinomialNB(alpha=1.0).fit(X, labels)
words = vec.get_feature_names_out()
for i, cls in enumerate(nb.classes_):
top = np.argsort(nb.feature_log_prob_[i])[::-1][:3]
print(cls, words[top].tolist())This kind of inspection is a cheap sanity check. If the top "spam" words are not spammy, suspect your labels or your tokenization before you suspect the model.
Text pipelines
For raw text, chain the vectorizer and the classifier in a Pipeline. The vectorizer's vocabulary is then learned only from training data, and cross-validation does not leak test vocabulary.
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"]))Words that were not seen in training are ignored by CountVectorizer, so they contribute nothing to the score. This matches the if w in vocab check in a from-scratch implementation.
TfidfVectorizer also works with MultinomialNB. The fractional TF-IDF weights are not true counts, but they are non-negative and often give better accuracy in practice.
Hyperparameters that matter
alpha
alpha is the additive smoothing constant. alpha=1.0 is Laplace smoothing, and smaller values such as 0.1 are Lidstone smoothing. Treat it as a tuned hyperparameter and search it on a log scale, for example [0.01, 0.1, 0.5, 1.0].
Setting alpha=0 brings back the zero-probability problem. Recent versions of scikit-learn clip very small values to 1e-10 and emit a warning unless you pass force_alpha=True.
Priors
fit_prior=True estimates P(y) from training frequencies. With fit_prior=False, the classes get a uniform prior. You can also pass class_prior=[...] explicitly. Use this when the deployment class mix differs from the training mix, or when you want to trade recall against precision without changing the likelihoods.
Binarizing
BernoulliNB thresholds its input at binarize=0.0 by default, so any positive value becomes 1. Set binarize=None if your input is already binary. Unlike the multinomial model, it also penalizes a word for being absent, so it can behave differently on short documents.
Incremental learning
All variants except CategoricalNB's older versions of partial_fit workflows share the same pattern: the first call must pass classes, and later calls are batches. This works for data that does not fit in memory.
import numpy as np
from sklearn.naive_bayes import MultinomialNB
X = np.array([[2, 1, 0], [0, 0, 3], [3, 0, 1], [0, 1, 4]])
y = np.array([0, 1, 0, 1])
clf = MultinomialNB()
clf.partial_fit(X[:2], y[:2], classes=[0, 1])
clf.partial_fit(X[2:], y[2:])
print(clf.class_count_)
print(clf.predict([[1, 0, 0]]))Because the model only accumulates counts, the batch order does not change the result. For text, use a stateless HashingVectorizer in place of CountVectorizer, since a vocabulary cannot grow between batches. Hashing can produce negative values unless you set alternate_sign=False, which MultinomialNB needs.
Common errors
- Negative feature values.
MultinomialNB,ComplementNB, andCategoricalNBraise aValueErrorfor negative input. AStandardScalerbefore them causes this. UseMinMaxScaler, or switch toGaussianNB. - Wrong class for the data.
GaussianNBon sparse word counts runs without error but fits normal densities to skewed data, and accuracy suffers. Match the class to the feature type. - Feature count mismatch. A
CategoricalNBcategory in the test set that was not seen in training raises an error. Setmin_categoriesto cover all possible values. - Misreading
predict_proba. The columns followclasses_, not the order of your labels list. Always readclf.classes_. - Trusting the probabilities. The values tend to sit near 0 or 1 even when the model is wrong. Use them for ranking, and calibrate them before using them as risk estimates. A later chapter covers calibration.
Exercise
You build a pipeline of StandardScaler() followed by MultinomialNB() on word-count features, and fit raises a ValueError about negative values. Why does this happen, and name two ways to fix it.
Show answer
StandardScaler subtracts the mean, so many values become negative, and the multinomial model requires non-negative counts or weights. Fix it by removing the scaler (counts need no scaling), by using MinMaxScaler so values stay in [0, 1], or by switching to GaussianNB if the features are truly continuous.
Exercise
A fitted MultinomialNB has feature_log_prob_ with shape (3, 5000). What do the 3 and the 5000 represent, and which attribute gives the log prior for each class?
Show answer
The 3 is the number of classes and the 5000 is the number of features (the vocabulary size). Each entry is log P(word | class) after smoothing. The log priors are in class_log_prior_, which has shape (3,).