def estimate_wrap(V, av, CHOICE, database, panelEst, ModNameSeqence, Draws): ''' # # # ''' if panelEst: #database.panel('ID') # Conditional to B_TIME_RND, the likelihood of one observation is # given by the logit model (called the kernel) obsprob = exp(models.loglogit(V, av, CHOICE)) # Conditional to B_TIME_RND, the likelihood of all observations for # one individual (the trajectory) is the product of the likelihood of # each observation. condprobIndiv = PanelLikelihoodTrajectory(obsprob) if Draws > 0: condprobIndiv = MonteCarlo(condprobIndiv) logprob = log(condprobIndiv) else: prob = exp(models.loglogit(V, av, CHOICE)) if Draws > 0: prob = MonteCarlo(prob) logprob = log(prob) if Draws > 0: biogeme = bio.BIOGEME(database, logprob, numberOfDraws=Draws) else: biogeme = bio.BIOGEME(database, logprob) biogeme.modelName = ModNameSeqence return biogeme.estimate()
def testEstimationAndSimulation(self): biogeme = bio.BIOGEME(database, logprob, numberOfThreads=1) results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike, -5214.049, 2) biosim = bio.BIOGEME(database, simulate) simresults = biosim.simulate(results.data.betaValues) self.assertAlmostEqual(sum(simresults['Prob. train']), 888.3883902853023, 1) self.assertAlmostEqual(sum(simresults['Elas. 1']), -17897.702976576973, 0)
def testEstimationAndSimulation(self): biogeme = bio.BIOGEME(database, logprob) results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike, -5214.049202307744, 1) biosim = bio.BIOGEME(database, simulate) simresults = biosim.simulate(results.data.betaValues) self.assertAlmostEqual(sum(simresults['Prob. train']), 888.3883902853023, 1) self.assertAlmostEqual(sum(simresults['Elas. 1']), -17898.420882021313, 0)
def evaluate_model(self, pandas_df_for_specified_country, model): # Estimation of probabilities for each alternative on aggregate. Simulate / forecast. def print_mode_shares(modename, modenumber): seriesObj = simresults.apply(lambda x: True if x['Actual choice'] == modenumber else False, axis=1) REAL = len(seriesObj[seriesObj == True].index) seriesObj = simresults.apply(lambda x: True if x['Simulated choice'] == modenumber else False, axis=1) SIMU = len(seriesObj[seriesObj == True].index) shares = (modename, '--> Real:' + "{0:.1%}".format(REAL / simresults.shape[0]) + '| Simu:' + "{0:.1%}".format(SIMU / simresults.shape[0])) print(shares) biosim = bio.BIOGEME(db.Database('estimationdb', pandas_df_for_specified_country), model.structure) biosim.modelName = "simulated_model" simresults = biosim.simulate(model.betas) # Add a column containing the suggestion from the model simresults['Simulated choice'] = simresults.idxmax(axis=1) # Add a column containing the actual choice of the individual simresults['Actual choice'] = pandas_df_for_specified_country['user_choice'].to_numpy() # Add a column which compares the predicted against the RP choice (correct prediction = 1, wrong prediction = 0) simresults['Correct prediction'] = np.where(simresults['Simulated choice'] == simresults['Actual choice'], 1, 0) #print_mode_shares('Depart earlier', 1) #print_mode_shares('Depart on-time', 2) #print_mode_shares('Depart later ', 3) return {'Model prediction accuracy': "{0:.1%}".format(simresults['Correct prediction'].mean()), 'Rho-square': "{0:.3}".format(model.results.getGeneralStatistics()['Rho-square-bar for the init. model'][0])}
def testSimulation(self): biogeme = bio.BIOGEME(database,simulate) biogeme.modelName = "01logit_simul" results = biogeme.simulate() self.assertAlmostEqual(sum(results['P1']),907.9992101964821,2) self.assertAlmostEqual(sum(results['logit elas. 1']),-12673.838605478186,2) self.assertAlmostEqual(sum(results['generic elas. 1']),-12673.838605478186,2)
def predict(self, trip_data, model_for_specified_country): for i in range(1, 7): trip_data['OCC_' + str(i)] = np.where(trip_data['user_occupation'] == i, 1, 0) trip_data['AGE'] = self.__birthday_to_age(trip_data['user_birthday']) # The trip is stored in a biogeme database, since it is required by Biogeme in order for it to function tripdb = db.Database("SuggestionDB", trip_data) # Simulate / forecast biosuggest = bio.BIOGEME(tripdb, model_for_specified_country.structure) biosuggest.modelName = "suggestion_to_user" suggestionresults = biosuggest.simulate(model_for_specified_country.betas) # Get the column index number of the max probability. This is My-TRAC's recommendation. Store it in a new col. suggestionresults['Recommendation'] = suggestionresults.idxmax(axis=1) suggestion = suggestionresults.values[0] # print('Trip data = ', trip_data.to_json()) # print('Results = ', # {'CAR': "{0:.1%}".format(suggestion[0]), # 'PT': "{0:.1%}".format(suggestion[1]), # 'BIKE/MOTO': "{0:.1%}".format(suggestion[2]), # 'My-TRAC recommendation': int(suggestion[3])}) return {'mod_car': suggestion[0], 'mod_pt': suggestion[1], 'mod_motbike': suggestion[2]}
def testEstimation(self): logprob = models.loglogit(V,av,CHOICE) weight = 8.890991e-01 * (1.0 * (GROUP == 2) + 1.2 * (GROUP == 3)) formulas = {'loglike':logprob,'weight':weight} biogeme = bio.BIOGEME(database,formulas) results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike,-5273.743,2)
def predict(self, trip_data, model_for_specified_country): trip_data['AGE'] = self.__birthday_to_age(trip_data['user_birthday']) # The trip is stored in a biogeme database, since it is required by Biogeme in order for it to function tripdb = db.Database("SuggestionDB", trip_data) # Simulate / forecast biosuggest = bio.BIOGEME(tripdb, model_for_specified_country.structure) biosuggest.modelName = "suggestion_to_user" suggestionresults = biosuggest.simulate( model_for_specified_country.betas) # Get the column index number of the max probability. This is My-TRAC's recommendation. Store it in a new col. suggestionresults['Recommendation'] = suggestionresults.idxmax(axis=1) suggestion = suggestionresults.values[0] # print('Trip data = ', trip_data.to_json()) # print('Results = ', # {'Depart earlier': "{0:.1%}".format(suggestion[0]), # 'Depart on-time': "{0:.1%}".format(suggestion[1]), # 'Depart later': "{0:.1%}".format(suggestion[2]), # 'My-TRAC recommendation': int(suggestion[3])}) return { 'tod_earlier': suggestion[0], 'tod_ontime': suggestion[1], 'tod_later': suggestion[2] }
def testEstimationScipy(self): logprob = models.loglogit(V, av, CHOICE) biogeme = bio.BIOGEME(database, logprob, seed=10, numberOfThreads=1) biogeme.modelName = "test_01" results = biogeme.estimate(bootstrap=10, algorithm=opt.scipy) self.assertAlmostEqual(results.data.logLike, -5331.252, 2) self.assertAlmostEqual(results.data.betas[0].bootstrap_stdErr, 0.04773096176427237, 2)
def train_MNL(data): for mode in modes_list: # availability data[mode+'_avail'] = 1 database = db.Database("MNL_SGP", data) beta_dic = {} variables = {} ASC_WALK = bioexp.Beta('B___ASC___Walk',0,None,None,1) #fixed ASC_PT = bioexp.Beta('B___ASC___PT',0,None,None,0) ASC_RIDEHAIL = bioexp.Beta('B___ASC___RH',0,None,None,0) ASC_AV = bioexp.Beta('B___ASC___AV',0,None,None,0) ASC_DRIVE = bioexp.Beta('B___ASC___Drive',0,None,None,0) for key in att: beta_dic[key] = {} if key != 'Walk': for var in z_vars: if var not in variables: variables[var] = bioexp.Variable(var) beta_name = 'B___' + var + '___' + key beta_dic[key][beta_name] = bioexp.Beta(beta_name, 0, None, None, 0) for var in att[key]: if var not in variables: variables[var] = bioexp.Variable(var) beta_name = 'B___' + var + '___' + key beta_dic[key][beta_name] = bioexp.Beta(beta_name, 0, None, None, 0) V = {key_choice_index['Walk']:ASC_WALK, key_choice_index['PT']:ASC_PT, key_choice_index['RH']:ASC_RIDEHAIL,key_choice_index['AV']:ASC_AV, key_choice_index['Drive']:ASC_DRIVE} AV = {} for key in att: AV[key_choice_index[key]] = bioexp.Variable(key+'_avail') if key != 'Walk': for var in z_vars: beta_name = 'B___' + var + '___' + key V[key_choice_index[key]] += variables[var] * beta_dic[key][beta_name] for var in att[key]: beta_name = 'B___' + var + '___' + key V[key_choice_index[key]] += variables[var] * beta_dic[key][beta_name] CHOICE = bioexp.Variable('choice') logprob = bioexp.bioLogLogit(V, AV, CHOICE) formulas = {'loglike': logprob} biogeme = bio.BIOGEME(database, formulas,numberOfThreads = 4) biogeme.modelName = "MNL_SGP" results = biogeme.estimate() os.remove("MNL_SGP.html") os.remove("MNL_SGP.pickle") # Print the estimated values betas = results.getBetaValues() beta={} for k, v in betas.items(): beta[k] = v return beta
def testEstimation(self): for k,f in self.models.items(): logging.info("Estimate {}".format(k)) ; biogeme = bio.BIOGEME(f[0],f[1],seed=10,numberOfDraws=5) biogeme.modelName = k biogeme.generateHtml = False results = biogeme.estimate() with self.subTest(msg="{}: check final log likelihhood".format(k)): self.assertAlmostEqual(results.data.logLike,f[2],2)
def build(self): exclude = ((self.PURPOSE != 1) * (self.PURPOSE != 3) + (self.CHOICE == 0)) > 0 self.database.remove(exclude) ASC_CAR = Beta('ASC_CAR', 0, None, None, 0, 'Car cte.') ASC_TRAIN = Beta('ASC_TRAIN', 0, None, None, 0, 'Train cte.') ASC_SM = Beta('ASC_SM', 0, None, None, 1, 'Swissmetro cte.') B_TIME = Beta('B_TIME', 0, None, None, 0, 'Travel time') B_COST = Beta('B_COST', 0, None, None, 0, 'Travel cost') SM_COST = self.SM_CO * (self.GA == 0) TRAIN_COST = self.TRAIN_CO * (self.GA == 0) TRAIN_TT_SCALED = DefineVariable('TRAIN_TT_SCALED', \ self.TRAIN_TT / 100.0, self.database) TRAIN_COST_SCALED = DefineVariable('TRAIN_COST_SCALED', \ TRAIN_COST / 100, self.database) SM_TT_SCALED = DefineVariable('SM_TT_SCALED', self.SM_TT / 100.0, self.database) SM_COST_SCALED = DefineVariable('SM_COST_SCALED', SM_COST / 100, self.database) CAR_TT_SCALED = DefineVariable('CAR_TT_SCALED', self.CAR_TT / 100, self.database) CAR_CO_SCALED = DefineVariable('CAR_CO_SCALED', self.CAR_CO / 100, self.database) self.x0 = np.zeros(4) V1 = ASC_TRAIN + \ B_TIME * TRAIN_TT_SCALED + \ B_COST * TRAIN_COST_SCALED V2 = ASC_SM + \ B_TIME * SM_TT_SCALED + \ B_COST * SM_COST_SCALED V3 = ASC_CAR + \ B_TIME * CAR_TT_SCALED + \ B_COST * CAR_CO_SCALED # Associate utility functions with the numbering of alternatives self.V = {1: V1, 2: V2, 3: V3} # Associate the availability conditions with the alternatives CAR_AV_SP = DefineVariable('CAR_AV_SP', self.CAR_AV * (self.SP != 0), self.database) TRAIN_AV_SP = DefineVariable('TRAIN_AV_SP', self.TRAIN_AV * (self.SP != 0), self.database) self.av = {1: TRAIN_AV_SP, 2: self.SM_AV, 3: CAR_AV_SP} logprob = bioLogLogit(self.V, self.av, self.CHOICE) self.biogeme = bio.BIOGEME(self.database, logprob) self.biogeme.modelName = "01logit" self.biogeme.generateHtml = False
def probas(self, betas=None): # The choice model is a logit, with availability conditions prob1 = models.logit(self.V, self.av, 1) prob2 = models.logit(self.V, self.av, 2) prob3 = models.logit(self.V, self.av, 3) simulate = {'Train': prob1, 'SM': prob2, 'Car': prob3} biogeme = bio.BIOGEME(self.database, simulate) biogeme.modelName = "01logit_simul" self.biogeme.generateHtml = False return biogeme.simulate(betas)
def build(self): # Parameters to be estimated ASC_WALKING = Beta('ASC_WALKING', 0, -10, 10, 1) ASC_CYCLING = Beta('ASC_CYCLING', 0, -10, 10, 0) ASC_PT = Beta('ASC_PT', 0, -10, 10, 0) ASC_DRIVING = Beta('ASC_DRIVING', 0, -10, 10, 0) B_TIME_WALKING = Beta('B_TIME_WALKING', 0, -10, 10, 0) B_TIME_CYCLING = Beta('B_TIME_CYCLING', 0, -10, 10, 0) B_TIME_DRIVING = Beta('B_TIME_DRIVING', 0, -10, 10, 0) B_COST_DRIVING = Beta('B_COST_DRIVING', 0, -10, 10, 0) B_COST_PT = Beta('B_COST_PT', 0, -10, 10, 0) B_TIME_PT_BUS = Beta('B_TIME_PT_BUS', 0, -10, 10, 0) B_TIME_PT_RAIL = Beta('B_TIME_PT_RAIL', 0, -10, 10, 0) B_TIME_PT_ACCESS = Beta('B_TIME_PT_ACCESS', 0, -10, 10, 0) # B_INT_WALK = Beta('B_INT_WALK',0,-10,10,0) B_TIME_PT_INT_WAIT = Beta('B_TIME_PT_INT_WAIT', 0, -10, 10, 0) B_TRAFFIC_DRIVING = Beta('B_TRAFFIC_DRIVING', 0, -10, 10, 0) # Utility functions V1 = (ASC_WALKING + B_TIME_WALKING * self.dur_walking) V2 = (ASC_CYCLING + B_TIME_CYCLING * self.dur_cycling) V3 = (ASC_PT + B_COST_PT * self.cost_transit + B_TIME_PT_ACCESS * self.dur_access + B_TIME_PT_RAIL * self.dur_pt_rail + B_TIME_PT_BUS * self.dur_pt_bus + B_TIME_PT_INT_WAIT * self.dur_interchange_waiting) V4 = (ASC_DRIVING + B_TIME_DRIVING * self.dur_driving + B_COST_DRIVING * (self.cost_driving + self.con_charge) + B_TRAFFIC_DRIVING * self.traffic_percent) # Associate utility functions with the numbering of alternatives V = {1: V1, 2: V2, 3: V3, 4: V4} av = {1: 1, 2: 1, 3: 1, 4: 1} # The choice model is a logit, with availability conditions logprob = bioLogLogit(V, av, self.tmode) self.biogeme = bio.BIOGEME(self.database, logprob) self.biogeme.modelName = "LPMC_MNL_DC" self.biogeme.generateHtml = False self.x0 = self.biogeme.betaInitValues
def setUp(self): np.random.seed(90267) rnd.seed(90267) Choice = Variable('Choice') Variable1 = Variable('Variable1') Variable2 = Variable('Variable2') beta1 = Beta('beta1', 0, None, None, 0) beta2 = Beta('beta2', 0, None, None, 0) V1 = beta1 * Variable1 V2 = beta2 * Variable2 V3 = 0 V = {1: V1, 2: V2, 3: V3} likelihood = models.loglogit(V, av=None, i=Choice) self.myBiogeme = bio.BIOGEME(myData1, likelihood) self.myBiogeme.modelName = 'simpleExample' self.theFunction = rosenbrock()
def setUp(self): np.random.seed(90267) rnd.seed(90267) Variable1 = Variable('Variable1') Variable2 = Variable('Variable2') beta1 = Beta('beta1', -1.0, -3, 3, 0) beta2 = Beta('beta2', 2.0, -3, 10, 0) likelihood = -beta1**2 * Variable1 - exp( beta2 * beta1) * Variable2 - beta2**4 simul = beta1 / Variable1 + beta2 / Variable2 dictOfExpressions = { 'loglike': likelihood, 'beta1': beta1, 'simul': simul } self.myBiogeme = bio.BIOGEME(myData1, dictOfExpressions) self.myBiogeme.modelName = 'simpleExample'
def predict_NL_2(betas, biogeme_file, data): for mode in modes_list: # availability data[mode+'_avail'] = 1 database = db.Database("NL_SGP", data) # The choice model is a nested logit prob_Walk = biomodels.nested(biogeme_file['V'], biogeme_file['av'], biogeme_file['nests'], key_choice_index['Walk']) prob_PT = biomodels.nested(biogeme_file['V'], biogeme_file['av'], biogeme_file['nests'], key_choice_index['PT']) prob_RH = biomodels.nested(biogeme_file['V'], biogeme_file['av'], biogeme_file['nests'], key_choice_index['RH']) prob_AV = biomodels.nested(biogeme_file['V'], biogeme_file['av'], biogeme_file['nests'], key_choice_index['AV']) prob_Drive = biomodels.nested(biogeme_file['V'], biogeme_file['av'], biogeme_file['nests'], key_choice_index['Drive']) simulate = {'prob_Walk': prob_Walk, 'prob_PT': prob_PT, 'prob_RH': prob_RH, 'prob_AV':prob_AV, 'prob_Drive':prob_Drive} biogeme = bio.BIOGEME(database, simulate) # Extract the values that are necessary betaValues = betas # simulatedValues is a Panda dataframe with the same number of rows as # the database, and as many columns as formulas to simulate. simulatedValues = biogeme.simulate(betaValues) prob_list = list(simulatedValues.columns) data_test = data for key in prob_list: data_test[key] = 0 data_test.loc[:,prob_list] = simulatedValues.loc[:, prob_list] data_test['max_prob'] = data_test[prob_list].max(axis=1) data_test['CHOOSE'] = 0 for mode in key_choice_index: col_nameprob = 'prob_' + mode data_test.loc[data_test[col_nameprob]==data_test['max_prob'],'CHOOSE'] = key_choice_index[mode] acc = len(data_test.loc[data_test['CHOOSE']==data_test['choice']])/len(data_test) return acc, data_test
def train_MNL(data): for mode in modes_list: # availability data[mode+'_avail'] = 1 database = db.Database("MNL_Train", data) beta_dic = {} variables = {} ASC_1 = bioexp.Beta('B___ASC___choice1',0,None,None,1) #fixed ASC_2 = bioexp.Beta('B___ASC___choice2',0,None,None,0) for key in att: beta_dic[key] = {} for var in att[key]: if var not in variables: variables[var] = bioexp.Variable(var) beta_name = 'B___' + var + '___' + key beta_dic[key][beta_name] = bioexp.Beta(beta_name, 0, None, None, 0) V = {key_choice_index['choice1']:ASC_1, key_choice_index['choice2']:ASC_2} AV = {} for key in att: AV[key_choice_index[key]] = bioexp.Variable(key+'_avail') for var in att[key]: beta_name = 'B___' + var + '___' + key V[key_choice_index[key]] += variables[var] * beta_dic[key][beta_name] CHOICE = bioexp.Variable('choice') logprob = bioexp.bioLogLogit(V, AV, CHOICE) formulas = {'loglike': logprob} biogeme = bio.BIOGEME(database, formulas,numberOfThreads = 4) biogeme.modelName = "MNL_Train" results = biogeme.estimate() os.remove("MNL_Train.html") os.remove("MNL_Train.pickle") # Print the estimated values betas = results.getBetaValues() beta={} for k, v in betas.items(): beta[k] = v return beta
def testEstimation(self): AutoTime = Variable('AutoTime') TransitTime = Variable('TransitTime') Choice = Variable('Choice') ASC_CAR = Beta('ASC_CAR', 0, None, None, 0) B_TIME = Beta('B_TIME', 0, None, None, 0) V = {0: ASC_CAR + B_TIME * AutoTime, 1: B_TIME * TransitTime} av = {0: 1, 1: 1} logprob = models.loglogit(V, av, Choice) biogeme = bio.BIOGEME(self.database, logprob) biogeme.modelName = 'test' biogeme.generateHtml = False results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike, -6.166042, 2)
B_COST * SM_COST_SCALED V3 = ASC_CAR + \ B_TIME * models.boxcox(CAR_TT_SCALED, LAMBDA) + \ B_COST * CAR_CO_SCALED # Associate utility functions with the numbering of alternatives V = {1: V1, 2: V2, 3: V3} # Associate the availability conditions with the alternatives av = {1: TRAIN_AV_SP, 2: SM_AV, 3: CAR_AV_SP} # Definition of the model. This is the contribution of each # observation to the log likelihood function. logprob = models.loglogit(V, av, CHOICE) # Define level of verbosity logger = msg.bioMessage() logger.setSilent() #logger.setWarning() #logger.setGeneral() #logger.setDetailed() # Create the Biogeme object biogeme = bio.BIOGEME(database, logprob) biogeme.modelName = '08boxcox' # Estimate the parameters results = biogeme.estimate() pandasResults = results.getEstimatedParameters() print(pandasResults)
def testEstimation(self): biogeme = bio.BIOGEME(database, logprob, numberOfDraws=5, seed=10) results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike, -4705.638407401872, 2)
B_COST = Beta('B_COST', 0, None, None, 0) tau1 = Beta('tau1', -1, None, 0, 0) delta2 = Beta('delta2', 2, 0, None, 0) tau2 = tau1 + delta2 TRAIN_COST = TRAIN_CO * (GA == 0) TRAIN_TT_SCALED = DefineVariable('TRAIN_TT_SCALED',\ TRAIN_TT / 100.0,database) TRAIN_COST_SCALED = DefineVariable('TRAIN_COST_SCALED',\ TRAIN_COST / 100,database) # Utility U = B_TIME * TRAIN_TT_SCALED + B_COST * TRAIN_COST_SCALED ChoiceProba = { 1: 1 - dist.logisticcdf(U - tau1), 2: dist.logisticcdf(U - tau1) - dist.logisticcdf(U - tau2), 3: dist.logisticcdf(U - tau2) } logprob = log(Elem(ChoiceProba, CHOICE)) biogeme = bio.BIOGEME(database, logprob, numberOfThreads=1) biogeme.modelName = "18ordinalLogit" results = biogeme.estimate() print("Results=", results)
V2 = ASC_SM + \ B_TIME_RND * SM_TT_SCALED + \ B_COST * SM_COST_SCALED V3 = ASC_CAR + \ B_TIME_RND * CAR_TT_SCALED + \ B_COST * CAR_CO_SCALED # Associate utility functions with the numbering of alternatives V = {1: V1, 2: V2, 3: V3} # Associate the availability conditions with the alternatives av = {1: TRAIN_AV_SP, 2: SM_AV, 3: CAR_AV_SP} # The choice model is a logit, with availability conditions prob = models.logit(V, av, CHOICE) logprob = log(MonteCarlo(prob)) R = 2000 biogeme = bio.BIOGEME(database, logprob, numberOfDraws=R) biogeme.modelName = '07estimationMonteCarlo_mlhs' results = biogeme.estimate() # Get the results in a pandas table pandasResults = results.getEstimatedParameters() print(pandasResults)
condlike = P_Envir01 * \ P_Envir02 * \ P_Envir03 * \ P_Mobil11 * \ P_Mobil14 * \ P_Mobil16 * \ P_Mobil17 * \ condprob # We integrate over omega using Monte-Carlo integration loglike = log(MonteCarlo(condlike)) # Define level of verbosity logger = msg.bioMessage() #logger.setSilent() #logger.setWarning() logger.setGeneral() #logger.setDetailed() # Create the Biogeme object biogeme = bio.BIOGEME(database, loglike, numberOfDraws=20000) biogeme.modelName = '06serialCorrelation' # Estimate the parameters results = biogeme.estimate() print(f'Estimated betas: {len(results.data.betaValues)}') print(f'Final log likelihood: {results.data.logLike:.3f}') print(f'Output file: {results.data.htmlFileName}') results.writeLaTeX() print(f'LaTeX file: {results.data.latexFileName}')
def testEstimation(self): biogeme = bio.BIOGEME(database, logprob) results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike, -5215.072, 2)
# Define level of verbosity logger = msg.bioMessage() #logger.setSilent() #logger.setWarning() logger.setGeneral() #logger.setDetailed() # These notes will be included as such in the report file. userNotes = ('Example of a logit model with three alternatives: Train, Car and Swissmetro.' ' Same as 01logit, using bioLinearUtility, and introducing some options ' 'and features.') # Create the Biogeme object biogeme = bio.BIOGEME(database, logprob, numberOfThreads=2, userNotes=userNotes) biogeme.modelName = '01logitBis' # Estimate the parameters results = biogeme.estimate(bootstrap=100, algorithm=opt.bioNewton, algoParameters={'hamabs': True}, saveIterations=True) biogeme.createLogFile(verbosity=3) # Get the results in a pandas table print('Parameters') print('----------') pandasResults = results.getEstimatedParameters() print(pandasResults)
def testEstimation(self): biogeme = bio.BIOGEME(database, logprob, numberOfDraws=5, seed=10) results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike, -4557.1998156795935, 2)
CAR_CO_SCALED = DefineVariable('CAR_CO_SCALED', CAR_CO / 100, database) V1 = ASC_TRAIN + \ B_TIME * TRAIN_TT_SCALED + \ B_COST * TRAIN_COST_SCALED V2 = ASC_SM + \ B_TIME * SM_TT_SCALED + \ B_COST * SM_COST_SCALED V3 = ASC_CAR + \ B_TIME * CAR_TT_SCALED + \ B_COST * CAR_CO_SCALED # Associate utility functions with the numbering of alternatives V = {1: V1, 2: V2, 3: V3} # Associate the availability conditions with the alternatives CAR_AV_SP = DefineVariable('CAR_AV_SP', CAR_AV * (SP != 0), database) TRAIN_AV_SP = DefineVariable('TRAIN_AV_SP', TRAIN_AV * (SP != 0), database) av = {1: TRAIN_AV_SP, 2: SM_AV, 3: CAR_AV_SP} logprob = bioLogLogit(V, av, CHOICE) weight = 8.890991e-01 * (1.0 * (GROUP == 2) + 1.2 * (GROUP == 3)) formulas = {'loglike': logprob, 'weight': weight} biogeme = bio.BIOGEME(database, formulas) biogeme.modelName = "02weight" results = biogeme.estimate() print("Results=", results)
def testEstimation(self): logprob = models.loglogit(V, av, CHOICE) biogeme = bio.BIOGEME(database, logprob) results = biogeme.estimate() self.assertAlmostEqual(results.data.logLike, -5423.299, 2)
CAR_TT_SCALED = CAR_TT / 100 CAR_CO_SCALED = CAR_CO / 100 # Definition of the utility functions V1 = ASC_TRAIN + \ B_TIME_RND * TRAIN_TT_SCALED + \ B_COST * TRAIN_COST_SCALED V2 = ASC_SM + \ B_TIME_RND * SM_TT_SCALED + \ B_COST * SM_COST_SCALED V3 = ASC_CAR + \ B_TIME_RND * CAR_TT_SCALED + \ B_COST * CAR_CO_SCALED # Associate utility functions with the numbering of alternatives V = {1: V1, 2: V2, 3: V3} # Associate the availability conditions with the alternatives av = {1: TRAIN_AV_SP, 2: SM_AV, 3: CAR_AV_SP} # The choice model is a logit, with availability conditions integrand = models.logit(V, av, CHOICE) numericalI = Integrate(integrand * density, 'omega') simulate = {'Numerical': numericalI} biogeme = bio.BIOGEME(database, simulate) results = biogeme.simulate() print('Mixture of logit - numerical integration: ', results.iloc[0]['Numerical'])