.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "tutorials/details/bayesian_model_selection.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 or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_tutorials_details_bayesian_model_selection.py: Bayesian model selection ======================== An overview of Bayesian model selection combining Gammapy with UltraNest and ArviZ packages. .. GENERATED FROM PYTHON SOURCE LINES 12-29 Context ------- For a general overview see the arviz guides: - https://arviz-devs.github.io/EABM/Chapters/Model_comparison.html - https://arviz-devs.github.io/EABM/Chapters/Sensitivity_checks.html Most of the text is directly taken from this reference and examples have been adapted to a gamma-ray analysis with Gammapy. Here we are going to focus on the following questions: - What are the common information criterion used for model selection nowadays? - how model comparison is sensitive to the choice of prior? - how the parameter posterior is sensitive to the choice of prior? .. GENERATED FROM PYTHON SOURCE LINES 32-41 Prerequisites ------------- - This is an advanced tutorial that requires to be familiar with Gammapy modeling features and statistics. - Knowledge Bayesian analysis and nested sampling, see the :doc:`/tutorials/details/nested_sampling_Crab` tutorial. - Reading the arviz guides previously mentioned could be a useful start. .. GENERATED FROM PYTHON SOURCE LINES 44-53 Proposed approach ----------------- In this example, we will perform a Bayesian analysis with multiple 1D spectra of the Crab nebula data. Then we will discuss how to interpret the posterior distributions, the sensitivity to prior of the different information criterion used for model selection, and how to define the priors. .. GENERATED FROM PYTHON SOURCE LINES 56-61 Setup ----- As usual, we’ll start with some setup … .. GENERATED FROM PYTHON SOURCE LINES 61-87 .. code-block:: Python import arviz as az import matplotlib.pyplot as plt import numpy as np from gammapy.datasets import Datasets from gammapy.datasets import SpectrumDatasetOnOff from gammapy.modeling.models import ( SkyModel, UniformPrior, LogUniformPrior, GaussianPrior, create_crab_spectral_model, Models, ) from gammapy.modeling import Sampler from gammapy.modeling import BayesianModelSelection from gammapy.stats.utils import ts_to_sigma import warnings warnings.filterwarnings("ignore", category=RuntimeWarning) .. GENERATED FROM PYTHON SOURCE LINES 89-95 Loading the spectral datasets ----------------------------- Here we will load a few Crab 1D spectral data for which we will do the analysis. .. GENERATED FROM PYTHON SOURCE LINES 95-106 .. code-block:: Python path = "$GAMMAPY_DATA/joint-crab/spectra/hess/" datasets = Datasets() for id in ["23523", "23526", "23559", "23592"]: dataset = SpectrumDatasetOnOff.read(f"{path}pha_obs{id}.fits") datasets.append(dataset) datasets = Datasets(datasets.stack_reduce()) .. GENERATED FROM PYTHON SOURCE LINES 107-115 Model definition ---------------- The Crab spectra will be modelled here with a powerlaw or a log parabola with prior of different strength (names are indicatives). Create a set of alternative models with different spectral shapes and prior strengths .. GENERATED FROM PYTHON SOURCE LINES 115-163 .. code-block:: Python alternative_models = {} models_types = ["lp", "pl"] prior_types = ["uninformative", "strong"] for model_type in models_types: for prior_type in prior_types: model_name = f"{model_type}({prior_type})" model = SkyModel.create(spectral_model=model_type, name=f"crab-{model_name}") model.spectral_model.reference.value = 1 ref_model = create_crab_spectral_model("magic_lp") if model_type == "lp": if "uninformative" in prior_type: model.spectral_model.amplitude.prior = LogUniformPrior( min=1e-14, max=1e-8 ) model.spectral_model.alpha.prior = UniformPrior(min=0, max=10) model.spectral_model.beta.prior = UniformPrior(min=0, max=10) elif "strong" in prior_type: model.spectral_model.amplitude.prior = LogUniformPrior( min=1e-11, max=1e-10 ) model.spectral_model.alpha.prior = GaussianPrior( mu=ref_model.alpha.value, sigma=0.1 ) model.spectral_model.beta.prior = GaussianPrior( mu=ref_model.beta.value, sigma=0.1 ) elif model_type == "pl": if "uninformative" in prior_type: model.spectral_model.amplitude.prior = LogUniformPrior( min=1e-14, max=1e-8 ) model.spectral_model.index.prior = UniformPrior(min=0, max=10) elif "strong" in prior_type: model.spectral_model.amplitude.prior = LogUniformPrior( min=1e-11, max=1e-10 ) model.spectral_model.index.prior = GaussianPrior( mu=ref_model.alpha.value, sigma=0.1 ) alternative_models[model_name] = Models(model) print(alternative_models) .. rst-class:: sphx-glr-script-out .. code-block:: none {'lp(uninformative)': , 'lp(strong)': , 'pl(uninformative)': , 'pl(strong)': } .. GENERATED FROM PYTHON SOURCE LINES 164-167 Defining the sampler and options -------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 167-179 .. code-block:: Python options = { "min_num_live_points": 300, "frac_remain": 0.2, "log_dir": None, "viz_callback": False, "show_status": False, } sampler = Sampler(backend="ultranest", options=options) .. GENERATED FROM PYTHON SOURCE LINES 180-186 Defining the model selection manager ------------------------------------ We define a `~gammapy.modeling.BayesianModelSelection` that will run the inference: .. GENERATED FROM PYTHON SOURCE LINES 186-192 .. code-block:: Python bms = BayesianModelSelection( sampler, posterior_downsample_factor=4, n_prior_samples=1000 ) .. GENERATED FROM PYTHON SOURCE LINES 193-197 Next we can run `~gammapy.modeling.BayesianModelSelection` that will run a sampler on the datasets for each of the alternative_models. No other option is accepted in the run method. .. GENERATED FROM PYTHON SOURCE LINES 197-201 .. code-block:: Python bms_results = bms.run(datasets, alternative_models) .. rst-class:: sphx-glr-script-out .. code-block:: none logZ = -29.016 +- 0.290 single instance: logZ = -29.016 +- 0.190 bootstrapped : logZ = -29.025 +- 0.226 tail : logZ = +- 0.182 insert order U test : converged: True correlation: inf iterations amplitude : 0.0000000000322│ ▁ ▁▁▁▁▁▁▂▂▃▄▅▆▇▇▇▇▇▆▅▅▄▃▂▂▁▁▁▁▁▁ ▁ │0.0000000000581 0.0000000000447 +- 0.0000000000029 alpha : 1.65 │ ▁▁▁▁▁▁▁▁▁▁▁▂▂▂▃▃▄▅▆▅▇▇▆▆▆▆▆▅▄▃▂▁▁▁▁▁▁ │2.90 2.37 +- 0.18 beta : 0.000 │▂▂▃▃▄▆▆▆▇▇▇▇▅▆▅▅▄▃▄▃▃▂▂▁▂▁▁▁▁▁▁▁▁▁▁ ▁▁ │0.611 0.183 +- 0.095 logZ = -20.736 +- 0.227 single instance: logZ = -20.736 +- 0.102 bootstrapped : logZ = -20.740 +- 0.136 tail : logZ = +- 0.182 insert order U test : converged: True correlation: inf iterations amplitude : 0.0000000000363│ ▁▁▁▁▁▁▁▂▂▄▃▅▅▇▇▇▇▅▆▃▅▃▃▂▂▂▁▁▁▁▁▁▁ ▁ │0.0000000000568 0.0000000000451 +- 0.0000000000026 alpha : 2.213 │ ▁▁▁ ▁▁▂▂▄▃▅▅▆▆▇▇▆▆▇▆▄▄▅▃▃▂▂▁▁▁▁▁▁▁▁ ▁ │2.775 2.462 +- 0.078 beta : -0.055│ ▁▁▁ ▁▁▁▁▁▂▃▃▅▅▅▆▆▆▆▇▆▅▄▄▄▂▂▁▁▁▁▁▁▁ ▁ │0.329 0.132 +- 0.048 logZ = -26.998 +- 0.368 single instance: logZ = -26.998 +- 0.161 bootstrapped : logZ = -27.033 +- 0.320 tail : logZ = +- 0.182 insert order U test : converged: True correlation: inf iterations index : 2.449 │ ▁▁▁▁▁▁▂▁▂▃▃▅▆▆▇▆▇▇▆▇▅▅▃▃▃▂▁▁▁▁▁▁▁ ▁▁▁ │3.011 2.704 +- 0.073 amplitude : 0.0000000000362│ ▁ ▁▁▁▁▁▂▂▂▃▅▄▅▇▇▇▆▇▆▅▄▆▃▄▂▂▁▁▁▁▁▁▁▁ ▁ │0.0000000000567 0.0000000000457 +- 0.0000000000027 logZ = -23.396 +- 0.240 single instance: logZ = -23.396 +- 0.111 bootstrapped : logZ = -23.374 +- 0.156 tail : logZ = +- 0.182 insert order U test : converged: True correlation: inf iterations index : 2.408 │ ▁ ▁▁▁▁▁▁▂▂▄▄▄▅▅▆▇▇▇▇▇▆▅▄▃▃▂▂▂▁▂▁▁▁▁ │2.803 2.623 +- 0.056 amplitude : 0.0000000000339│ ▁ ▁▁▁▁▁▁▁▂▃▄▄▅▆▅▆▇▇▇▇▆▅▄▃▃▃▂▂▁▁▁▁▁▁▁▁ │0.0000000000541 0.0000000000440 +- 0.0000000000026 .. GENERATED FROM PYTHON SOURCE LINES 202-208 Exploring the results --------------------- The sampler has finished to evaluating all the models. Let’s start by looking at the results for one. .. GENERATED FROM PYTHON SOURCE LINES 208-212 .. code-block:: Python inference_result = bms_results["lp(uninformative)"] .. GENERATED FROM PYTHON SOURCE LINES 213-223 Parameters values ~~~~~~~~~~~~~~~~~ The output of the Bayesian analysis is the posterior distribution and there is no “best-fit” output. One has to define, based on the posteriors, what we want to consider as “best-fit” and several options are possible: "mean", "median", "mode" or "maximum likelihood value". Note that Gammapy assigns the mean as the model parameter values but the other options would also be relevant choices. .. GENERATED FROM PYTHON SOURCE LINES 223-227 .. code-block:: Python inference_result.parameters_table() .. raw:: html
Table length=3
parametermeanmedianmodevalue at max ln(L)
str9float64float64float64float64
amplitude4.4738002043077384e-114.460046480706527e-114.358540477841562e-114.498001372226806e-11
alpha2.37074172026819642.38022829585506072.3788506957802662.4206844192807075
beta0.18207310483477250.172887214685379430.165886865764209860.15335036021226958


