"""
=====================================================
Calibration of generative and weighted models
=====================================================

A classifier is calibrated when, among the instances to which it gives a
probability of 0.8, about 80% belong to the predicted class. The figure
draws the reliability diagrams of five models of the library.

The problem is binary, with a few informative attributes and many redundant
copies of them. A model that assumes independence counts the redundant
attributes several times, which pushes its probabilities towards 0 and 1.
The models are:

1.  :class:`skbn.MixedNB`, Naive Bayes, the most affected.
2.  :class:`skbn.AnDE`: conditioning on a super-parent absorbs part of the
    redundancy.
3.  :class:`skbn.WeightedAnDE` with component weights, one weight per SPODE
    and class. They decide how much each SPODE is trusted, but every SPODE
    still counts the redundant children several times.
4.  :class:`skbn.WeightedAnDE` with factor weights, one weight per factor,
    value and class inside each SPODE, which can discount each redundant
    child.
5.  :class:`skbn.ALR`, one weight per pair of attributes over the pairwise
    joins of AnJE, which also discounts redundant pairs.

A curve below the diagonal on the right and above it on the left means
overconfidence. The histograms show how often each model predicts each
probability.
"""

# Author: The scikit-bayes Developers
# SPDX-License-Identifier: BSD-3-Clause

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import NullLocator, StrMethodFormatter
from sklearn.calibration import calibration_curve
from sklearn.datasets import make_classification
from sklearn.metrics import brier_score_loss, log_loss
from sklearn.model_selection import train_test_split

from skbn import ALR, AnDE, MixedNB, WeightedAnDE

X, y = make_classification(
    n_samples=12000,
    n_features=14,
    n_informative=4,
    n_redundant=10,
    n_clusters_per_class=2,
    class_sep=0.8,
    flip_y=0.05,
    random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.5, random_state=42
)

# Name: model, colour, line style, marker
models = {
    "MixedNB": (MixedNB(), "#6E6E6E", "-", "s"),
    "AnDE": (AnDE(n_dependence=1), "#0072B2", "-", "o"),
    "WeightedAnDE, component": (WeightedAnDE(weight_level=3), "#CC79A7", "-", "^"),
    "WeightedAnDE, factor": (
        WeightedAnDE(weight_scope="factor", weight_level=3),
        "#CC79A7",
        "--",
        "v",
    ),
    "ALR": (ALR(n_join=2, weight_level=1), "#D55E00", "-", "D"),
}

probas = {}
for name, (model, *_) in models.items():
    model.fit(X_train, y_train)
    probas[name] = model.predict_proba(X_test)[:, 1]
    print(
        f"{name:24s} log loss {log_loss(y_test, probas[name]):.3f}   "
        f"Brier {brier_score_loss(y_test, probas[name]):.3f}"
    )

fig, (ax_rel, ax_hist) = plt.subplots(1, 2, figsize=(12, 5))

ax_rel.plot([0, 1], [0, 1], color="#1A1A1A", ls=":", lw=1, label="Perfect calibration")
bins = np.linspace(0, 1, 21)

for name, (_, color, style, marker) in models.items():
    frac_pos, mean_pred = calibration_curve(
        y_test, probas[name], n_bins=12, strategy="quantile"
    )
    ll = log_loss(y_test, probas[name])
    ax_rel.plot(
        mean_pred,
        frac_pos,
        color=color,
        ls=style,
        marker=marker,
        label=f"{name}, log loss {ll:.3f}",
    )
    ax_hist.hist(probas[name], bins=bins, histtype="step", color=color, ls=style)

ax_rel.set_xlabel("Predicted probability of class 1")
ax_rel.set_ylabel("Observed fraction of class 1")
ax_rel.set_xlim(0, 1)
ax_rel.set_ylim(0, 1)
ax_rel.set_box_aspect(1)
ax_rel.set_title("Reliability diagram")

ax_hist.set_xlabel("Predicted probability of class 1")
ax_hist.set_ylabel("Test instances")
ax_hist.set_xlim(0, 1)
ax_hist.set_yscale("log")
ax_hist.set_yticks([100, 200, 500, 1000])
ax_hist.set_ylim(90, 1400)
ax_hist.yaxis.set_major_formatter(StrMethodFormatter("{x:g}"))
ax_hist.yaxis.set_minor_locator(NullLocator())
ax_hist.set_title("Predicted probabilities")

fig.legend(*ax_rel.get_legend_handles_labels(), loc="outside lower center", ncol=3)
fig.suptitle("Calibration with redundant attributes")
plt.show()
