.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/bayesian_swissmetro/plot_b01b_logit.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_bayesian_swissmetro_plot_b01b_logit.py: 1b. Estimation of a logit model with custom priors (Bayesian) ============================================================= This example estimates the same Bayesian logit model as in Example 1a, but illustrates how to specify custom prior distributions for the model parameters. The example demonstrates: - the use of non-default prior distributions, - the specification of custom PyMC prior functions, - the use of truncated prior distributions to enforce sign constraints, - the estimation of a Bayesian logit model, - the extraction and display of the estimation results. The `# %%` markers are used to separate the script into notebook cells when the example gallery is converted into Jupyter notebooks. Tested with Biogeme 3.3.3. Michel Bierlaire, EPFL Tue Jun 09 2026, 15:10:00 .. GENERATED FROM PYTHON SOURCE LINES 26-31 .. code-block:: Python import pymc as pm from IPython.core.display_functions import display from pytensor.tensor.variable import TensorVariable .. GENERATED FROM PYTHON SOURCE LINES 32-33 Import the variables and the database prepared in the Swissmetro data-processing example. .. GENERATED FROM PYTHON SOURCE LINES 33-56 .. code-block:: Python from swissmetro_data import ( CAR_AV_SP, CAR_CO_SCALED, CAR_TT_SCALED, CHOICE, SM_AV, SM_COST_SCALED, SM_TT_SCALED, TRAIN_AV_SP, TRAIN_COST_SCALED, TRAIN_TT_SCALED, database, ) import biogeme.biogeme_logging as blog from biogeme.bayesian_estimation import ( BayesianResultsSummary, get_pandas_estimated_parameters, ) from biogeme.biogeme import BIOGEME from biogeme.expressions import Beta from biogeme.models import loglogit .. GENERATED FROM PYTHON SOURCE LINES 57-59 Configure the Biogeme logger. Increasing the verbosity level provides additional information about the estimation process. .. GENERATED FROM PYTHON SOURCE LINES 59-63 .. code-block:: Python logger = blog.get_screen_logger(level=blog.DEBUG) logger.info('Example b01b_logit.py') .. rst-class:: sphx-glr-script-out .. code-block:: none [INFO] 2026-08-28 11:57:02,158 Example b01b_logit.py .. GENERATED FROM PYTHON SOURCE LINES 64-68 Define the alternative-specific constants. By default, Biogeme uses a normal prior distribution, possibly truncated if bounds are specified. Here, we increase the prior standard deviation by setting `sigma_prior=30`. .. GENERATED FROM PYTHON SOURCE LINES 68-93 .. code-block:: Python asc_car = Beta('asc_car', 0, None, None, 0, sigma_prior=30) asc_train = Beta('asc_train', 0, None, None, 0, sigma_prior=30) # For the remaining parameters, we define a custom Student-t prior. # When bounds are specified, the prior is truncated accordingly. # Consult the PyMC documentation for the available probability # distributions. def negative_student_prior( name: str, initial_value: float, lower_bound: float | None, upper_bound: float | None, ) -> TensorVariable: """Generate a Student-t prior distribution.""" if lower_bound is None and upper_bound is None: return pm.StudentT(name=name, mu=initial_value, sigma=10.0, nu=5.0) rv = pm.StudentT.dist(mu=initial_value, sigma=10.0, nu=5.0) return pm.Truncated( name, rv, lower=lower_bound, upper=upper_bound, initval=initial_value ) .. GENERATED FROM PYTHON SOURCE LINES 94-97 Define the coefficients associated with travel time and travel cost. The upper bound is fixed to zero in order to reflect the prior assumption that increases in time and cost reduce utility. .. GENERATED FROM PYTHON SOURCE LINES 97-101 .. code-block:: Python b_time = Beta('b_time', -1, None, 0, 0, prior=negative_student_prior) b_cost = Beta('b_cost', -1, None, 0, 0, prior=negative_student_prior) .. GENERATED FROM PYTHON SOURCE LINES 102-103 Define the utility functions. .. GENERATED FROM PYTHON SOURCE LINES 103-107 .. code-block:: Python v_train = asc_train + b_time * TRAIN_TT_SCALED + b_cost * TRAIN_COST_SCALED v_sm = b_time * SM_TT_SCALED + b_cost * SM_COST_SCALED v_car = asc_car + b_time * CAR_TT_SCALED + b_cost * CAR_CO_SCALED .. GENERATED FROM PYTHON SOURCE LINES 108-109 Associate each utility function with the corresponding alternative identifier. .. GENERATED FROM PYTHON SOURCE LINES 109-111 .. code-block:: Python v = {1: v_train, 2: v_sm, 3: v_car} .. GENERATED FROM PYTHON SOURCE LINES 112-113 Associate the availability conditions with each alternative. .. GENERATED FROM PYTHON SOURCE LINES 113-115 .. code-block:: Python av = {1: TRAIN_AV_SP, 2: SM_AV, 3: CAR_AV_SP} .. GENERATED FROM PYTHON SOURCE LINES 116-117 Define the log-likelihood contribution of each observation. .. GENERATED FROM PYTHON SOURCE LINES 117-119 .. code-block:: Python log_probability = loglogit(v, av, CHOICE) .. GENERATED FROM PYTHON SOURCE LINES 120-123 Create the Biogeme object. We explicitly request the standard PyMC sampler. See the PyMC documentation for details about the available sampling algorithms. .. GENERATED FROM PYTHON SOURCE LINES 123-126 .. code-block:: Python the_biogeme = BIOGEME(database, log_probability, mcmc_sampling_strategy='pymc') the_biogeme.model_name = 'b01b_logit' .. rst-class:: sphx-glr-script-out .. code-block:: none [DEBUG] 2026-08-28 11:57:02,159 READ FILE biogeme.toml : automatic [DEBUG] 2026-08-28 11:57:02,160 Parameter file: /Users/bierlair/MyFiles/github/biogeme/docs/source/examples/bayesian_swissmetro/biogeme.toml [INFO] 2026-08-28 11:57:02,170 Biogeme parameters read from biogeme.toml. .. GENERATED FROM PYTHON SOURCE LINES 127-131 Estimate the parameters. The estimation code is placed inside a function protected by the standard Python main guard. This is required because PyMC may use multiprocessing, and worker processes re-import the script. .. GENERATED FROM PYTHON SOURCE LINES 131-157 .. code-block:: Python def main() -> None: """Estimate the Bayesian logit model and display the results.""" try: results = BayesianResultsSummary.from_yaml_file( filename=f'saved_results/{the_biogeme.model_name}.yaml' ) except FileNotFoundError: results = the_biogeme.bayesian_estimation().to_summary() # %% # Display a short summary of the estimation results. print(results.short_summary()) # %% # Convert the estimated parameters into a pandas DataFrame. pandas_results = get_pandas_estimated_parameters( estimation_results=results, ) display(pandas_results) if __name__ == '__main__': main() .. rst-class:: sphx-glr-script-out .. code-block:: none Sample size 6768 Sampler NUTS Number of chains 4 Number of draws per chain 2000 Total number of draws 8000 Acceptance rate target 0.9 Run time 0:01:41.915272 Posterior predictive log-likelihood (sum of log mean p) -5329.78 Expected log-likelihood E[log L(Y|θ)] -5333.25 Best-draw log-likelihood (posterior upper bound) -5331.26 LOO (Leave-One-Out Cross-Validation) -5336.75 LOO Standard Error 59.65 Effective number of parameters (p_LOO) 6.97 Name Value (mean) Value (median) ... R hat ESS (bulk) ESS (tail) 0 asc_train -0.701234 -0.701008 ... 1.001489 4046.690153 4523.293643 1 asc_car -0.154589 -0.154037 ... 1.000632 4425.236634 5063.536359 2 b_time -1.279362 -1.279136 ... 1.001875 3853.384854 4470.989316 3 b_cost -1.084899 -1.083987 ... 1.000197 6014.871012 5579.737697 [4 rows x 12 columns] .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.026 seconds) .. _sphx_glr_download_auto_examples_bayesian_swissmetro_plot_b01b_logit.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_b01b_logit.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_b01b_logit.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_b01b_logit.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_