Note
Go to the end to download the full example code.
Context-dependent rules on mixed data#
A monitored system has a continuous measurement and a categorical operating mode with three values. An instance is an anomaly (class 1) under a rule that depends on the mode: the measurement is above 1 in mode 0, below -1 in mode 1 and between -0.5 and 0.5 in mode 2. The mode and the measurement are independent of each other, and neither says much about the class on its own.
skbn.MixedNB models the measurement with a single Gaussian per class,
so it cannot place a different boundary in each mode. skbn.AnDE with
n_dependence=1 conditions the measurement on the mode and learns one
boundary per mode. The figure shows the probability of an anomaly over the
measurement for each mode, with the training accuracy 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.metrics import accuracy_score
from skbn import AnDE, MixedNB
warnings.filterwarnings("ignore", category=UserWarning)
np.random.seed(42)
n_samples = 3000
X_cont = np.random.randn(n_samples, 1) * 1.5
X_cat = np.random.randint(0, 3, size=(n_samples, 1))
X = np.hstack([X_cont, X_cat])
# Anomaly rule per mode
y = np.zeros(n_samples, dtype=int)
mask_0 = (X_cat.flatten() == 0) & (X_cont.flatten() > 1.0)
y[mask_0] = 1
mask_1 = (X_cat.flatten() == 1) & (X_cont.flatten() < -1.0)
y[mask_1] = 1
mask_2 = (X_cat.flatten() == 2) & (np.abs(X_cont.flatten()) < 0.5)
y[mask_2] = 1
mnb = MixedNB()
mnb.fit(X, y)
ande = AnDE(n_dependence=1)
ande.fit(X, y)
models = [mnb, ande]
titles = ["MixedNB", "AnDE, $n = 1$"]
fig, axes = plt.subplots(1, 2, figsize=(11, 4.6), sharey=True)
# Cell centers are used for prediction and cell edges for pcolormesh
n_points = 200
x_centers = np.linspace(-4, 4, n_points)
step = x_centers[1] - x_centers[0]
x_edges = np.concatenate([x_centers - step / 2, [x_centers[-1] + step / 2]])
y_edges = np.array([-0.5, 0.5, 1.5, 2.5])
for ax, model, title in zip(axes, models, titles):
acc = accuracy_score(y, model.predict(X))
prob_map = np.zeros((3, n_points))
for cat_val in [0, 1, 2]:
batch_cat = np.full((n_points, 1), cat_val)
batch_X = np.hstack([x_centers.reshape(-1, 1), batch_cat])
probs = model.predict_proba(batch_X)[:, 1]
prob_map[cat_val, :] = probs
pcm = ax.pcolormesh(
x_edges,
y_edges,
prob_map,
cmap="viridis",
vmin=0,
vmax=1,
shading="flat",
alpha=0.8,
)
mask_sub = np.random.choice(n_samples, 400, replace=False)
X_sub = X[mask_sub]
y_sub = y[mask_sub]
# Jitter the categorical axis so the points do not overlap
y_jitter = X_sub[:, 1] + np.random.uniform(-0.2, 0.2, size=len(X_sub))
ax.scatter(
X_sub[y_sub == 0, 0],
y_jitter[y_sub == 0],
c="indigo",
marker="o",
s=20,
alpha=0.6,
edgecolors="w",
linewidth=0.6,
label="Class 0",
)
ax.scatter(
X_sub[y_sub == 1, 0],
y_jitter[y_sub == 1],
c="gold",
marker="^",
s=20,
alpha=0.8,
edgecolors="k",
linewidth=0.4,
label="Class 1",
)
ax.set_title(f"{title}\nTraining accuracy: {acc:.3f}")
ax.set_xlabel("Measurement")
ax.set_xlim(x_edges[0], x_edges[-1])
ax.set_yticks(
[0, 1, 2],
["Mode 0\nAbove 1", "Mode 1\nBelow $-1$", "Mode 2\nWithin $\\pm 0.5$"],
)
# Anomaly thresholds of each mode
ax.vlines(1.0, -0.5, 0.5, colors="black", linestyles="--", alpha=0.5)
ax.vlines(-1.0, 0.5, 1.5, colors="black", linestyles="--", alpha=0.5)
ax.vlines([-0.5, 0.5], 1.5, 2.5, colors="black", linestyles="--", alpha=0.5)
axes[0].set_ylabel("Operating mode")
fig.colorbar(pcm, ax=axes, label="Probability of an anomaly")
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=2)
fig.suptitle("Anomaly rule that depends on the operating mode")
plt.show()
Total running time of the script: (0 minutes 4.318 seconds)