Note
Go to the end to download the full example code.
MixedNB on mixed continuous and categorical data#
A dataset has one continuous feature and one categorical feature with three categories. Each class generates both: the continuous feature is Gaussian with unit variance, centered at -1 for class 0 and at 1 for class 1, and the category follows a different distribution per class (class 0 mostly draws category 0, class 1 mostly category 2).
skbn.MixedNB models each feature with the distribution that
generated it. It is compared with two scikit-learn pipelines. The first
one-hot encodes the category and fits sklearn.naive_bayes.GaussianNB,
so the category indicators are treated as Gaussian variables. The second bins
the continuous feature into five quantile bins and fits
sklearn.naive_bayes.CategoricalNB, which discards the position of
the value inside each bin. The figure shows the probability of class 1 over
the feature plane for each model, with the test accuracy and log loss in the
titles.

# Author: The scikit-bayes Developers
# SPDX-License-Identifier: BSD-3-Clause
import warnings
import matplotlib.pyplot as plt
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.metrics import accuracy_score, log_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import CategoricalNB, GaussianNB
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder
from skbn import MixedNB
warnings.filterwarnings("ignore")
np.random.seed(42)
n_samples = 1000
# Class 0: continuous feature centered at -1, category 0 is the most likely
n0 = n_samples // 2
X_cont_0 = np.random.normal(-1.0, 1.0, size=n0)
X_cat_0 = np.random.choice([0, 1, 2], size=n0, p=[0.7, 0.2, 0.1])
# Class 1: continuous feature centered at 1, category 2 is the most likely
n1 = n_samples - n0
X_cont_1 = np.random.normal(1.0, 1.0, size=n1)
X_cat_1 = np.random.choice([0, 1, 2], size=n1, p=[0.1, 0.2, 0.7])
X_cont = np.concatenate([X_cont_0, X_cont_1])
X_cat = np.concatenate([X_cat_0, X_cat_1])
y = np.concatenate([np.zeros(n0), np.ones(n1)]).astype(int)
# Columns: continuous, categorical
X = np.column_stack([X_cont, X_cat])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42
)
mnb = MixedNB()
mnb.fit(X_train, y_train)
pipe_ohe = make_pipeline(
ColumnTransformer(
[("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False), [1])],
remainder="passthrough",
),
GaussianNB(),
)
pipe_ohe.fit(X_train, y_train)
pipe_kbins = make_pipeline(
ColumnTransformer(
[
(
"discretizer",
KBinsDiscretizer(n_bins=5, encode="ordinal", strategy="quantile"),
[0],
)
],
remainder="passthrough",
),
CategoricalNB(),
)
pipe_kbins.fit(X_train, y_train)
models = [mnb, pipe_ohe, pipe_kbins]
titles = [
"MixedNB",
"One-hot encoding + GaussianNB",
"Binning + CategoricalNB",
]
fig, axes = plt.subplots(1, 3, figsize=(12.5, 4.6), sharey=True)
h = 0.05
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = -0.5, 2.5 # One row per category
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, 1))
grid_X = np.c_[xx.ravel(), yy.ravel()]
for ax, model, title in zip(axes, models, titles):
Z = model.predict_proba(grid_X)[:, 1]
Z = Z.reshape(xx.shape)
acc = accuracy_score(y_test, model.predict(X_test))
ll = log_loss(y_test, model.predict_proba(X_test))
image = ax.imshow(
Z,
extent=(x_min, x_max, y_min, y_max),
origin="lower",
cmap="viridis",
vmin=0,
vmax=1,
aspect="auto",
alpha=0.8,
)
# Jitter the categorical axis so the test points do not overlap
X_plot = X_test.copy()
y_jit = X_plot[:, 1] + np.random.uniform(-0.2, 0.2, size=len(X_plot))
ax.scatter(
X_plot[y_test == 0, 0],
y_jit[y_test == 0],
c="indigo",
marker="o",
s=30,
alpha=0.9,
edgecolors="w",
linewidth=0.8,
label="Class 0",
)
ax.scatter(
X_plot[y_test == 1, 0],
y_jit[y_test == 1],
c="gold",
marker="^",
s=30,
alpha=0.9,
edgecolors="k",
linewidth=0.5,
label="Class 1",
)
ax.set_title(f"{title}\nAccuracy {acc:.3f}, log loss {ll:.3f}")
ax.set_xlabel("Continuous feature")
ax.set_yticks([0, 1, 2])
axes[0].set_ylabel("Categorical feature")
fig.colorbar(image, ax=axes, label="Probability of class 1")
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=2)
fig.suptitle("MixedNB and scikit-learn pipelines on mixed data")
plt.show()
Total running time of the script: (0 minutes 0.738 seconds)