.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/anje/19_plot_anje_vs_alr.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_anje_19_plot_anje_vs_alr.py: ===================================================== AnJE or ALR: generative and discriminative n-joins ===================================================== :class:`skbn.AnJE` and :class:`skbn.ALR` use the same statistics, the joint distributions of every pair of attributes given the class (``n_join=2``). AnJE pools them with fixed weights. ALR learns one weight per pair, value and class by maximising the conditional log-likelihood, as in Zaidi et al. (2016). The data have twelve continuous attributes, four of them informative and four redundant combinations of those, and the models are trained on samples of increasing size. Three ALR settings are compared: the defaults, which follow the paper (no penalty), and penalties ``l2_reg`` of 1 and 10 towards ``w = 1``. With a few hundred samples, ALR classifies as well as AnJE but its probabilities are far more extreme, so its log loss is several times higher. Its starting point ``w = 1`` is not AnJE but the product of all the n-joins, which counts every attribute many times, and a penalty towards that point cannot correct it while the data are few. From a few thousand samples on, the weights undo the redundancy and ALR is more accurate than AnJE. Its log loss needs the penalty: with ``l2_reg=10`` it falls below that of AnJE on the largest sample. Without a penalty, L-BFGS-B reaches its limit of 10,000 iterations on that sample, which is the cost shown on the right. .. GENERATED FROM PYTHON SOURCE LINES 28-116 .. image-sg:: /auto_examples/anje/images/sphx_glr_19_plot_anje_vs_alr_001.png :alt: AnJE and ALR with two-attribute joins :srcset: /auto_examples/anje/images/sphx_glr_19_plot_anje_vs_alr_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none AnJE log loss [0.707 0.429 0.344 0.326 0.328] ALR log loss [4.742 2.716 3.035 4.657 1.112] ALR, $\lambda = 1$ log loss [4.736 2.493 1.045 0.829 0.354] ALR, $\lambda = 10$ log loss [4.739 2.536 1.044 0.536 0.293] | .. code-block:: Python # Author: The scikit-bayes Developers # SPDX-License-Identifier: BSD-3-Clause import time import warnings import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import NullLocator, StrMethodFormatter from sklearn.datasets import make_classification from sklearn.exceptions import ConvergenceWarning from sklearn.metrics import accuracy_score, log_loss from sklearn.model_selection import train_test_split from skbn import ALR, AnJE seeds = [0, 1, 2] sizes = [100, 300, 1000, 3000, 10000] # Name, factory, colour, line style; lambda is l2_reg models = [ ("AnJE", lambda: AnJE(n_join=2), "#009E73", "-"), ("ALR", lambda: ALR(n_join=2), "#D55E00", "-"), (r"ALR, $\lambda = 1$", lambda: ALR(n_join=2, l2_reg=1.0), "#D55E00", "--"), (r"ALR, $\lambda = 10$", lambda: ALR(n_join=2, l2_reg=10.0), "#D55E00", ":"), ] # The unpenalized ALR stops at max_iter on the largest sample (see above) warnings.filterwarnings("ignore", category=ConvergenceWarning) # Fit each model once so that the times below exclude the compilation of # the kernels on their first use X_small, y_small = make_classification(n_samples=200, n_features=12, random_state=0) for _, factory, _, _ in models: factory().fit(X_small, y_small) shape = (len(seeds), len(sizes), len(models)) res_ll, res_acc, res_time = np.zeros(shape), np.zeros(shape), np.zeros(shape) for i, seed in enumerate(seeds): X, y = make_classification( n_samples=15000, n_features=12, n_informative=4, n_redundant=4, n_clusters_per_class=2, random_state=seed, ) for j, n_train in enumerate(sizes): X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=n_train, test_size=5000, random_state=seed ) for k, (_, factory, _, _) in enumerate(models): start = time.perf_counter() clf = factory().fit(X_train, y_train) res_time[i, j, k] = time.perf_counter() - start proba = clf.predict_proba(X_test) res_ll[i, j, k] = log_loss(y_test, proba) res_acc[i, j, k] = accuracy_score(y_test, proba.argmax(axis=1)) mean_ll, mean_acc, mean_time = (r.mean(axis=0) for r in (res_ll, res_acc, res_time)) for k, (name, *_) in enumerate(models): print(f"{name:16s} log loss {np.round(mean_ll[:, k], 3)}") fig, axes = plt.subplots(1, 3, figsize=(13, 4.2)) panels = [ (mean_ll, "Test log loss"), (mean_acc, "Test accuracy"), (mean_time, "Training time (s)"), ] for ax, (values, ylabel) in zip(axes, panels): for k, (name, _, color, style) in enumerate(models): ax.plot(sizes, values[:, k], ls=style, marker="o", color=color, label=name) ax.set_ylabel(ylabel) ax.set_xlabel("Training set size") ax.set_xscale("log") ax.set_xticks(sizes) ax.xaxis.set_major_formatter(StrMethodFormatter("{x:g}")) ax.xaxis.set_minor_locator(NullLocator()) for ax, ticks in [(axes[0], [0.3, 0.5, 1, 2, 5]), (axes[2], [0.01, 0.1, 1, 10])]: ax.set_yscale("log") ax.set_yticks(ticks) ax.yaxis.set_major_formatter(StrMethodFormatter("{x:g}")) ax.yaxis.set_minor_locator(NullLocator()) fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=4) fig.suptitle("AnJE and ALR with two-attribute joins") plt.show() .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 34.441 seconds) .. _sphx_glr_download_auto_examples_anje_19_plot_anje_vs_alr.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: 19_plot_anje_vs_alr.ipynb <19_plot_anje_vs_alr.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: 19_plot_anje_vs_alr.py <19_plot_anje_vs_alr.py>` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: 19_plot_anje_vs_alr.zip <19_plot_anje_vs_alr.zip>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_