In [1]:
import larch
This example is an itinerary choice model built using the example itinerary choice dataset included with Larch. See example 300 for details.
In [2]:
from larch.examples import example
d = example(300, 'd')
We will be building a nested logit model, but in order to do so we need to rationalize the alternative numbers. As given, our raw itinerary choice data has a lot of alternatives, but they are not ordered or numbered in a regular way; each elemental alternative has an arbitrary code number assigned to it, and the code numbers for one case are not comparable to another case. We need to renumber the alternatives in a manner that is more suited for our application, such that based on the code number we can programatically extract a the relevant features of the alternative that we will want to use in building our nested logit model. In this example we want to test a model which has nests based on level of service. To renumber, first we will define the relevant categories and values, and establish a numbering system using a special object:
In [3]:
d1 = d.new_systematic_alternatives(
groupby='nb_cnxs',
name='alternative_code',
padding_levels=4,
groupby_prefixes=['Cnx'],
overwrite=False,
complete_features_list={'nb_cnxs':[0,1,2]},
)
If we compare the new data with the old data, we'll see that we have created a few more alternative.
In [4]:
d.info()
In [5]:
d1.info()
Now let's make our model. The utility function we will use is the same as the one we used for the MNL version of the model.
In [6]:
m = larch.Model(dataservice=d1)
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",
]
from larch.roles import PX
m.utility_ca = sum(PX(i) for i in v)
m.choice_ca_var = 'choice'
If we just end our model specification here, we will have a plain MNL model. To change to
a nested logit model, all we need to do is add the nests. We can do this easily, using the
special magic_nesting
method, that uses the structure of the data that we defined above.
In [7]:
m.magic_nesting()
In [8]:
m.load_data()
In [9]:
m.maximize_loglike()
Out[9]:
In [ ]: