301: Itinerary Choice using MNL

301: Itinerary Choice using MNL

import larch
larch.__version__
'5.6.1'

This example is an itinerary choice model built using the example itinerary choice dataset included with Larch. We’ll begin by loading that example data.

from larch.data_warehouse import example_file
itin = pd.read_csv(example_file("arc"), index_col=['id_case','id_alt'])
d = larch.DataFrames(itin, ch='choice', crack=True, autoscale_weights=True)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [2], in <module>
      1 from larch.data_warehouse import example_file
----> 2 itin = pd.read_csv(example_file("arc"), index_col=['id_case','id_alt'])
      3 d = larch.DataFrames(itin, ch='choice', crack=True, autoscale_weights=True)

NameError: name 'pd' is not defined

Now let’s make our model. We’ll use a few variables to define our linear-in-parameters utility function.

m = larch.Model(dataservice=d)

v = [
    "timeperiod==2",
    "timeperiod==3",
    "timeperiod==4",
    "timeperiod==5",
    "timeperiod==6",
    "timeperiod==7",
    "timeperiod==8",
    "timeperiod==9",
    "carrier==2",
    "carrier==3",
    "carrier==4",
    "carrier==5",
    "equipment==2",
    "fare_hy",    
    "fare_ly",    
    "elapsed_time",  
    "nb_cnxs",       
]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [3], in <module>
----> 1 m = larch.Model(dataservice=d)
      3 v = [
      4     "timeperiod==2",
      5     "timeperiod==3",
   (...)
     20     "nb_cnxs",       
     21 ]

NameError: name 'd' is not defined

The larch.roles module defines a few convenient classes for declaring data and parameter. One we will use here is PX which creates a linear-in-parameter term that represents one data element (a column from our data, or an expression that can be evaluated on the data alone) multiplied by a parameter with the same name.

from larch.roles import PX
m.utility_ca = sum(PX(i) for i in v)
m.choice_ca_var = 'choice'
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [4], in <module>
      1 from larch.roles import PX
----> 2 m.utility_ca = sum(PX(i) for i in v)
      3 m.choice_ca_var = 'choice'

NameError: name 'v' is not defined

Since we are estimating just an MNL model in this example, this is all we need to do to build our model, and we’re ready to go. To estimate the likelihood maximizing parameters, we give:

m.load_data()
m.maximize_loglike()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [5], in <module>
----> 1 m.load_data()
      2 m.maximize_loglike()

NameError: name 'm' is not defined