.. GENERATED FROM PYTHON SOURCE LINES 228-230 We can visualize the distributions with `~arziv.plot_dist` function of ArviZ: .. GENERATED FROM PYTHON SOURCE LINES 230-237 .. code-block:: Python az.plot_dist( inference_result.inference_data, ) plt.show() .. image-sg:: /tutorials/details/images/sphx_glr_bayesian_model_selection_001.png :alt: amplitude, alpha, beta :srcset: /tutorials/details/images/sphx_glr_bayesian_model_selection_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 238-240 Or make a corner plot .. GENERATED FROM PYTHON SOURCE LINES 240-263 .. code-block:: Python with az.rc_context( rc={ "stats.point_estimate": "median", "stats.ci_kind": "hdi", # Highest Density Interval (HDI) "stats.ci_prob": 0.89, # Optional: sets HDI probability mass (default is 0.89) } ): az.plot_pair( inference_result.inference_data, marginal=True, visuals={ "scatter": False, "contourf": True, "divergence": True, "point_estimate": True, "credible_interval": True, }, ) plt.show() .. image-sg:: /tutorials/details/images/sphx_glr_bayesian_model_selection_002.png :alt: bayesian model selection :srcset: /tutorials/details/images/sphx_glr_bayesian_model_selection_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 264-283 **Note: Why does ArviZ default to an 89% Credible Interval?** Unlike frequentist tools that default to 95%, ArviZ sets its default credible interval probability (`stats.ci_prob`) to 0.89 (89%) for two main reasons: - **Avoiding “Significance” Misinterpretation:** Popularized by Richard McElreath (*Statistical Rethinking*), 89% breaks the automatic habit of treating intervals like frequentist 95% confidence intervals (tied to :math:`p < 0.05` binary significance testing). It serves as a reminder that any interval width is an arbitrary summary of the posterior distribution. - **Computational Stability:** Estimating the boundaries of a 95% or 99% Highest Density Interval (HDI) relies on very few posterior draws in the extreme tails, making the endpoints noisy. An 89% interval leaves more samples in the tails (11%), producing more numerically stable boundary estimates for standard sample sizes. .. GENERATED FROM PYTHON SOURCE LINES 286-339 Information criteria ---------------------- Bayes Factor ~~~~~~~~~~~~ The **Bayes factor** (:math:`BF_{10}`) between two competing models :math:`M_1` and :math:`M_0` (given a dataset :math:`D`) is the ratio of their marginal likelihoods: .. math:: BF_{10} = \frac{P(D \mid M_1)}{P(D \mid M_0)} = \frac{Z_1}{Z_0} - :math:`P(D \mid M_1)`: the probability of the data given model :math:`M_1` (marginal likelihood or *evidence*). - :math:`P(D \mid M_0)`: the probability of the data given model :math:`M_0`. If :math:`BF_{10} > 1`, the data favors model :math:`M_1`. If :math:`BF_{10} < 1`, the data favors model :math:`M_0`. A standard scale (proposed by Harold Jeffreys) is used to classify the t of the evidence: +--------------------------------+-------------------------------------+ | Bayes Factor (:math:`BF_{10}`) | Interpretation | +================================+=====================================+ | **1 to 3** | Anecdotal or weak evidence for | | | :math:`M_1` | +--------------------------------+-------------------------------------+ | **3 to 10** | Substantial / moderate evidence | +--------------------------------+-------------------------------------+ | **10 to 30** | Strong evidence | +--------------------------------+-------------------------------------+ | **30 to 100** | Very strong evidence | +--------------------------------+-------------------------------------+ | **> 100** | Decisive evidence | +--------------------------------+-------------------------------------+ The Savage–Dickey density ratio provides a simple shortcut to compute the Bayes factor when comparing a nested null hypothesis. In that case instead of computing difficult marginal likelihoods for both models separately, it is only computed for the broader model (\(M_{1}\)) and compare its prior and posterior densities evaluated at the null point \(\theta _{0}\): .. math:: BF_{10} = \frac{P(\theta=\theta_0 \mid D, M_1)}{P(\theta=\theta_0 \mid M_1)} The `plot_bf` function of arviz we can be used to compute this quantity and visualise how much we gained between the prior and the posterior. Here we show this for the ``alpha`` parameter. According to Jeffreys’ scale, a :math:`BF_{01} = \frac{1}{BF_{10}} = 20` indicates **strong evidence** that the true value is equal to the reference value (grey line). .. GENERATED FROM PYTHON SOURCE LINES 339-349 .. code-block:: Python az.plot_bf( inference_result.inference_data, var_names="alpha", ref_val=inference_result.models.parameters["alpha"].value, # grey line ) plt.show() .. image-sg:: /tutorials/details/images/sphx_glr_bayesian_model_selection_003.png :alt: alpha :srcset: /tutorials/details/images/sphx_glr_bayesian_model_selection_003.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 350-357 Bayes factors evaluate the entire model, including its specific prior assumptions, to determine which explains the data better overall. Because of this prior sensitivity, other methods which judge models strictly on predictive accuracy are preferred when priors are only used for regularization. This includes notably the ELDP discussed in the following. .. GENERATED FROM PYTHON SOURCE LINES 359-473 AIC: Akaike Information Criterion ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The **AIC** is a classical (frequentist) metric used to compare statistical models by balancing **goodness of fit** against **model complexity**: .. math:: \text{AIC} = 2k - 2\ln(\hat{L}) - **Goodness of Fit** (:math:`-2\ln(\hat{L})`): measures how well the model fits the observed data using the maximum likelihood estimate (:math:`\hat{L}`). A better model yields a lower deviance. - **Complexity Penalty** (:math:`2k`): penalizes the model based on its exact number of free parameters (:math:`k`) to prevent overfitting. - **Goal:** when comparing competing models on the same dataset, the model with the **lowest AIC** is preferred. - **Limitation in Bayesian Inference:** AIC relies on a single point estimate (the Maximum Likelihood Estimate) and assumes flat priors, ignoring the uncertainty captured across a full posterior distribution. When comparing candidate models, :math:`\Delta\text{AIC}_i = \text{AIC}_i - \text{AIC}_{\min}` measures the information loss experienced if model :math:`i` is used instead of the best model (:math:`\text{AIC}_{\min}`). A stadard scale was proposed by Burnham & Anderson (2002): +----------------------------+-----------------------+-----------------------+ | :math:`\Delta\text{AIC}_i` | Level of empirical | Interpretation | | | support for model | for model :math:`i` | | | :math:`i` | | +============================+=======================+=======================+ | **0 - 2** | **Substantial** | The model is nearly | | | | indistinguishable | | | | from the best model | | | | and should be | | | | strongly considered. | +----------------------------+-----------------------+-----------------------+ | **4 - 7** | **Considerably less** | The model has | | | | noticeably weaker | | | | support compared to | | | | the best model. | +----------------------------+-----------------------+-----------------------+ | **> 10** | **Essentially none** | The model is very | | | | unlikely to be the | | | | best explanation for | | | | the data and can | | | | usually be discarded. | +----------------------------+-----------------------+-----------------------+ (Note: values falling in the gaps — such as 2 to 4 or 7 to 10 — represent smooth transitions between these categories rather than hard cutoffs). ELPD: Expected Log-Predictive Density ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The **ELPD** can be seen as a bayesian version of the AIC. It measures a model’s out-of-sample predictive accuracy by evaluating how well the entire posterior distribution predicts unseen data points :math:`\tilde{y}_i`: .. math:: \text{ELPD} = \sum_{i=1}^{n} \int p_t(\tilde{y}_i) \log p(\tilde{y}_i \mid y) \, d\tilde{y}_i - **Why it is more Bayesian than AIC:** standard **AIC** relies on a single point estimate (the Maximum Likelihood Estimate, :math:`\hat{\theta}_{\text{MLE}}`) to compute goodness of fit. In contrast, ELPD integrates over the **full posterior distribution** :math:`p(\theta \mid y)`, naturally accounting for parameter uncertainty. - **The Missing Penalization Term:** because the true data-generating distribution :math:`p_t(\tilde{y}_i)` is unknown, we must approximate ELPD using our observed sample :math:`y` (computing the *log pointwise predictive density*, or **lppd**). Evaluating the model on the same data used to analyse it introduces **optimistic overfitting bias**. - **How Penalization is Added:** to correct for overfitting, an **effective number of parameters** (:math:`p_{\text{LOO}}`) is estimated from the in-sample analysis: .. math:: \widehat{\text{ELPD}} = \text{lppd} - p_{\text{LOO}} *(Note: can be multiplied by -2 to place it on the deviance scale).* - **Asymptotic Equivalence to AIC:** as the sample size grows large (:math:`n \to \infty`) and the influence of the prior vanishes, the posterior distribution converges to a normal distribution centered at the MLE. Under these conditions, the effective number of parameters :math:`p_{\text{eff}}` equals the actual parameter count :math:`k`, and :math:`-2 \times \widehat{\text{ELPD}}` **asymptotically converges to AIC**. **PSIS-LOO-CV: Pareto-smoothed importance sampling leave-one-out cross-validation** The penalization term :math:`p_{\text{LOO}}` is computed using cross-validation. One round of cross-validation involves partitioning a sample of data into complementary subsets, performing the analysis on one subset (called the training set), and validating the analysis on the other subset (called the validation set or testing set). Leave-p-out cross-validation involves using p observations as the validation set and the remaining observations as the training set. Leave-one-out cross-validation (LOO-CV) is a particular case of leave-k-out cross-validation with k = 1. One downside of cross-validation is that it is computationally expensive. We need to evaluate the model times, and if we have a large dataset, this can be very expensive. But lucky us, by being Bayesian we can approximately compute LOO-CV in a very fast way using importance sampling. The method used here is the Pareto-Smooth Importance Sampling Leave-One-Out Cross Validation `(Vehtari, Gelman, and Gabry 2017; Yao et al. 2018) `__, which is abbreviated as PSIS-LOO-CV .. GENERATED FROM PYTHON SOURCE LINES 473-478 .. code-block:: Python elpd = inference_result.elpd print(elpd) .. rst-class:: sphx-glr-script-out .. code-block:: none Computed from 1079 posterior samples and 43 observations log-likelihood matrix. Estimate SE elpd_loo -19.61 3.39 p_loo 2.75 - ------ Pareto k diagnostic values: Count Pct. (-Inf, 0.67] (good) 43 100.0% (0.67, 1] (bad) 0 0.0% (1, Inf) (very bad) 0 0.0% .. GENERATED FROM PYTHON SOURCE LINES 479-485 The Pareto k diagnostic tell us if the approximation used to compute LOO is valid. In general ideally it should be lower than 0.7 in every pixel. The :math:`p_{\text{LOO}}` give us an estimate of the effective number of parameters. .. GENERATED FROM PYTHON SOURCE LINES 485-490 .. code-block:: Python az.plot_khat(elpd) plt.show() .. image-sg:: /tutorials/details/images/sphx_glr_bayesian_model_selection_004.png :alt: bayesian model selection :srcset: /tutorials/details/images/sphx_glr_bayesian_model_selection_004.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 491-496 Model comparison ---------------- We can have a look at the statistics summary table for all models .. GENERATED FROM PYTHON SOURCE LINES 496-501 .. code-block:: Python # lower is better bms_results.stats_table().pprint(max_width=-1) .. rst-class:: sphx-glr-script-out .. code-block:: none Model (prior) -2logz -2logl AIC elpd dof eff. dof logz error elpd error good Pareto k fraction ----------------- ------ ------ ------ ------ ----- -------- ---------- ---------- ---------------------- lp(uninformative) 58.031 33.349 39.349 39.223 3.000 2.749 0.580 6.786 1.000 lp(strong) 41.473 33.342 39.342 37.033 3.000 1.655 0.454 6.298 1.000 pl(uninformative) 53.996 36.405 40.405 40.135 2.000 1.552 0.737 5.826 1.000 pl(strong) 46.792 36.412 40.412 40.636 2.000 1.274 0.481 5.722 1.000 .. GENERATED FROM PYTHON SOURCE LINES 502-505 For the same model type we can see that the effective degree of freedom decreases as the prior strength increases. .. GENERATED FROM PYTHON SOURCE LINES 508-513 | Now let’s compare the different models to a reference model. | So H0 will be the reference model taken as the powerl-law with uninformative prior `pl(uninformative)` and H1 each of the other models. .. GENERATED FROM PYTHON SOURCE LINES 513-521 .. code-block:: Python # lower => H0 is better stats_difference_table = bms_results.stats_difference_table( reference_models_name="pl(uninformative)" ) stats_difference_table.pprint(max_width=-1) .. rst-class:: sphx-glr-script-out .. code-block:: none Model (prior) -2logz -2logl AIC elpd dof eff. dof --------------------------------------------- ------ ------ ------ ------ ------ -------- H0: pl(uninformative) - H1: lp(uninformative) -4.035 3.056 1.056 0.912 -1.000 -1.197 H0: pl(uninformative) - H1: lp(strong) 12.523 3.064 1.064 3.101 -1.000 -0.103 H0: pl(uninformative) - H1: pl(strong) 7.204 -0.007 -0.007 -0.501 0.000 0.278 .. GENERATED FROM PYTHON SOURCE LINES 522-525 As our simple test models are nested we can use Wilks theorem to scale ts=-2logl into significance in sigma .. GENERATED FROM PYTHON SOURCE LINES 525-532 .. code-block:: Python ts = stats_difference_table["-2logl"][0] dof = stats_difference_table["dof"][0] sigma = ts_to_sigma(ts, np.abs(dof)) print("LP is favored at", sigma, "sigma") .. rst-class:: sphx-glr-script-out .. code-block:: none LP is favored at 1.7482579361864439 sigma .. GENERATED FROM PYTHON SOURCE LINES 533-550 | This tell us that the log-parabola is preferred over a power-law but not very significantly. | Similarly AIC difference of 1 tell us than the models are almost equivalent to describe this dataset. | We have the same conclusion from the difference in elpd which is small. In the next table we can see it’s also small compared to the standard error on the elpd difference, which is plotted in the comparison plot below. The logz is more affected by the choice of priors. It penalizes much more the models with more effective degrees of freedom, this effect is amplified the weaker the prior is (because in that case the logz integrate over a larger “irrelevant” parameter space). We see also that using logz to compare models with different prior strength might reflect more the prior relative strength than actual differences between the models. .. GENERATED FROM PYTHON SOURCE LINES 552-556 As our statistics come with errors, more robust comparisons can be done with the methods implemented in `~arziv.compare` that we can call from our results object: .. GENERATED FROM PYTHON SOURCE LINES 556-561 .. code-block:: Python az_comparison = bms_results.compare(method="BB-pseudo-BMA") print(az_comparison.to_string()) .. rst-class:: sphx-glr-script-out .. code-block:: none rank elpd_diff dse p_worse diag_diff diag_elpd p elpd se weight lp(strong) 0 0.0 0.00 NaN 1.7 -19.0 3.0 0.48 lp(uninformative) 1 -1.0 0.77 0.92 N < 100 2.7 -20.0 3.3 0.22 pl(uninformative) 2 -2.0 1.70 0.82 N < 100 1.6 -20.0 2.8 0.15 pl(strong) 3 -2.0 2.10 0.80 N < 100 1.3 -20.0 2.8 0.15 .. GENERATED FROM PYTHON SOURCE LINES 562-568 The weight can be loosely interpreted as the probability of each model (among the compared model) given the data. The dSE is the standard error of the difference in ELPD between each model and the top-ranked model (plotted in cyan below). By default the uncertainty and the weights are computed using Bayesian bootstrap. .. GENERATED FROM PYTHON SOURCE LINES 568-581 .. code-block:: Python pc = az.plot_compare( az_comparison, relative_scale=True, rotated=True, ) fig = pc.viz["figure"].item() fig.set_size_inches(7, 4) plt.show() .. image-sg:: /tutorials/details/images/sphx_glr_bayesian_model_selection_005.png :alt: Model comparison higher is better :srcset: /tutorials/details/images/sphx_glr_bayesian_model_selection_005.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 582-597 Prior and likelihood sensitivity diagnostics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``psens`` function compute power-scaling sensitivity diagnostic. If power-scales the prior or likelihood and calculates how much the posterior is affected. Higher values returned indicate greater sensitivity. Prior sensitivity above 0.05 indicates informative prior. Likelihood sensitivity below 0.05 indicates weak or noninformative likelihood. The result can also be visualized with ``psense_summary`` function from ``arviz_stats`` that is attached to our result object as ``prior_sensitivity_table`` .. GENERATED FROM PYTHON SOURCE LINES 597-607 .. code-block:: Python bms_results["lp(uninformative)"].prior_sensitivity_table() bms_results["lp(strong)"].prior_sensitivity_table() print( bms_results.prior_sensitivity_table() ) # this will display all the models names and the prior_sensitivity_table .. rst-class:: sphx-glr-script-out .. code-block:: none Prior sensitivity for model: lp(uninformative) prior likelihood diagnosis amplitude 0.010 0.077 ✓ alpha 0.005 0.119 ✓ beta 0.002 0.161 ✓ Prior sensitivity for model: lp(strong) prior likelihood diagnosis amplitude 0.016 0.075 ✓ alpha 0.061 0.024 potential strong prior / weak likelihood beta 0.053 0.050 potential strong prior / weak likelihood Prior sensitivity for model: pl(uninformative) prior likelihood diagnosis index 0.006 0.102 ✓ amplitude 0.010 0.095 ✓ Prior sensitivity for model: pl(strong) prior likelihood diagnosis index 0.193 0.166 potential prior-data conflict amplitude 0.101 0.119 potential prior-data conflict .. GENERATED FROM PYTHON SOURCE LINES 608-639 How to measure the strength of a prior? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The entropy is a property of probability distributions the same way the mean or variance are, actually it’s the expected value of the negative log probability of the distribution. We can think of entropy as a measure of the information or uncertainty of a distribution has. Loosely speaking the entropy of a distribution is high when the distribution is spread out and low when the distribution is concentrated. In the context of prior elicitation, maximum entropy can be a guiding principle to pick priors. According to this principle we should choose the prior that maximizes the entropy, subject to known constraints of the prior (`Jaynes 2003 `__). This is a way to choose a prior that is as vague as possible, given the information we have. Further information on this is found in the arziv documentation `here `__ Take away message ~~~~~~~~~~~~~~~~~ **Because of its prior sensitivity, log Z (and Bayes factors) should generally be avoided for model comparison, and ELPD should be preferred.** Compared to AIC, ELPD has the advantage of providing uncertainty estimates (standard errors), which allow you to better assess how distinguishable the models are. However, the computational cost of estimating ELPD is considerably higher than AIC. Prior sensitivity diagnostics are just as important as information criteria for assessing the compatibility of the models with the data and whether conclusions are robust. .. rst-class:: sphx-glr-timing **Total running time of the script:** (1 minutes 23.593 seconds) .. _sphx_glr_download_tutorials_details_bayesian_model_selection.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/gammapy/gammapy-webpage/v2.2?urlpath=lab/tree/notebooks/2.2/tutorials/details/bayesian_model_selection.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: bayesian_model_selection.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: bayesian_model_selection.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: bayesian_model_selection.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_