Note
Go to the end to download the full example code.
Pipelines and model selection with scikit-learn#
The estimators of the library follow the scikit-learn interface, so they can be combined with its preprocessing, pipelines and model selection.
The data are a table with numeric and text columns and some missing values,
as it would come out of a database. Although the classifiers in scikit-bayes
handle text columns and missing values natively, a
sklearn.pipeline.Pipeline with
sklearn.compose.ColumnTransformer can still be used when explicit
imputation or encoding is preferred before fitting skbn.ALR.
A sklearn.model_selection.GridSearchCV then chooses the size of
the attribute subsets of ALR (n_join) and the granularity of its
weights (weight_level) by cross-validated log loss. The heatmap shows
the score of every combination.

Best parameters: {'model__n_join': 2, 'model__weight_level': 1}
Cross-validated log loss: 0.283
Test log loss: 0.265
# Author: The scikit-bayes Developers
# SPDX-License-Identifier: BSD-3-Clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OrdinalEncoder
from skbn import ALR
# A mixed table with missing values
rng = np.random.RandomState(42)
n_samples = 3000
temperature = rng.normal(60, 15, n_samples)
pressure = rng.normal(1.0, 0.3, n_samples)
vibration = rng.gamma(2.0, 1.0, n_samples)
mode = rng.choice(["Idle", "Normal", "Boost"], n_samples)
supplier = rng.choice(["North", "South", "East", "West"], n_samples)
# The fault depends on the temperature in a different way in each mode
limit = np.select([mode == "Idle", mode == "Normal"], [45.0, 70.0], default=85.0)
fault = (temperature > limit) | ((vibration > 4.0) & (supplier == "East"))
y = (fault ^ (rng.rand(n_samples) < 0.05)).astype(int)
# Columns: temperature, pressure, vibration, mode, supplier
X = np.empty((n_samples, 5), dtype=object)
for j, column in enumerate([temperature, pressure, vibration, mode, supplier]):
X[:, j] = column
# Missing values in a numeric and in a text column
X[rng.rand(n_samples) < 0.08, 1] = np.nan
X[rng.rand(n_samples) < 0.08, 4] = np.nan
numeric = [0, 1, 2]
categorical = [3, 4]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=42
)
# Preprocessing and ALR in one pipeline
preprocess = ColumnTransformer(
[
("num", SimpleImputer(strategy="median"), numeric),
(
"cat",
make_pipeline(SimpleImputer(strategy="most_frequent"), OrdinalEncoder()),
categorical,
),
]
)
# The transformer puts the numeric columns first, then the categorical ones
cat_idx = list(range(len(numeric), len(numeric) + len(categorical)))
pipe = Pipeline(
[
("preprocess", preprocess),
("model", ALR(categorical_features=cat_idx, l2_reg=1.0, max_iter=200)),
]
)
# Grid search over the join size and the weight level
orders = [1, 2, 3]
levels = [1, 2, 3]
search = GridSearchCV(
pipe,
{"model__n_join": orders, "model__weight_level": levels},
scoring="neg_log_loss",
cv=5,
)
search.fit(X_train, y_train)
print("Best parameters:", search.best_params_)
print(f"Cross-validated log loss: {-search.best_score_:.3f}")
print(f"Test log loss: {-search.score(X_test, y_test):.3f}")
# Mean log loss of every combination, as an (order, level) matrix
scores = np.zeros((len(orders), len(levels)))
for params, score in zip(
search.cv_results_["params"], search.cv_results_["mean_test_score"]
):
i = orders.index(params["model__n_join"])
j = levels.index(params["model__weight_level"])
scores[i, j] = -score
fig, ax = plt.subplots(figsize=(6.5, 4.6))
im = ax.imshow(scores, cmap="viridis_r")
for i in range(len(orders)):
for j in range(len(levels)):
ax.text(
j,
i,
f"{scores[i, j]:.3f}",
ha="center",
va="center",
color="white" if scores[i, j] > scores.mean() else "#1A1A1A",
)
# Frame the best combination
i, j = np.unravel_index(scores.argmin(), scores.shape)
ax.add_patch(plt.Rectangle((j - 0.5, i - 0.5), 1, 1, fill=False, color="#D55E00", lw=3))
ax.set_xticks(range(len(levels)), [str(k) for k in levels])
ax.set_yticks(range(len(orders)), [str(n) for n in orders])
ax.set_xlabel("Weight level")
ax.set_ylabel("Join size")
ax.grid(False)
ax.set_title("Cross-validated log loss of ALR")
fig.colorbar(im, ax=ax, label="Log loss")
plt.show()
Total running time of the script: (0 minutes 0.770 seconds)