signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _uneven_transform_deriv_v(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>shape_params,<EOL>output_array=None,<EOL>*args, **kwargs):
<EOL>natural_shapes = np.exp(shape_params)<EOL>natural_shapes[np.isposinf(natural_shapes)] = max_comp_value<EOL>long_shapes = rows_to_alts.dot(natural_shapes)<EOL>exp_neg_utilities = np.exp(-<NUM_LIT:1> * systematic_utilities)<EOL>exp_shape_utilities = np.exp(long_shapes * systematic_utilities)<EOL>derivs = (<NUM_LIT:1...
Parameters ---------- systematic_utilities : 1D ndarray. All elements should be ints, floats, or longs. Should contain the systematic utilities of each observation per available alternative. Note that this vector is formed by the dot product of the design matrix with the vector of utility coefficients. ...
f7698:m2
def _uneven_transform_deriv_shape(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>shape_params,<EOL>output_array=None,<EOL>*args, **kwargs):
<EOL>natural_shapes = np.exp(shape_params)<EOL>natural_shapes[np.isposinf(natural_shapes)] = max_comp_value<EOL>long_shapes = rows_to_alts.dot(natural_shapes)<EOL>exp_shape_utilities = np.exp(long_shapes * systematic_utilities)<EOL>derivs = (systematic_utilities / (<NUM_LIT:1.0> + exp_shape_utilities))<EOL>derivs[np.is...
Parameters ---------- systematic_utilities : 1D ndarray. All elements should be ints, floats, or longs. Should contain the systematic utilities of each observation per available alternative. Note that this vector is formed by the dot product of the design matrix with the vector of utility coefficients. ...
f7698:m3
def _uneven_transform_deriv_alpha(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>intercept_params,<EOL>output_array=None,<EOL>*args, **kwargs):
return output_array<EOL>
Parameters ---------- systematic_utilities : 1D ndarray. All elements should be ints, floats, or longs. Should contain the systematic utilities of each observation per available alternative. Note that this vector is formed by the dot product of the design matrix with the vector of utility coefficients. ...
f7698:m4
def create_calc_dh_dv(estimator):
dh_dv = diags(np.ones(estimator.design.shape[<NUM_LIT:0>]), <NUM_LIT:0>, format='<STR_LIT>')<EOL>calc_dh_dv = partial(_uneven_transform_deriv_v, output_array=dh_dv)<EOL>return calc_dh_dv<EOL>
Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the index. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. Should contain a `design` attribute that is a 2D ndarray repre...
f7698:m5
def create_calc_dh_d_shape(estimator):
dh_d_shape = estimator.rows_to_alts.copy()<EOL>calc_dh_d_shape = partial(_uneven_transform_deriv_shape,<EOL>output_array=dh_d_shape)<EOL>return calc_dh_d_shape<EOL>
Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the shape parameters. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. Should contain a `rows_to_alts` attribute that is a...
f7698:m6
def create_calc_dh_d_alpha(estimator):
if estimator.intercept_ref_pos is not None:<EOL><INDENT>needed_idxs = range(estimator.rows_to_alts.shape[<NUM_LIT:1>])<EOL>needed_idxs.remove(estimator.intercept_ref_pos)<EOL>dh_d_alpha = (estimator.rows_to_alts<EOL>.copy()<EOL>.transpose()[needed_idxs, :]<EOL>.transpose())<EOL><DEDENT>else:<EOL><INDENT>dh_d_alpha = No...
Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the outside intercept parameters. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. Should contain a `rows_to_alts` attribu...
f7698:m7
def check_length_of_initial_values(self, init_values):
<EOL>num_alts = self.rows_to_alts.shape[<NUM_LIT:1>]<EOL>num_index_coefs = self.design.shape[<NUM_LIT:1>]<EOL>if self.intercept_ref_pos is not None:<EOL><INDENT>assumed_param_dimensions = num_index_coefs + <NUM_LIT:2> * num_alts - <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>assumed_param_dimensions = num_index_coefs + nu...
Ensures that `init_values` is of the correct length. Raises a helpful ValueError if otherwise. Parameters ---------- init_values : 1D ndarray. The initial values to start the optimizatin process with. There should be one value for each index coefficient, outside intercept parameter, and shape parameter bei...
f7698:c0:m1
def fit_mle(self,<EOL>init_vals,<EOL>init_shapes=None,<EOL>init_intercepts=None,<EOL>init_coefs=None,<EOL>print_res=True,<EOL>method="<STR_LIT>",<EOL>loss_tol=<NUM_LIT>,<EOL>gradient_tol=<NUM_LIT>,<EOL>maxiter=<NUM_LIT:1000>,<EOL>ridge=None,<EOL>constrained_pos=None,<EOL>just_point=False,<EOL>**kwargs):
<EOL>self.optimization_method = method<EOL>self.ridge_param = ridge<EOL>if ridge is not None:<EOL><INDENT>warnings.warn(_ridge_warning_msg)<EOL><DEDENT>mapping_res = self.get_mappings_for_fit()<EOL>rows_to_alts = mapping_res["<STR_LIT>"]<EOL>if init_vals is None and all([x is not None for x in [init_shapes,<EOL>init_co...
Parameters ---------- init_vals : 1D ndarray. The initial values to start the optimization process with. There should be one value for each index coefficient and shape parameter being estimated. Shape parameters should come before intercept parameters, which should come before index coefficients. On...
f7698:c1:m1
def ensure_valid_nums_in_specification_cols(specification, dataframe):
problem_cols = []<EOL>for col in specification:<EOL><INDENT>if dataframe[col].dtype.kind not in ['<STR_LIT:f>', '<STR_LIT:i>', '<STR_LIT:u>']:<EOL><INDENT>problem_cols.append(col)<EOL><DEDENT>elif np.isinf(dataframe[col]).any():<EOL><INDENT>problem_cols.append(col)<EOL><DEDENT>elif np.isnan(dataframe[col]).any():<EOL><...
Checks whether each column in `specification` contains numeric data, excluding positive or negative infinity and excluding NaN. Raises ValueError if any of the columns do not meet these requirements. Parameters ---------- specification : iterable of column headers in `dataframe`. dataframe : pandas DataFrame. Data...
f7699:m0
def ensure_ref_position_is_valid(ref_position, num_alts, param_title):
assert param_title in ['<STR_LIT>', '<STR_LIT>']<EOL>try:<EOL><INDENT>assert ref_position is None or isinstance(ref_position, int)<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise TypeError(msg.format(param_title))<EOL><DEDENT>if param_title == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>assert ...
Ensures that `ref_position` is None or an integer that is in the interval `[0, num_alts - 1]`. If None, ensures that intercepts are not the parameters being estimated. Raises a helpful ValueError if otherwise. Parameters ---------- ref_position : int. An integer denoting the position in an array of parameters that...
f7699:m1
def check_length_of_shape_or_intercept_names(name_list,<EOL>num_alts,<EOL>constrained_param,<EOL>list_title):
if len(name_list) != (num_alts - constrained_param):<EOL><INDENT>msg_1 = "<STR_LIT>".format(list_title)<EOL>msg_2 = "<STR_LIT>".format(list_title, len(name_list))<EOL>correct_length = num_alts - constrained_param<EOL>msg_3 = "<STR_LIT>".format(correct_length)<EOL>total_msg = "<STR_LIT:\n>".join([msg_1, msg_2, msg_3])<E...
Ensures that the length of the parameter names matches the number of parameters that will be estimated. Will raise a ValueError otherwise. Parameters ---------- name_list : list of strings. Each element should be the name of a parameter that is to be estimated. num_alts : int. Should be the total number of alt...
f7699:m2
def check_type_of_nest_spec_keys_and_values(nest_spec):
try:<EOL><INDENT>assert all([isinstance(k, str) for k in nest_spec])<EOL>assert all([isinstance(nest_spec[k], list) for k in nest_spec])<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise TypeError(msg)<EOL><DEDENT>return None<EOL>
Ensures that the keys and values of `nest_spec` are strings and lists. Raises a helpful ValueError if they are. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which ...
f7699:m3
def check_for_empty_nests_in_nest_spec(nest_spec):
empty_nests = []<EOL>for k in nest_spec:<EOL><INDENT>if len(nest_spec[k]) == <NUM_LIT:0>:<EOL><INDENT>empty_nests.append(k)<EOL><DEDENT><DEDENT>if empty_nests != []:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(empty_nests))<EOL><DEDENT>return None<EOL>
Ensures that the values of `nest_spec` are not empty lists. Raises a helpful ValueError if they are. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. ...
f7699:m4
def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements):
try:<EOL><INDENT>assert all([isinstance(x, int) for x in list_elements])<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL>
Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nest...
f7699:m5
def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements):
try:<EOL><INDENT>assert len(set(list_elements)) == len(list_elements)<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL>
Ensures that the alternative id's in `nest_spec` are only associated with a single nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alterna...
f7699:m6
def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids):
unaccounted_alt_ids = []<EOL>for alt_id in all_ids:<EOL><INDENT>if alt_id not in list_elements:<EOL><INDENT>unaccounted_alt_ids.append(alt_id)<EOL><DEDENT><DEDENT>if unaccounted_alt_ids != []:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(unaccounted_alt_ids))<EOL><DEDENT>return None<EOL>
Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives be...
f7699:m7
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids):
invalid_alt_ids = []<EOL>for x in list_elements:<EOL><INDENT>if x not in all_ids:<EOL><INDENT>invalid_alt_ids.append(x)<EOL><DEDENT><DEDENT>if invalid_alt_ids != []:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(invalid_alt_ids))<EOL><DEDENT>return None<EOL>
Ensures that the alternative id's in `nest_spec` are all in the universal choice set for this dataset. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting...
f7699:m8
def add_intercept_to_dataframe(specification, dataframe):
if "<STR_LIT>" in specification and "<STR_LIT>" not in dataframe.columns:<EOL><INDENT>dataframe["<STR_LIT>"] = <NUM_LIT:1.0><EOL><DEDENT>return None<EOL>
Checks whether `intercept` is in `specification` but not in `dataframe` and adds the required column to dataframe. Note this function is not idempotent--it alters the original argument, `dataframe`. Parameters ---------- specification : an iterable that has a `__contains__` method. dataframe : pandas DataFrame. Da...
f7699:m9
def check_num_rows_of_parameter_array(param_array, correct_num_rows, title):
if param_array.shape[<NUM_LIT:0>] != correct_num_rows:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(title, correct_num_rows))<EOL><DEDENT>return None<EOL>
Ensures that `param_array.shape[0]` has the correct magnitude. Raises a helpful ValueError if otherwise. Parameters ---------- param_array : ndarray. correct_num_rows : int. The int that `param_array.shape[0]` should equal. title : str. The 'name' of the param_array whose shape is being checked. Results -----...
f7699:m10
def check_type_and_size_of_param_list(param_list, expected_length):
try:<EOL><INDENT>assert isinstance(param_list, list)<EOL>assert len(param_list) == expected_length<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(expected_length))<EOL><DEDENT>return None<EOL>
Ensure that param_list is a list with the expected length. Raises a helpful ValueError if this is not the case.
f7699:m11
def check_type_of_param_list_elements(param_list):
try:<EOL><INDENT>assert isinstance(param_list[<NUM_LIT:0>], np.ndarray)<EOL>assert all([(x is None or isinstance(x, np.ndarray))<EOL>for x in param_list])<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>total_msg = msg + "<STR_LIT:\n>" + msg_2<EOL>raise TypeError(total_msg)<...
Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise.
f7699:m12
def check_num_columns_in_param_list_arrays(param_list):
try:<EOL><INDENT>num_columns = param_list[<NUM_LIT:0>].shape[<NUM_LIT:1>]<EOL>assert all([x is None or (x.shape[<NUM_LIT:1>] == num_columns)<EOL>for x in param_list])<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL>
Ensure that each array in param_list, that is not None, has the same number of columns. Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None.
f7699:m13
def check_dimensional_equality_of_param_list_arrays(param_list):
try:<EOL><INDENT>num_dimensions = len(param_list[<NUM_LIT:0>].shape)<EOL>assert num_dimensions in [<NUM_LIT:1>, <NUM_LIT:2>]<EOL>assert all([(x is None or (len(x.shape) == num_dimensions))<EOL>for x in param_list])<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>total_msg = ...
Ensures that all arrays in param_list have the same dimension, and that this dimension is either 1 or 2 (i.e. all arrays are 1D arrays or all arrays are 2D arrays.) Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None.
f7699:m14
def check_for_choice_col_based_on_return_long_probs(return_long_probs,<EOL>choice_col):
if not return_long_probs and choice_col is None:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Ensure that if return_long_probs is False then choice_col is not None. Raise a helpful ValueError if otherwise. Parameters ---------- return_long_probs : bool. Indicates whether or not the long format probabilites (a 1D numpy array with one element per observation per available alternative) sho...
f7699:m15
def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars,<EOL>name_dict,<EOL>ind_var_names):
if mixing_vars is None:<EOL><INDENT>return None<EOL><DEDENT>problem_names = [variable_name for variable_name in mixing_vars<EOL>if variable_name not in ind_var_names]<EOL>msg_0 = "<STR_LIT>"<EOL>msg_1 = "<STR_LIT>"<EOL>msg_with_name_dict = msg_0 + msg_1.format(problem_names)<EOL>msg_2 = "<STR_LIT>"<EOL>msg_3 = "<STR_LI...
Ensures that all of the variables listed in `mixing_vars` are present in `ind_var_names`. Raises a helpful ValueError if otherwise. Parameters ---------- mixing_vars : list of strings, or None. Each string denotes a parameter to be treated as a random variable. name_dict : OrderedDict or None. Contains the spe...
f7699:m16
def ensure_all_alternatives_are_chosen(alt_id_col, choice_col, dataframe):
all_ids = set(dataframe[alt_id_col].unique())<EOL>chosen_ids = set(dataframe.loc[dataframe[choice_col] == <NUM_LIT:1>,<EOL>alt_id_col].unique())<EOL>non_chosen_ids = all_ids.difference(chosen_ids)<EOL>if len(non_chosen_ids) != <NUM_LIT:0>:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise ValueError(msg.format(...
Ensures that all of the available alternatives in the dataset are chosen at least once (for model identification). Raises a ValueError otherwise. Parameters ---------- alt_id_col : str. Should denote the column in `dataframe` that contains the alternative identifiers for each row. choice_col : str. Should ...
f7699:m17
def compute_aic(model_object):
assert isinstance(model_object.params, pd.Series)<EOL>assert isinstance(model_object.log_likelihood, Number)<EOL>return -<NUM_LIT:2> * model_object.log_likelihood + <NUM_LIT:2> * model_object.params.size<EOL>
Compute the Akaike Information Criteria for an estimated model. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` should be a number, and `model_object.params` should be a pandas Serie...
f7699:m18
def compute_bic(model_object):
assert isinstance(model_object.params, pd.Series)<EOL>assert isinstance(model_object.log_likelihood, Number)<EOL>assert isinstance(model_object.nobs, Number)<EOL>log_likelihood = model_object.log_likelihood<EOL>num_obs = model_object.nobs<EOL>num_params = model_object.params.size<EOL>return -<NUM_LIT:2> * log_likelihoo...
Compute the Bayesian Information Criteria for an estimated model. Parameters ---------- model_object : an MNDC_Model (multinomial discrete choice model) instance. The model should have already been estimated. `model_object.log_likelihood` and `model_object.nobs` should be a number, and `model_object.params...
f7699:m19
def get_mappings_for_fit(self, dense=False):
return create_long_form_mappings(self.data,<EOL>self.obs_id_col,<EOL>self.alt_id_col,<EOL>choice_col=self.choice_col,<EOL>nest_spec=self.nest_spec,<EOL>mix_id_col=self.mixing_id_col,<EOL>dense=dense)<EOL>
Parameters ---------- dense : bool, optional. Dictates if sparse matrices will be returned or dense numpy arrays. Returns ------- mapping_dict : OrderedDict. Keys will be `["rows_to_obs", "rows_to_alts", "chosen_row_to_obs", "rows_to_nests"]`. The value for `rows_to_obs` will map the rows of the `long_...
f7699:c0:m1
def _store_basic_estimation_results(self, results_dict):
<EOL>self.log_likelihood = results_dict["<STR_LIT>"]<EOL>self.fitted_probs = results_dict["<STR_LIT>"]<EOL>self.long_fitted_probs = results_dict["<STR_LIT>"]<EOL>self.long_residuals = results_dict["<STR_LIT>"]<EOL>self.ind_chi_squareds = results_dict["<STR_LIT>"]<EOL>self.chi_square = self.ind_chi_squareds.sum()<EOL>se...
Extracts the basic estimation results (i.e. those that need no further calculation or logic applied to them) and stores them on the model object. Parameters ---------- results_dict : dict. The estimation result dictionary that is output from scipy.optimize.minimize. In addition to the standard keys which are ...
f7699:c0:m2
def _create_results_summary(self):
<EOL>needed_attributes = ["<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>try:<EOL><INDENT>assert all([hasattr(self, attr) for attr in needed_attributes])<EOL>assert all([isinstance(getattr(self, attr), pd.Series)<EOL>for attr in needed_attributes])...
Create the dataframe that displays the estimation results, and store it on the model instance. Returns ------- None.
f7699:c0:m3
def _record_values_for_fit_summary_and_statsmodels(self):
<EOL>needed_attributes = ["<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>try:<EOL><INDENT>assert all([hasattr(self, attr) for attr in needed_attributes])<EOL>assert all([getattr(self, attr) is not None<EOL>for attr in needed_attributes])<EOL><DEDENT>except AssertionError:<EOL><INDENT>msg = "<STR_LI...
Store the various estimation results that are used to describe how well the estimated model fits the given dataset, and record the values that are needed for the statsmodels estimation results table. All values are stored on the model instance. Returns ------- None.
f7699:c0:m4
def _create_fit_summary(self):
<EOL>needed_attributes = ["<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>try:<EOL><INDENT>assert all([hasattr(self, attr) for attr in needed_attributes])<EOL>assert all([getattr(self, attr) is not None<EOL>for attr in needed_attributes])<EOL><DEDEN...
Create and store a pandas series that will display to users the various statistics/values that indicate how well the estimated model fit the given dataset. Returns ------- None.
f7699:c0:m5
def _store_inferential_results(self,<EOL>value_array,<EOL>index_names,<EOL>attribute_name,<EOL>series_name=None,<EOL>column_names=None):
if len(value_array.shape) == <NUM_LIT:1>:<EOL><INDENT>assert series_name is not None<EOL>new_attribute_value = pd.Series(value_array,<EOL>index=index_names,<EOL>name=series_name)<EOL><DEDENT>elif len(value_array.shape) == <NUM_LIT:2>:<EOL><INDENT>assert column_names is not None<EOL>new_attribute_value = pd.DataFrame(va...
Store the estimation results that relate to statistical inference, such as parameter estimates, standard errors, p-values, etc. Parameters ---------- value_array : 1D or 2D ndarray. Contains the values that are to be stored on the model instance. index_names : list of strings. Contains the names that are to be...
f7699:c0:m6
def _store_generic_inference_results(self,<EOL>results_dict,<EOL>all_params,<EOL>all_names):
<EOL>self._store_inferential_results(results_dict["<STR_LIT>"],<EOL>index_names=self.ind_var_names,<EOL>attribute_name="<STR_LIT>",<EOL>series_name="<STR_LIT>")<EOL>self._store_inferential_results(results_dict["<STR_LIT>"],<EOL>index_names=all_names,<EOL>attribute_name="<STR_LIT>",<EOL>series_name="<STR_LIT>")<EOL>self...
Store the model inference values that are common to all choice models. This includes things like index coefficients, gradients, hessians, asymptotic covariance matrices, t-values, p-values, and robust versions of these values. Parameters ---------- results_dict : dict. The estimation result dictionary that is outp...
f7699:c0:m7
def _store_optional_parameters(self,<EOL>optional_params,<EOL>name_list_attr,<EOL>default_name_str,<EOL>all_names,<EOL>all_params,<EOL>param_attr_name,<EOL>series_name):
<EOL>num_elements = optional_params.shape[<NUM_LIT:0>]<EOL>parameter_names = getattr(self, name_list_attr)<EOL>if parameter_names is None:<EOL><INDENT>parameter_names = [default_name_str.format(x) for x in<EOL>range(<NUM_LIT:1>, num_elements + <NUM_LIT:1>)]<EOL><DEDENT>all_names = list(parameter_names) + list(all_names...
Extract the optional parameters from the `results_dict`, save them to the model object, and update the list of all parameters and all parameter names. Parameters ---------- optional_params : 1D ndarray. The optional parameters whose values and names should be stored. name_list_attr : str. The attribute name on...
f7699:c0:m8
def _adjust_inferential_results_for_parameter_constraints(self,<EOL>constraints):
if constraints is not None:<EOL><INDENT>inferential_attributes = ["<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>assert all([hasattr(self, x) for x in inferential_attributes])<EOL>assert hasattr(self, "<STR_LIT>")<EOL>all_names = self.params.index.tolist()<EOL>for ...
Ensure that parameters that were constrained during estimation do not have any values showed for inferential results. After all, no inference was performed. Parameters ---------- constraints : list of ints, or None. If list, should contain the positions in the array of all estimated parameters that were constr...
f7699:c0:m9
def _check_result_dict_for_needed_keys(self, results_dict):
missing_cols = [x for x in needed_result_keys if x not in results_dict]<EOL>if missing_cols != []:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(missing_cols))<EOL><DEDENT>return None<EOL>
Ensure that `results_dict` has the needed keys to store all the estimation results. Raise a helpful ValueError otherwise.
f7699:c0:m10
def _add_mixing_variable_names_to_individual_vars(self):
assert isinstance(self.ind_var_names, list)<EOL>already_included = any(["<STR_LIT>" in x for x in self.ind_var_names])<EOL>if self.mixing_vars is not None and not already_included:<EOL><INDENT>new_ind_var_names = ["<STR_LIT>" + x for x in self.mixing_vars]<EOL>self.ind_var_names += new_ind_var_names<EOL><DEDENT>return ...
Ensure that the model objects mixing variables are added to its list of individual variables.
f7699:c0:m11
def store_fit_results(self, results_dict):
<EOL>self._check_result_dict_for_needed_keys(results_dict)<EOL>self._store_basic_estimation_results(results_dict)<EOL>if not hasattr(self, "<STR_LIT>"):<EOL><INDENT>self.design_3d = None<EOL><DEDENT>self._add_mixing_variable_names_to_individual_vars()<EOL>all_names = deepcopy(self.ind_var_names)<EOL>all_params = [deepc...
Parameters ---------- results_dict : dict. The estimation result dictionary that is output from scipy.optimize.minimize. In addition to the standard keys which are included, it should also contain the following keys: `["final_gradient", "final_hessian", "fisher_info", "final_log_likelihood", "chosen...
f7699:c0:m12
def fit_mle(self,<EOL>init_vals,<EOL>print_res=True,<EOL>method="<STR_LIT>",<EOL>loss_tol=<NUM_LIT>,<EOL>gradient_tol=<NUM_LIT>,<EOL>maxiter=<NUM_LIT:1000>,<EOL>ridge=None,<EOL>*args):
msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL>
Parameters ---------- init_vals : 1D ndarray. The initial values to start the optimizatin process with. There should be one value for each utility coefficient, outside intercept parameter, shape parameter, and nest parameter being estimated. print_res : bool, optional. Determines whether the timing and ...
f7699:c0:m13
def print_summaries(self):
if hasattr(self, "<STR_LIT>") and hasattr(self, "<STR_LIT>"):<EOL><INDENT>print("<STR_LIT:\n>")<EOL>print(self.fit_summary)<EOL>print("<STR_LIT:=>" * <NUM_LIT:30>)<EOL>print(self.summary)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise NotImplementedError(msg.format(self.model_type) + ...
Returns None. Will print the measures of fit and the estimation results for the model.
f7699:c0:m14
def conf_int(self, alpha=<NUM_LIT>, coefs=None, return_df=False):
<EOL>z_critical = scipy.stats.norm.ppf(<NUM_LIT:1.0> - alpha / <NUM_LIT>,<EOL>loc=<NUM_LIT:0>, scale=<NUM_LIT:1>)<EOL>lower = self.params - z_critical * self.standard_errors<EOL>upper = self.params + z_critical * self.standard_errors<EOL>lower.name = "<STR_LIT>"<EOL>upper.name = "<STR_LIT>"<EOL>combined = pd.concat((lo...
Creates the dataframe or array of lower and upper bounds for the (1-alpha)% confidence interval of the estimated parameters. Used when creating the statsmodels summary. Parameters ---------- alpha : float, optional. Should be between 0.0 and 1.0. Determines the (1-alpha)% confidence interval that will be repor...
f7699:c0:m15
def get_statsmodels_summary(self,<EOL>title=None,<EOL>alpha=<NUM_LIT>):
try:<EOL><INDENT>from statsmodels.iolib.summary import Summary<EOL><DEDENT>except ImportError:<EOL><INDENT>print("<STR_LIT>")<EOL>return self.print_summaries()<EOL><DEDENT>if not hasattr(self, "<STR_LIT>"):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL><DEDENT>smry = Summary()<EOL>new_yname, new_...
Parameters ---------- title : str, or None, optional. Will be the title of the returned summary. If None, the default title is used. alpha : float, optional. Should be between 0.0 and 1.0. Determines the width of the displayed, (1 - alpha)% confidence interval. Returns ------- statsmodels.summary objec...
f7699:c0:m16
def check_param_list_validity(self, param_list):
if param_list is None:<EOL><INDENT>return None<EOL><DEDENT>check_type_and_size_of_param_list(param_list, <NUM_LIT:4>)<EOL>check_type_of_param_list_elements(param_list)<EOL>check_dimensional_equality_of_param_list_arrays(param_list)<EOL>if len(param_list[<NUM_LIT:0>].shape) == <NUM_LIT:2>:<EOL><INDENT>check_num_columns_...
Parameters ---------- param_list : list. Contains four elements, each being a numpy array. Either all of the arrays should be 1D or all of the arrays should be 2D. If 2D, the arrays should have the same number of columns. Each column being a particular set of parameter values that one wants to predict w...
f7699:c0:m17
def predict(self,<EOL>data,<EOL>param_list=None,<EOL>return_long_probs=True,<EOL>choice_col=None,<EOL>num_draws=None,<EOL>seed=None):
<EOL>dataframe = get_dataframe_from_data(data)<EOL>add_intercept_to_dataframe(self.specification, dataframe)<EOL>for column in [self.alt_id_col,<EOL>self.obs_id_col,<EOL>self.mixing_id_col]:<EOL><INDENT>if column is not None:<EOL><INDENT>ensure_columns_are_in_dataframe([column], dataframe)<EOL><DEDENT><DEDENT>self.chec...
Parameters ---------- data : string or pandas dataframe. If string, data should be an absolute or relative path to a CSV file containing the long format data for this choice model. Note long format is has one row per available alternative for each observation. If pandas dataframe, the dataframe should b...
f7699:c0:m18
def to_pickle(self, filepath):
if not isinstance(filepath, str):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not filepath.endswith("<STR_LIT>"):<EOL><INDENT>filepath = filepath + "<STR_LIT>"<EOL><DEDENT>with open(filepath, "<STR_LIT:wb>") as f:<EOL><INDENT>pickle.dump(self, f)<EOL><DEDENT>print("<STR_LIT>".format(filepath))<EOL>return N...
Parameters ---------- filepath : str. Should end in .pkl. If it does not, ".pkl" will be appended to the passed string. Returns ------- None. Saves the model object to the location specified by `filepath`.
f7699:c0:m19
def calc_nested_probs(nest_coefs,<EOL>index_coefs,<EOL>design,<EOL>rows_to_obs,<EOL>rows_to_nests,<EOL>chosen_row_to_obs=None,<EOL>return_type="<STR_LIT>",<EOL>*args,<EOL>**kwargs):
<EOL>try:<EOL><INDENT>assert len(index_coefs.shape) <= <NUM_LIT:2><EOL>assert (len(index_coefs.shape) == <NUM_LIT:1>) or (index_coefs.shape[<NUM_LIT:1>] == <NUM_LIT:1>)<EOL>assert len(nest_coefs.shape) <= <NUM_LIT:2><EOL>assert (len(nest_coefs.shape) == <NUM_LIT:1>) or (nest_coefs.shape[<NUM_LIT:1>] == <NUM_LIT:1>)<EOL...
Parameters ---------- nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities of each alternative bein...
f7700:m0
def calc_nested_log_likelihood(nest_coefs,<EOL>index_coefs,<EOL>design,<EOL>rows_to_obs,<EOL>rows_to_nests,<EOL>choice_vector,<EOL>ridge=None,<EOL>weights=None,<EOL>*args,<EOL>**kwargs):
<EOL>long_probs = calc_nested_probs(nest_coefs,<EOL>index_coefs,<EOL>design,<EOL>rows_to_obs,<EOL>rows_to_nests,<EOL>return_type='<STR_LIT>')<EOL>if weights is None:<EOL><INDENT>weights = <NUM_LIT:1><EOL><DEDENT>log_likelihood = choice_vector.dot(weights * np.log(long_probs))<EOL>if ridge is None:<EOL><INDENT>return lo...
Parameters ---------- nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities of each alternative bein...
f7700:m1
def prep_vectors_for_gradient(nest_coefs,<EOL>index_coefs,<EOL>design,<EOL>choice_vec,<EOL>rows_to_obs,<EOL>rows_to_nests,<EOL>*args,<EOL>**kwargs):
<EOL>long_nest_params = (rows_to_nests.multiply(nest_coefs[None, :])<EOL>.sum(axis=<NUM_LIT:1>)<EOL>.A<EOL>.ravel())<EOL>scaled_y = choice_vec / long_nest_params<EOL>inf_index = np.isinf(scaled_y)<EOL>scaled_y[inf_index] = max_comp_value<EOL>obs_to_chosen_nests = (rows_to_obs.T *<EOL>rows_to_nests.multiply(choice_vec[:...
Parameters ---------- nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities of each alternative bein...
f7700:m2
def naturalize_nest_coefs(nest_coef_estimates):
<EOL>exp_term = np.exp(-<NUM_LIT:1> * nest_coef_estimates)<EOL>inf_idx = np.isinf(exp_term)<EOL>exp_term[inf_idx] = max_comp_value<EOL>nest_coefs = <NUM_LIT:1.0> / (<NUM_LIT:1.0> + exp_term)<EOL>zero_idx = (nest_coefs == <NUM_LIT:0>)<EOL>nest_coefs[zero_idx] = min_comp_value<EOL>return nest_coefs<EOL>
Parameters ---------- nest_coef_estimates : 1D ndarray. Should contain the estimated logit's (`ln[nest_coefs / (1 - nest_coefs)]`) of the true nest coefficients. All values should be ints, floats, or longs. Returns ------- nest_coefs : 1D ndarray. Will contain the 'natural' nest coefficients: `1.0 ...
f7700:m3
def calc_nested_gradient(orig_nest_coefs,<EOL>index_coefs,<EOL>design,<EOL>choice_vec,<EOL>rows_to_obs,<EOL>rows_to_nests,<EOL>ridge=None,<EOL>weights=None,<EOL>use_jacobian=True,<EOL>*args,<EOL>**kwargs):
<EOL>if weights is None:<EOL><INDENT>weights = np.ones(design.shape[<NUM_LIT:0>])<EOL><DEDENT>weights_per_obs = np.max(rows_to_obs.toarray() * weights[:, None], axis=<NUM_LIT:0>)<EOL>nest_coefs = naturalize_nest_coefs(orig_nest_coefs)<EOL>vector_dict = prep_vectors_for_gradient(nest_coefs,<EOL>index_coefs,<EOL>design,<...
Parameters ---------- orig_nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities of each alternative...
f7700:m4
def calc_bhhh_hessian_approximation(orig_nest_coefs,<EOL>index_coefs,<EOL>design,<EOL>choice_vec,<EOL>rows_to_obs,<EOL>rows_to_nests,<EOL>ridge=None,<EOL>weights=None,<EOL>use_jacobian=True,<EOL>*args,<EOL>**kwargs):
<EOL>if weights is None:<EOL><INDENT>weights = np.ones(design.shape[<NUM_LIT:0>])<EOL><DEDENT>weights_per_obs = np.max(rows_to_obs.toarray() * weights[:, None], axis=<NUM_LIT:0>)<EOL>nest_coefs = naturalize_nest_coefs(orig_nest_coefs)<EOL>vector_dict = prep_vectors_for_gradient(nest_coefs,<EOL>index_coefs,<EOL>design,<...
Parameters ---------- orig_nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities of each alternative...
f7700:m5
def calc_individual_chi_squares(residuals,<EOL>long_probabilities,<EOL>rows_to_obs):
chi_squared_terms = np.square(residuals) / long_probabilities<EOL>return rows_to_obs.T.dot(chi_squared_terms)<EOL>
Calculates individual chi-squared values for each choice situation in the dataset. Parameters ---------- residuals : 1D ndarray. The choice vector minus the predicted probability of each alternative for each observation. long_probabilities : 1D ndarray. The probability of each alternative being chosen in e...
f7701:m1
def calc_rho_and_rho_bar_squared(final_log_likelihood,<EOL>null_log_likelihood,<EOL>num_est_parameters):
rho_squared = <NUM_LIT:1.0> - final_log_likelihood / null_log_likelihood<EOL>rho_bar_squared = <NUM_LIT:1.0> - ((final_log_likelihood - num_est_parameters) /<EOL>null_log_likelihood)<EOL>return rho_squared, rho_bar_squared<EOL>
Calculates McFadden's rho-squared and rho-bar squared for the given model. Parameters ---------- final_log_likelihood : float. The final log-likelihood of the model whose rho-squared and rho-bar squared are being calculated for. null_log_likelihood : float. The log-likelihood of the model in question, when...
f7701:m2
def calc_and_store_post_estimation_results(results_dict,<EOL>estimator):
<EOL>final_log_likelihood = -<NUM_LIT:1> * results_dict["<STR_LIT>"]<EOL>results_dict["<STR_LIT>"] = final_log_likelihood<EOL>final_params = results_dict["<STR_LIT:x>"]<EOL>split_res = estimator.convenience_split_params(final_params,<EOL>return_all_types=True)<EOL>results_dict["<STR_LIT>"] = split_res[<NUM_LIT:0>]<EOL>...
Calculates and stores post-estimation results that require the use of the systematic utility transformation functions or the various derivative functions. Note that this function is only valid for logit-type models. Parameters ---------- results_dict : dict. This dictionary should be the dictionary returned from ...
f7701:m3
def estimate(init_values,<EOL>estimator,<EOL>method,<EOL>loss_tol,<EOL>gradient_tol,<EOL>maxiter,<EOL>print_results,<EOL>use_hessian=True,<EOL>just_point=False,<EOL>**kwargs):
if not just_point:<EOL><INDENT>log_likelihood_at_zero =estimator.convenience_calc_log_likelihood(estimator.zero_vector)<EOL>initial_log_likelihood =estimator.convenience_calc_log_likelihood(init_values)<EOL>if print_results:<EOL><INDENT>null_msg = "<STR_LIT>"<EOL>print(null_msg.format(log_likelihood_at_zero))<EOL>init_...
Estimate the given choice model that is defined by `estimator`. Parameters ---------- init_vals : 1D ndarray. Should contain the initial values to start the optimization process with. estimator : an instance of the EstimationObj class. method : str, optional. Should be a valid string for scipy.optimize.min...
f7701:m4
def convenience_split_params(self, params, return_all_types=False):
return self.split_params(params,<EOL>self.rows_to_alts,<EOL>self.design,<EOL>return_all_types=return_all_types)<EOL>
Splits parameter vector into shape, intercept, and index parameters. Parameters ---------- params : 1D ndarray. The array of parameters being estimated or used in calculations. return_all_types : bool, optional. Determines whether or not a tuple of 4 elements will be returned (with one element for the nest...
f7701:c0:m1
def convenience_calc_probs(self, params):
msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL>
Calculates the probabilities of the chosen alternative, and the long format probabilities for this model and dataset.
f7701:c0:m2
def convenience_calc_log_likelihood(self, params):
msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL>
Calculates the log-likelihood for this model and dataset.
f7701:c0:m3
def convenience_calc_gradient(self, params):
msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL>
Calculates the gradient of the log-likelihood for this model / dataset.
f7701:c0:m4
def convenience_calc_hessian(self, params):
msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL>
Calculates the hessian of the log-likelihood for this model / dataset.
f7701:c0:m5
def convenience_calc_fisher_approx(self, params):
msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL>
Calculates the BHHH approximation of the Fisher Information Matrix for this model / dataset.
f7701:c0:m6
def calc_neg_log_likelihood_and_neg_gradient(self, params):
neg_log_likelihood = -<NUM_LIT:1> * self.convenience_calc_log_likelihood(params)<EOL>neg_gradient = -<NUM_LIT:1> * self.convenience_calc_gradient(params)<EOL>if self.constrained_pos is not None:<EOL><INDENT>neg_gradient[self.constrained_pos] = <NUM_LIT:0><EOL><DEDENT>return neg_log_likelihood, neg_gradient<EOL>
Calculates and returns the negative of the log-likelihood and the negative of the gradient. This function is used as the objective function in scipy.optimize.minimize.
f7701:c0:m7
def calc_neg_hessian(self, params):
return -<NUM_LIT:1> * self.convenience_calc_hessian(params)<EOL>
Calculate and return the negative of the hessian for this model and dataset.
f7701:c0:m8
def convenience_calc_probs(self, params):
shapes, intercepts, betas = self.convenience_split_params(params)<EOL>prob_args = [betas,<EOL>self.design,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.utility_transform]<EOL>prob_kwargs = {"<STR_LIT>": intercepts,<EOL>"<STR_LIT>": shapes,<EOL>"<STR_LIT>": self.chosen_row_to_obs,<EOL>"<...
Calculates the probabilities of the chosen alternative, and the long format probabilities for this model and dataset.
f7701:c1:m1
def convenience_calc_log_likelihood(self, params):
shapes, intercepts, betas = self.convenience_split_params(params)<EOL>args = [betas,<EOL>self.design,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.choice_vector,<EOL>self.utility_transform]<EOL>kwargs = {"<STR_LIT>": intercepts,<EOL>"<STR_LIT>": shapes,<EOL>"<STR_LIT>": self.ridge,<EOL>...
Calculates the log-likelihood for this model and dataset.
f7701:c1:m2
def convenience_calc_gradient(self, params):
shapes, intercepts, betas = self.convenience_split_params(params)<EOL>args = [betas,<EOL>self.design,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.choice_vector,<EOL>self.utility_transform,<EOL>self.calc_dh_d_shape,<EOL>self.calc_dh_dv,<EOL>self.calc_dh_d_alpha,<EOL>intercepts,<EOL>shap...
Calculates the gradient of the log-likelihood for this model / dataset.
f7701:c1:m3
def convenience_calc_hessian(self, params):
shapes, intercepts, betas = self.convenience_split_params(params)<EOL>args = [betas,<EOL>self.design,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.utility_transform,<EOL>self.calc_dh_d_shape,<EOL>self.calc_dh_dv,<EOL>self.calc_dh_d_alpha,<EOL>self.block_matrix_idxs,<EOL>intercepts,<EOL>...
Calculates the hessian of the log-likelihood for this model / dataset.
f7701:c1:m4
def convenience_calc_fisher_approx(self, params):
shapes, intercepts, betas = self.convenience_split_params(params)<EOL>args = [betas,<EOL>self.design,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.choice_vector,<EOL>self.utility_transform,<EOL>self.calc_dh_d_shape,<EOL>self.calc_dh_dv,<EOL>self.calc_dh_d_alpha,<EOL>intercepts,<EOL>shap...
Calculates the BHHH approximation of the Fisher Information Matrix for this model / dataset.
f7701:c1:m5
def check_conf_percentage_validity(conf_percentage):
msg = "<STR_LIT>"<EOL>condition_1 = isinstance(conf_percentage, Number)<EOL>if not condition_1:<EOL><INDENT>raise ValueError(msg)<EOL><DEDENT>else:<EOL><INDENT>condition_2 = <NUM_LIT:0> < conf_percentage < <NUM_LIT:100><EOL>if not condition_2:<EOL><INDENT>raise ValueError(msg)<EOL><DEDENT><DEDENT>return None<EOL>
Ensures that `conf_percentage` is in (0, 100). Raises a helpful ValueError if otherwise.
f7702:m0
def ensure_samples_is_ndim_ndarray(samples, name='<STR_LIT>', ndim=<NUM_LIT:2>):
assert isinstance(ndim, int)<EOL>assert isinstance(name, str)<EOL>if not isinstance(samples, np.ndarray) or not (samples.ndim == ndim):<EOL><INDENT>sample_name = name + "<STR_LIT>"<EOL>msg = "<STR_LIT>".format(sample_name, ndim)<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL>
Ensures that `samples` is an `ndim` numpy array. Raises a helpful ValueError if otherwise.
f7702:m1
def get_alpha_from_conf_percentage(conf_percentage):
return <NUM_LIT> - conf_percentage<EOL>
Calculates `100 - conf_percentage`, which is useful for calculating alpha levels.
f7702:m2
def combine_conf_endpoints(lower_array, upper_array):
return np.concatenate([lower_array[None, :], upper_array[None, :]], axis=<NUM_LIT:0>)<EOL>
Concatenates upper and lower endpoint arrays for a given confidence level.
f7702:m3
def ensure_model_obj_has_mapping_constructor(model_obj):
if not hasattr(model_obj, "<STR_LIT>"):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL>
Ensure that `model_obj` has a 'get_mappings_for_fit' method. Raises a helpful ValueError if otherwise.
f7703:m0
def ensure_rows_to_obs_validity(rows_to_obs):
if rows_to_obs is not None and not isspmatrix_csr(rows_to_obs):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL>
Ensure that `rows_to_obs` is None or a 2D scipy sparse CSR matrix. Raises a helpful ValueError if otherwise.
f7703:m1
def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights):
if not isinstance(wide_weights, np.ndarray):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>ndim = wide_weights.ndim<EOL>if not <NUM_LIT:0> < ndim < <NUM_LIT:3>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL>
Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful ValueError if otherwise.
f7703:m2
def check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs):
<EOL>ensure_model_obj_has_mapping_constructor(model_obj)<EOL>ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights)<EOL>ensure_rows_to_obs_validity(rows_to_obs)<EOL>return None<EOL>
Ensures the args to `create_long_form_weights` have expected properties.
f7703:m3
def create_long_form_weights(model_obj, wide_weights, rows_to_obs=None):
<EOL>check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs)<EOL>if rows_to_obs is None:<EOL><INDENT>rows_to_obs = model_obj.get_mappings_for_fit()['<STR_LIT>']<EOL><DEDENT>wide_weights_2d =wide_weights if wide_weights.ndim == <NUM_LIT:2> else wide_weights[:, None]<EOL>long_weights = rows_to_obs.dot(wide...
Converts an array of weights with one element per observation (wide-format) to an array of weights with one element per observation per available alternative (long-format). Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are ...
f7703:m4
def calc_finite_diff_terms_for_abc(model_obj,<EOL>mle_params,<EOL>init_vals,<EOL>epsilon,<EOL>**fit_kwargs):
<EOL>num_obs = model_obj.data[model_obj.obs_id_col].unique().size<EOL>init_weights_wide = np.ones(num_obs, dtype=float) / num_obs<EOL>init_wide_weights_plus = (<NUM_LIT:1> - epsilon) * init_weights_wide<EOL>init_wide_weights_minus = (<NUM_LIT:1> + epsilon) * init_weights_wide<EOL>term_plus = np.empty((num_obs, init_val...
Calculates the terms needed for the finite difference approximations of the empirical influence and second order empirical influence functions. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap...
f7703:m5
def calc_empirical_influence_abc(term_plus,<EOL>term_minus,<EOL>epsilon):
<EOL>denominator = <NUM_LIT:2> * epsilon<EOL>empirical_influence = np.zeros(term_plus.shape)<EOL>diff_idx = ~np.isclose(term_plus, term_minus, atol=<NUM_LIT>, rtol=<NUM_LIT:0>)<EOL>if diff_idx.any():<EOL><INDENT>empirical_influence[diff_idx] =(term_plus[diff_idx] - term_minus[diff_idx]) / denominator<EOL><DEDENT>return...
Calculates the finite difference, midpoint / slope approximation to the empirical influence array needed to compute the approximate boostrap confidence (ABC) intervals. Parameters ---------- term_plus : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the param...
f7703:m6
def calc_2nd_order_influence_abc(mle_params,<EOL>term_plus,<EOL>term_minus,<EOL>epsilon):
<EOL>denominator = epsilon**<NUM_LIT:2><EOL>term_2 = np.broadcast_to(<NUM_LIT:2> * mle_params, term_plus.shape)<EOL>second_order_influence = np.zeros(term_plus.shape, dtype=float)<EOL>diff_idx = ~np.isclose(term_plus + term_minus, term_2, atol=<NUM_LIT>, rtol=<NUM_LIT:0>)<EOL>if diff_idx.any():<EOL><INDENT>second_order...
Calculates either a 'positive' finite difference approximation or an approximation of a 'positive' finite difference approximation to the the 2nd order empirical influence array needed to compute the approximate boostrap confidence (ABC) intervals. See the 'Notes' section for more information on the ambiguous function ...
f7703:m7
def calc_influence_arrays_for_abc(model_obj,<EOL>mle_est,<EOL>init_values,<EOL>epsilon,<EOL>**fit_kwargs):
<EOL>term_plus, term_minus = calc_finite_diff_terms_for_abc(model_obj,<EOL>mle_est,<EOL>init_values,<EOL>epsilon,<EOL>**fit_kwargs)<EOL>empirical_influence =calc_empirical_influence_abc(term_plus, term_minus, epsilon)<EOL>second_order_influence =calc_2nd_order_influence_abc(mle_est, term_plus, term_minus, epsilon)<EOL>...
Calculates the empirical influence array and the 2nd order empirical influence array needed to compute the approximate boostrap confidence (ABC) intervals. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing t...
f7703:m8
def calc_std_error_abc(empirical_influence):
num_obs = empirical_influence.shape[<NUM_LIT:0>]<EOL>std_error = ((empirical_influence**<NUM_LIT:2>).sum(axis=<NUM_LIT:0>))**<NUM_LIT:0.5> / num_obs<EOL>return std_error<EOL>
Calculates the standard error of the MLE estimates for use in calculating the approximate bootstrap confidence (ABC) intervals. Parameters ---------- empirical_influence : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. El...
f7703:m9
def calc_acceleration_abc(empirical_influence):
influence_cubed = empirical_influence**<NUM_LIT:3><EOL>influence_squared = empirical_influence**<NUM_LIT:2><EOL>numerator = influence_cubed.sum(axis=<NUM_LIT:0>)<EOL>denominator = <NUM_LIT:6> * (influence_squared.sum(axis=<NUM_LIT:0>))**<NUM_LIT><EOL>acceleration = numerator / denominator<EOL>return acceleration<EOL>
Calculates the acceleration constant for the approximate bootstrap confidence (ABC) intervals. Parameters ---------- empirical_influence : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimated. Elements should denote the empi...
f7703:m10
def calc_bias_abc(second_order_influence):
num_obs = second_order_influence.shape[<NUM_LIT:0>]<EOL>constant = <NUM_LIT> * num_obs**<NUM_LIT:2><EOL>bias = second_order_influence.sum(axis=<NUM_LIT:0>) / constant<EOL>return bias<EOL>
Calculates the approximate bias of the MLE estimates for use in calculating the approximate bootstrap confidence (ABC) intervals. Parameters ---------- second_order_influence : 2D ndarray. Should have one row for each observation. Should have one column for each parameter in the parameter vector being estimate...
f7703:m11
def calc_quadratic_coef_abc(model_object,<EOL>mle_params,<EOL>init_vals,<EOL>empirical_influence,<EOL>std_error,<EOL>epsilon,<EOL>**fit_kwargs):
<EOL>num_obs = float(empirical_influence.shape[<NUM_LIT:0>])<EOL>standardized_influence =empirical_influence / (num_obs**<NUM_LIT:2> * std_error[None, :])<EOL>init_weights_wide = (np.ones(int(num_obs), dtype=float) / num_obs)[:, None]<EOL>term_1_wide_weights =(<NUM_LIT:1> - epsilon) * init_weights_wide + epsilon * stan...
Calculates the quadratic coefficient needed to compute the approximate boostrap confidence (ABC) intervals. Parameters ---------- model_object : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_pa...
f7703:m12
def efron_quadratic_coef_abc(model_object,<EOL>mle_params,<EOL>init_vals,<EOL>empirical_influence,<EOL>std_error,<EOL>epsilon,<EOL>**fit_kwargs):
<EOL>num_obs = float(empirical_influence.shape[<NUM_LIT:0>])<EOL>standardized_influence =empirical_influence / (num_obs**<NUM_LIT:2> * std_error[None, :])<EOL>init_weights_wide = (np.ones(int(num_obs), dtype=float) / num_obs)[:, None]<EOL>term_1_wide_weights = init_weights_wide + epsilon * standardized_influence<EOL>te...
Calculates the quadratic coefficient needed to compute the approximate boostrap confidence (ABC) intervals. Parameters ---------- model_object : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_pa...
f7703:m13
def calc_total_curvature_abc(bias, std_error, quadratic_coef):
total_curvature = (bias / std_error) - quadratic_coef<EOL>return total_curvature<EOL>
Calculate the total curvature of the level surface of the weight vector, where the set of weights in the surface are those where the weighted MLE equals the original (i.e. the equal-weighted) MLE. Parameters ---------- bias : 1D ndarray. Contains the approximate bias of the MLE estimates for use in the ABC con...
f7703:m14
def calc_bias_correction_abc(acceleration, total_curvature):
inner_arg = <NUM_LIT:2> * norm.cdf(acceleration) * norm.cdf(-<NUM_LIT:1> * total_curvature)<EOL>bias_correction = norm.ppf(inner_arg)<EOL>return bias_correction<EOL>
Calculate the bias correction constant for the approximate bootstrap confidence (ABC) intervals. Parameters ---------- acceleration : 1D ndarray of scalars. Should contain the ABC intervals' estimated acceleration constants. total_curvature : 1D ndarray of scalars. Should denote the ABC intervals' computred to...
f7703:m15
def calc_endpoint_from_percentile_abc(model_obj,<EOL>init_vals,<EOL>percentile,<EOL>bias_correction,<EOL>acceleration,<EOL>std_error,<EOL>empirical_influence,<EOL>**fit_kwargs):
<EOL>bias_corrected_z = bias_correction + norm.ppf(percentile * <NUM_LIT>)<EOL>lam = bias_corrected_z / (<NUM_LIT:1> - acceleration * bias_corrected_z)**<NUM_LIT:2><EOL>multiplier = lam / std_error<EOL>num_obs = empirical_influence.shape[<NUM_LIT:0>]<EOL>init_weights_wide = np.ones(num_obs, dtype=float)[:, None] / num_...
Calculates the endpoint of the 1-tailed, (percentile)% confidence interval. Note this interval spans from negative infinity to the calculated endpoint. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the b...
f7703:m16
def efron_endpoint_from_percentile_abc(model_obj,<EOL>init_vals,<EOL>percentile,<EOL>bias_correction,<EOL>acceleration,<EOL>std_error,<EOL>empirical_influence,<EOL>**fit_kwargs):
<EOL>bias_corrected_z = bias_correction + norm.ppf(percentile * <NUM_LIT>)<EOL>num_obs = empirical_influence.shape[<NUM_LIT:0>]<EOL>lam = bias_corrected_z / (<NUM_LIT:1> - acceleration * bias_corrected_z)**<NUM_LIT:2><EOL>multiplier = lam / (std_error * num_obs**<NUM_LIT:2>)<EOL>init_weights_wide = np.ones(num_obs, dty...
Calculates the endpoint of the 1-tailed, (percentile)% confidence interval. Note this interval spans from negative infinity to the calculated endpoint. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the b...
f7703:m17
def efron_endpoints_for_abc_confidence_interval(conf_percentage,<EOL>model_obj,<EOL>init_vals,<EOL>bias_correction,<EOL>acceleration,<EOL>std_error,<EOL>empirical_influence,<EOL>**fit_kwargs):
<EOL>alpha_percent = get_alpha_from_conf_percentage(conf_percentage)<EOL>lower_percentile = alpha_percent / <NUM_LIT><EOL>upper_percentile = <NUM_LIT:100> - lower_percentile<EOL>lower_endpoint = efron_endpoint_from_percentile_abc(model_obj,<EOL>init_vals,<EOL>lower_percentile,<EOL>bias_correction,<EOL>acceleration,<EOL...
Calculates the endpoints of the equal-tailed, `conf_percentage`% approximate bootstrap confidence (ABC) interval. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`...
f7703:m18
def calc_abc_interval(model_obj,<EOL>mle_params,<EOL>init_vals,<EOL>conf_percentage,<EOL>epsilon=<NUM_LIT>,<EOL>**fit_kwargs):
<EOL>check_conf_percentage_validity(conf_percentage)<EOL>empirical_influence, second_order_influence =calc_influence_arrays_for_abc(model_obj,<EOL>mle_params,<EOL>init_vals,<EOL>epsilon,<EOL>**fit_kwargs)<EOL>acceleration = calc_acceleration_abc(empirical_influence)<EOL>std_error = calc_std_error_abc(empirical_influenc...
Calculate 'approximate bootstrap confidence' intervals. Parameters ---------- model_obj : an instance or sublcass of the MNDC class. Should be the model object that corresponds to the model we are constructing the bootstrap confidence intervals for. mle_params : 1D ndarray. Should contain the desired model...
f7703:m19
def extract_default_init_vals(orig_model_obj, mnl_point_series, num_params):
<EOL>init_vals = np.zeros(num_params, dtype=float)<EOL>no_outside_intercepts = orig_model_obj.intercept_names is None<EOL>if no_outside_intercepts:<EOL><INDENT>init_index_coefs = mnl_point_series.values<EOL>init_intercepts = None<EOL><DEDENT>else:<EOL><INDENT>init_index_coefs =mnl_point_series.loc[orig_model_obj.ind_va...
Get the default initial values for the desired model type, based on the point estimate of the MNL model that is 'closest' to the desired model. Parameters ---------- orig_model_obj : an instance or sublcass of the MNDC class. Should correspond to the actual model that we want to bootstrap. mnl_point_series : panda...
f7704:m0
def get_model_abbrev(model_obj):
<EOL>model_type = model_obj.model_type<EOL>for key in model_type_to_display_name:<EOL><INDENT>if model_type_to_display_name[key] == model_type:<EOL><INDENT>return key<EOL><DEDENT><DEDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL>
Extract the string used to specify the model type of this model object in `pylogit.create_chohice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- str. The internal abbreviation used for the particular type of MNDC_Model.
f7704:m1
def get_model_creation_kwargs(model_obj):
<EOL>model_abbrev = get_model_abbrev(model_obj)<EOL>model_kwargs = {"<STR_LIT>": model_abbrev,<EOL>"<STR_LIT>": model_obj.name_spec,<EOL>"<STR_LIT>": model_obj.intercept_names,<EOL>"<STR_LIT>": model_obj.intercept_ref_position,<EOL>"<STR_LIT>": model_obj.shape_names,<EOL>"<STR_LIT>": model_obj.shape_ref_position,<EOL>"...
Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the keyword arguments and the required values that are needed to initialize a replica ...
f7704:m2
def get_mnl_point_est(orig_model_obj,<EOL>new_df,<EOL>boot_id_col,<EOL>num_params,<EOL>mnl_spec,<EOL>mnl_names,<EOL>mnl_init_vals,<EOL>mnl_fit_kwargs):
<EOL>if orig_model_obj.model_type == model_type_to_display_name["<STR_LIT>"]:<EOL><INDENT>mnl_spec = orig_model_obj.specification<EOL>mnl_names = orig_model_obj.name_spec<EOL>if mnl_init_vals is None:<EOL><INDENT>mnl_init_vals = np.zeros(num_params)<EOL><DEDENT>if mnl_fit_kwargs is None:<EOL><INDENT>mnl_fit_kwargs = {}...
Calculates the MLE for the desired MNL model. Parameters ---------- orig_model_obj : An MNDC_Model instance. The object corresponding to the desired model being bootstrapped. new_df : pandas DataFrame. The pandas dataframe containing the data to be used to estimate the MLE of the MNL model for the current ...
f7704:m3
def retrieve_point_est(orig_model_obj,<EOL>new_df,<EOL>new_id_col,<EOL>num_params,<EOL>mnl_spec,<EOL>mnl_names,<EOL>mnl_init_vals,<EOL>mnl_fit_kwargs,<EOL>extract_init_vals=None,<EOL>**fit_kwargs):
<EOL>mnl_point, mnl_obj = get_mnl_point_est(orig_model_obj,<EOL>new_df,<EOL>new_id_col,<EOL>num_params,<EOL>mnl_spec,<EOL>mnl_names,<EOL>mnl_init_vals,<EOL>mnl_fit_kwargs)<EOL>mnl_point_series = pd.Series(mnl_point["<STR_LIT:x>"], index=mnl_obj.ind_var_names)<EOL>if orig_model_obj.model_type == model_type_to_display_na...
Calculates the MLE for the desired MNL model. Parameters ---------- orig_model_obj : An MNDC_Model instance. The object corresponding to the desired model being bootstrapped. new_df : pandas DataFrame. The pandas dataframe containing the data to be used to estimate the MLE of the MNL model for the current ...
f7704:m4
def relate_obs_ids_to_chosen_alts(obs_id_array,<EOL>alt_id_array,<EOL>choice_array):
<EOL>chosen_alts_to_obs_ids = {}<EOL>for alt_id in np.sort(np.unique(alt_id_array)):<EOL><INDENT>selection_condition =np.where((alt_id_array == alt_id) & (choice_array == <NUM_LIT:1>))<EOL>chosen_alts_to_obs_ids[alt_id] =np.sort(np.unique(obs_id_array[selection_condition]))<EOL><DEDENT>return chosen_alts_to_obs_ids<EOL...
Creates a dictionary that relates each unique alternative id to the set of observations ids that chose the given alternative. Parameters ---------- obs_id_array : 1D ndarray of ints. Should be a long-format array of observation ids. Each element should correspond to the unique id of the unit of observation tha...
f7705:m0