.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/sampling/_plot_b03cnl.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_sampling__plot_b03cnl.py: Cross-nested logit ================== Estimation of a cross-nested logit model using sampling of alternatives. Michel Bierlaire Sat Jul 26 2025, 14:57:17 .. GENERATED FROM PYTHON SOURCE LINES 11-42 .. code-block:: Python import pandas as pd from alternatives import ( ID_COLUMN, all_alternatives, alternatives, asian_and_downtown, only_asian, only_downtown, partitions, ) from compare import compare from IPython.core.display_functions import display from specification_sampling import V, combined_variables import biogeme.biogeme_logging as blog from biogeme.biogeme import BIOGEME from biogeme.expressions import Beta from biogeme.nests import NestsForCrossNestedLogit, OneNestForCrossNestedLogit from biogeme.results_processing import ( EstimationResults, get_pandas_estimated_parameters, ) from biogeme.sampling_of_alternatives import ( ChoiceSetsGeneration, GenerateModel, SamplingContext, generate_segment_size, ) from biogeme.tools import timeit .. GENERATED FROM PYTHON SOURCE LINES 43-45 .. code-block:: Python logger = blog.get_screen_logger(level=blog.INFO) .. GENERATED FROM PYTHON SOURCE LINES 46-54 .. code-block:: Python PARTITION = 'downtown' MEV_PARTITION = 'uniform_asian_or_downtown' SAMPLE_SIZE = 10 # out of 100 alternatives SAMPLE_SIZE_MEV = 63 # out of 63 alternatives CHOICE_COLUMN = 'cnl_3' MODEL_NAME = f'cnl_{SAMPLE_SIZE}_{SAMPLE_SIZE_MEV}' FILE_NAME = f'{MODEL_NAME}.dat' .. GENERATED FROM PYTHON SOURCE LINES 55-59 .. code-block:: Python the_partition = partitions.get(PARTITION) if the_partition is None: raise ValueError(f'Unknown partition: {PARTITION}') .. GENERATED FROM PYTHON SOURCE LINES 60-64 .. code-block:: Python segment_sizes = list( generate_segment_size(SAMPLE_SIZE, the_partition.number_of_segments()) ) .. GENERATED FROM PYTHON SOURCE LINES 65-66 We use all alternatives in the nest. .. GENERATED FROM PYTHON SOURCE LINES 66-73 .. code-block:: Python mev_partition = partitions.get(MEV_PARTITION) if mev_partition is None: raise ValueError(f'Unknown partition: {MEV_PARTITION}') mev_segment_sizes = [ SAMPLE_SIZE_MEV, ] .. GENERATED FROM PYTHON SOURCE LINES 74-75 Nests .. GENERATED FROM PYTHON SOURCE LINES 77-78 Downtown .. GENERATED FROM PYTHON SOURCE LINES 78-86 .. code-block:: Python mu_downtown = Beta('mu_downtown', 1, 1, None, 0) downtown_alpha_dict = {i: 0.5 for i in asian_and_downtown} | { i: 1 for i in only_downtown } downtown_nest = OneNestForCrossNestedLogit( nest_param=mu_downtown, dict_of_alpha=downtown_alpha_dict, name='downtown' ) .. GENERATED FROM PYTHON SOURCE LINES 87-88 Asian .. GENERATED FROM PYTHON SOURCE LINES 88-99 .. code-block:: Python mu_asian = Beta('mu_asian', 1, 1, None, 0) asian_alpha_dict = {i: 0.5 for i in asian_and_downtown} | {i: 1.0 for i in only_asian} asian_nest = OneNestForCrossNestedLogit( nest_param=mu_asian, dict_of_alpha=asian_alpha_dict, name='asian' ) cnl_nests = NestsForCrossNestedLogit( choice_set=all_alternatives, tuple_of_nests=(downtown_nest, asian_nest), ) .. GENERATED FROM PYTHON SOURCE LINES 100-102 .. code-block:: Python observations = pd.read_csv('obs_choice.dat') .. GENERATED FROM PYTHON SOURCE LINES 103-118 .. code-block:: Python context = SamplingContext( the_partition=the_partition, sample_sizes=segment_sizes, individuals=observations, choice_column=CHOICE_COLUMN, alternatives=alternatives, id_column=ID_COLUMN, biogeme_file_name=FILE_NAME, utility_function=V, combined_variables=combined_variables, mev_partition=mev_partition, mev_sample_sizes=mev_segment_sizes, cnl_nests=cnl_nests, ) .. GENERATED FROM PYTHON SOURCE LINES 119-121 .. code-block:: Python logger.info(context.reporting()) .. GENERATED FROM PYTHON SOURCE LINES 122-125 .. code-block:: Python the_data_generation = ChoiceSetsGeneration(context=context) the_model_generation = GenerateModel(context=context) .. GENERATED FROM PYTHON SOURCE LINES 126-128 .. code-block:: Python biogeme_database = the_data_generation.sample_and_merge(recycle=False) .. GENERATED FROM PYTHON SOURCE LINES 129-131 .. code-block:: Python logprob = the_model_generation.get_cross_nested_logit() .. GENERATED FROM PYTHON SOURCE LINES 132-135 .. code-block:: Python the_biogeme = BIOGEME(biogeme_database, logprob) the_biogeme.model_name = MODEL_NAME .. GENERATED FROM PYTHON SOURCE LINES 136-137 Calculate the null log likelihood for reporting. .. GENERATED FROM PYTHON SOURCE LINES 137-141 .. code-block:: Python the_biogeme.calculate_null_loglikelihood( {i: 1 for i in range(context.total_sample_size)} ) .. GENERATED FROM PYTHON SOURCE LINES 142-143 Estimate the parameters. .. GENERATED FROM PYTHON SOURCE LINES 143-151 .. code-block:: Python try: results = EstimationResults.from_yaml_file( filename=f'saved_results/{the_biogeme.model_name}.yaml' ) except FileNotFoundError: with timeit(f'Estimate of model {the_biogeme.model_name}'): results = the_biogeme.estimate() .. GENERATED FROM PYTHON SOURCE LINES 152-154 .. code-block:: Python print(results.short_summary()) .. GENERATED FROM PYTHON SOURCE LINES 155-159 .. code-block:: Python parameters_tables = get_pandas_estimated_parameters(estimation_results=results) estimated_parameters = parameters_tables['Estimated parameters'] display(estimated_parameters) .. GENERATED FROM PYTHON SOURCE LINES 160-162 .. code-block:: Python df, msg = compare(estimated_parameters) .. GENERATED FROM PYTHON SOURCE LINES 163-165 .. code-block:: Python print(df) .. GENERATED FROM PYTHON SOURCE LINES 166-167 .. code-block:: Python print(msg) .. _sphx_glr_download_auto_examples_sampling__plot_b03cnl.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: _plot_b03cnl.ipynb <_plot_b03cnl.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: _plot_b03cnl.py <_plot_b03cnl.py>` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: _plot_b03cnl.zip <_plot_b03cnl.zip>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_