signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def calc_log_likes_for_replicates(self,<EOL>replicates='<STR_LIT>',<EOL>num_draws=None,<EOL>seed=None): | <EOL>ensure_replicates_kwarg_validity(replicates)<EOL>replicate_vec = getattr(self, replicates + "<STR_LIT>").values<EOL>choice_col = self.model_obj.choice_col<EOL>current_model_type = self.model_obj.model_type<EOL>non_2d_predictions =[model_type_to_display_name["<STR_LIT>"],<EOL>model_type_to_display_name["<STR_LIT>"]... | Calculate the log-likelihood value of one's replicates, given one's
dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
num_draws : int greater than zero or None, optional.
Denotes the number of random ... | f7686:c0:m3 |
def calc_gradient_norm_for_replicates(self,<EOL>replicates='<STR_LIT>',<EOL>ridge=None,<EOL>constrained_pos=None,<EOL>weights=None): | <EOL>ensure_replicates_kwarg_validity(replicates)<EOL>estimation_obj =create_estimation_obj(self.model_obj,<EOL>self.mle_params.values,<EOL>ridge=ridge,<EOL>constrained_pos=constrained_pos,<EOL>weights=weights)<EOL>if hasattr(estimation_obj, "<STR_LIT>"):<EOL><INDENT>estimation_obj.set_derivatives()<EOL><DEDENT>replica... | Calculate the Euclidean-norm of the gradient of one's replicates, given
one's dataset.
Parameters
----------
replicates : str in {'bootstrap', 'jackknife'}.
Denotes which set of replicates should have their log-likelihoods
calculated.
ridge : float or None, optional.
Denotes the ridge penalty used when est... | f7686:c0:m4 |
def calc_percentile_interval(self, conf_percentage): | <EOL>alpha = bc.get_alpha_from_conf_percentage(conf_percentage)<EOL>single_column_names =['<STR_LIT>'.format(alpha / <NUM_LIT>),<EOL>'<STR_LIT>'.format(<NUM_LIT:100> - alpha / <NUM_LIT>)]<EOL>conf_intervals =bc.calc_percentile_interval(self.bootstrap_replicates.values,<EOL>conf_percentage)<EOL>self.percentile_interval ... | Calculates percentile bootstrap confidence intervals for one's model.
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`.
Returns
-------
None. Will store the perc... | f7686:c0:m5 |
def calc_bca_interval(self, conf_percentage): | <EOL>alpha = bc.get_alpha_from_conf_percentage(conf_percentage)<EOL>single_column_names =['<STR_LIT>'.format(alpha / <NUM_LIT>),<EOL>'<STR_LIT>'.format(<NUM_LIT:100> - alpha / <NUM_LIT>)]<EOL>args = [self.bootstrap_replicates.values,<EOL>self.jackknife_replicates.values,<EOL>self.mle_params.values,<EOL>conf_percentage]... | Calculates Bias-Corrected and Accelerated (BCa) Bootstrap Confidence
Intervals for one's model.
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`.
Returns
-------... | f7686:c0:m6 |
def calc_abc_interval(self,<EOL>conf_percentage,<EOL>init_vals,<EOL>epsilon=<NUM_LIT>,<EOL>**fit_kwargs): | print("<STR_LIT>")<EOL>print(time.strftime("<STR_LIT>"))<EOL>sys.stdout.flush()<EOL>alpha = bc.get_alpha_from_conf_percentage(conf_percentage)<EOL>single_column_names =['<STR_LIT>'.format(alpha / <NUM_LIT>),<EOL>'<STR_LIT>'.format(<NUM_LIT:100> - alpha / <NUM_LIT>)]<EOL>conf_intervals =abc.calc_abc_interval(self.model_... | Calculates Approximate Bootstrap Confidence Intervals for one's model.
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`.
init_vals : 1D ndarray.
The initial v... | f7686:c0:m7 |
def calc_conf_intervals(self,<EOL>conf_percentage,<EOL>interval_type='<STR_LIT:all>',<EOL>init_vals=None,<EOL>epsilon=abc.EPSILON,<EOL>**fit_kwargs): | if interval_type == '<STR_LIT>':<EOL><INDENT>self.calc_percentile_interval(conf_percentage)<EOL><DEDENT>elif interval_type == '<STR_LIT>':<EOL><INDENT>self.calc_bca_interval(conf_percentage)<EOL><DEDENT>elif interval_type == '<STR_LIT:abc>':<EOL><INDENT>self.calc_abc_interval(conf_percentage,<EOL>init_vals,<EOL>epsilon... | Calculates percentile, bias-corrected and accelerated, and approximate
bootstrap confidence intervals.
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`.
interval_... | f7686:c0:m8 |
def split_param_vec(beta, return_all_types=False, *args, **kwargs): | if return_all_types:<EOL><INDENT>return None, None, None, beta<EOL><DEDENT>else:<EOL><INDENT>return None, None, beta<EOL><DEDENT> | Parameters
----------
beta : 1D numpy array.
All elements should by ints, floats, or longs. Should have 1 element
for each utility coefficient being estimated (i.e. num_features).
return_all_types : bool, optional.
Determines whether or not a tuple of 4 elements will be returned (with
one element for th... | f7687:m0 |
def mnl_utility_transform(sys_utility_array, *args, **kwargs): | <EOL>if len(sys_utility_array.shape) == <NUM_LIT:1>:<EOL><INDENT>systematic_utilities = sys_utility_array[:, np.newaxis]<EOL><DEDENT>else:<EOL><INDENT>systematic_utilities = sys_utility_array<EOL><DEDENT>return systematic_utilities<EOL> | Parameters
----------
sys_utility_array : ndarray.
Should have 1D or 2D. Should have been created by the dot product of a
design matrix and an array of index coefficients.
Returns
-------
systematic_utilities : 2D ndarray.
The input systematic utilities. If `sys_utility_array` is 2D, then
`... | f7687:m1 |
def check_length_of_init_values(design_3d, init_values): | if init_values.shape[<NUM_LIT:0>] != design_3d.shape[<NUM_LIT:2>]:<EOL><INDENT>msg_1 = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>".format(design_3d.shape[<NUM_LIT:2>])<EOL>raise ValueError(msg_1 + msg_2)<EOL><DEDENT>return None<EOL> | Ensures that the initial values are of the correct length, given the design
matrix that they will be dot-producted with. Raises a ValueError if that is
not the case, and provides a useful error message to users.
Parameters
----------
init_values : 1D ndarray.
1D numpy array of the initial values to start the optim... | f7687:m2 |
def add_mixl_specific_results_to_estimation_res(estimator, results_dict): | <EOL>prob_res = mlc.calc_choice_sequence_probs(results_dict["<STR_LIT>"],<EOL>estimator.choice_vector,<EOL>estimator.rows_to_mixers,<EOL>return_type='<STR_LIT:all>')<EOL>results_dict["<STR_LIT>"] = prob_res[<NUM_LIT:0>]<EOL>results_dict["<STR_LIT>"] = prob_res[<NUM_LIT:1>]<EOL>return results_dict<EOL> | Stores particular items in the results dictionary that are unique to mixed
logit-type models. In particular, this function calculates and adds
`sequence_probs` and `expanded_sequence_probs` to the results dictionary.
The `constrained_pos` object is also stored to the results_dict.
Parameters
----------
estimator : an ... | f7687:m3 |
def convenience_split_params(self, params, return_all_types=False): | return self.split_params(params,<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... | f7687:c0:m1 |
def check_length_of_initial_values(self, init_values): | return check_length_of_init_values(self.design_3d, init_values)<EOL> | Ensures that the initial values are of the correct length. | f7687:c0:m2 |
def convenience_calc_probs(self, params): | shapes, intercepts, betas = self.convenience_split_params(params)<EOL>prob_args = (betas,<EOL>self.design_3d,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.utility_transform)<EOL>prob_kwargs = {"<STR_LIT>": self.chosen_row_to_obs,<EOL>"<STR_LIT>": True}<EOL>probability_results = general_... | Calculates the probabilities of the chosen alternative, and the long
format probabilities for this model and dataset. | f7687:c0:m3 |
def convenience_calc_log_likelihood(self, params): | shapes, intercepts, betas = self.convenience_split_params(params)<EOL>args = [betas,<EOL>self.design_3d,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.rows_to_mixers,<EOL>self.choice_vector,<EOL>self.utility_transform]<EOL>kwargs = {"<STR_LIT>": self.ridge, "<STR_LIT>": self.weights}<EOL... | Calculates the log-likelihood for this model and dataset. | f7687:c0:m4 |
def convenience_calc_gradient(self, params): | shapes, intercepts, betas = self.convenience_split_params(params)<EOL>args = [betas,<EOL>self.design_3d,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.rows_to_mixers,<EOL>self.choice_vector,<EOL>self.utility_transform]<EOL>return general_gradient(*args, ridge=self.ridge, weights=self.wei... | Calculates the gradient of the log-likelihood for this model / dataset. | f7687:c0:m5 |
def convenience_calc_hessian(self, params): | shapes, intercepts, betas = self.convenience_split_params(params)<EOL>args = [betas,<EOL>self.design_3d,<EOL>self.alt_id_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_alts,<EOL>self.rows_to_mixers,<EOL>self.choice_vector,<EOL>self.utility_transform]<EOL>approx_hess =general_bhhh(*args, ridge=self.ridge, weights=self.w... | Calculates the hessian of the log-likelihood for this model / dataset.
Note that this function name is INCORRECT with regard to the actual
actions performed. The Mixed Logit model uses the BHHH approximation
to the Fisher Information Matrix in place of the actual hessian. | f7687:c0:m6 |
def convenience_calc_fisher_approx(self, params): | shapes, intercepts, betas = self.convenience_split_params(params)<EOL>placeholder_bhhh = np.diag(-<NUM_LIT:1> * np.ones(betas.shape[<NUM_LIT:0>]))<EOL>return placeholder_bhhh<EOL> | Calculates the BHHH approximation of the Fisher Information Matrix for
this model / dataset. Note that this function name is INCORRECT with
regard to the actual actions performed. The Mixed Logit model uses a
placeholder for the BHHH approximation of the Fisher Information Matrix
because the BHHH approximation is alrea... | f7687:c0:m7 |
def fit_mle(self,<EOL>init_vals,<EOL>num_draws,<EOL>seed=None,<EOL>constrained_pos=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>just_point=False,<EOL>**kwargs): | <EOL>kwargs_to_be_ignored = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>if any([x in kwargs for x in kwargs_to_be_ignored]):<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg.format(kwargs_to_be_ignored) + msg_2)<EOL><DEDENT>self.optimization_method = method<EOL>self.ridge_param = ridge<EOL... | Parameters
----------
init_vals : 1D ndarray.
Should contain the initial values to start the optimization process
with. There should be one value for each utility coefficient and
shape parameter being estimated.
num_draws : int.
Should be greater than zero. Denotes the number of draws that we
are ma... | f7687:c1:m1 |
def __filter_past_mappings(self,<EOL>past_mappings,<EOL>long_inclusion_array): | new_mappings = {}<EOL>for key in past_mappings:<EOL><INDENT>if past_mappings[key] is None:<EOL><INDENT>new_mappings[key] = None<EOL><DEDENT>else:<EOL><INDENT>mask_array = long_inclusion_array[:, None]<EOL>orig_map = past_mappings[key]<EOL>new_map = orig_map.multiply(np.tile(mask_array,<EOL>(<NUM_LIT:1>, orig_map.shape[... | Parameters
----------
past_mappings : dict.
All elements should be None or compressed sparse row matrices from
scipy.sparse. The following keys should be in past_mappings:
- "rows_to_obs",
- "rows_to_alts",
- "chosen_rows_to_obs",
- "rows_to_nests",
- "rows_to_mixers"
The values that a... | f7687:c1:m2 |
def panel_predict(self,<EOL>data,<EOL>num_draws,<EOL>return_long_probs=True,<EOL>choice_col=None,<EOL>seed=None): | <EOL>if choice_col is None and not return_long_probs:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>dataframe = get_dataframe_from_data(data)<EOL>condition_1 = "<STR_LIT>" in self.specification<EOL>condition_2 = "<STR_LIT>" not in dataframe.columns<EOL>if condition_1 and condition_2:<EOL><INDENT>d... | 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 to be predicted with this
choice model. Note long format has one row per available
alternative for each observation. If pandas dataframe, the
... | f7687:c1:m3 |
def create_estimation_obj(model_obj,<EOL>init_vals,<EOL>mappings=None,<EOL>ridge=None,<EOL>constrained_pos=None,<EOL>weights=None): | <EOL>mapping_matrices =model_obj.get_mappings_for_fit() if mappings is None else mappings<EOL>zero_vector = np.zeros(init_vals.shape[<NUM_LIT:0>])<EOL>internal_model_name = display_name_to_model_type[model_obj.model_type]<EOL>estimator_class, current_split_func =(model_type_to_resources[internal_model_name]['<STR_LIT>'... | Should return a model estimation object corresponding to the model type of
the `model_obj`.
Parameters
----------
model_obj : an instance or sublcass of the MNDC class.
init_vals : 1D ndarray.
The initial values to start the estimation process with. In the
following order, there should be one value for each ne... | f7688:m0 |
def split_param_vec(param_vec, rows_to_alts, design, return_all_types=False): | <EOL>num_shapes = rows_to_alts.shape[<NUM_LIT:1>]<EOL>num_index_coefs = design.shape[<NUM_LIT:1>]<EOL>shapes = param_vec[:num_shapes]<EOL>betas = param_vec[-<NUM_LIT:1> * num_index_coefs:]<EOL>remaining_idx = param_vec.shape[<NUM_LIT:0>] - (num_shapes + num_index_coefs)<EOL>if remaining_idx > <NUM_LIT:0>:<EOL><INDENT>i... | Parameters
----------
param_vec : 1D ndarray.
Elements should all be ints, floats, or longs. Should have as many
elements as there are parameters being estimated.
rows_to_alts : 2D scipy sparse matrix.
There should be one row per observation per available alternative and
one column per possible alternat... | f7689:m0 |
def _scobit_utility_transform(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>shape_params,<EOL>intercept_params,<EOL>intercept_ref_pos=None,<EOL>*args, **kwargs): | <EOL>if intercept_ref_pos is not None and intercept_params is not None:<EOL><INDENT>needed_idxs = range(intercept_params.shape[<NUM_LIT:0>] + <NUM_LIT:1>)<EOL>needed_idxs.remove(intercept_ref_pos)<EOL>if len(intercept_params.shape) > <NUM_LIT:1> and intercept_params.shape[<NUM_LIT:1>] > <NUM_LIT:1>:<EOL><INDENT>all_int... | 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.
... | f7689:m1 |
def _scobit_transform_deriv_v(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>shape_params,<EOL>output_array=None,<EOL>*args, **kwargs): | <EOL>curve_shapes = np.exp(shape_params)<EOL>curve_shapes[np.isposinf(curve_shapes)] = max_comp_value<EOL>long_curve_shapes = rows_to_alts.dot(curve_shapes)<EOL>exp_neg_v = np.exp(-<NUM_LIT:1> * systematic_utilities)<EOL>powered_term = np.power(<NUM_LIT:1> + exp_neg_v, long_curve_shapes)<EOL>small_powered_term = np.pow... | 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.
... | f7689:m2 |
def _scobit_transform_deriv_shape(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>shape_params,<EOL>output_array=None,<EOL>*args, **kwargs): | <EOL>curve_shapes = np.exp(shape_params)<EOL>curve_shapes[np.isposinf(curve_shapes)] = max_comp_value<EOL>long_curve_shapes = rows_to_alts.dot(curve_shapes)<EOL>exp_neg_v = np.exp(-<NUM_LIT:1> * systematic_utilities)<EOL>powered_term = np.power(<NUM_LIT:1> + exp_neg_v, long_curve_shapes)<EOL>curve_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.
... | f7689:m3 |
def _scobit_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.
... | f7689: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(_scobit_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... | f7689:m5 |
def create_calc_dh_d_shape(estimator): | dh_d_shape = estimator.rows_to_alts.copy()<EOL>calc_dh_d_shape = partial(_scobit_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... | f7689: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... | f7689: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 optimization process with. There
should be one value for each index coefficient, outside intercept
parameter, and shape parameter be... | f7689: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... | f7689:c1:m1 |
def ensure_valid_model_type(specified_type, model_type_list): | if specified_type not in model_type_list:<EOL><INDENT>msg_1 = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>".format(model_type_list)<EOL>msg_3 = "<STR_LIT>".format(specified_type)<EOL>total_msg = "<STR_LIT:\n>".join([msg_1, msg_2, msg_3])<EOL>raise ValueError(total_msg)<EOL><DEDENT>return None<EOL> | Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked.
model_type_list : list of strings.
Contains all of the model types that are acceptable k... | f7691:m0 |
def create_choice_model(data,<EOL>alt_id_col,<EOL>obs_id_col,<EOL>choice_col,<EOL>specification,<EOL>model_type,<EOL>intercept_ref_pos=None,<EOL>shape_ref_pos=None,<EOL>names=None,<EOL>intercept_names=None,<EOL>shape_names=None,<EOL>nest_spec=None,<EOL>mixing_id_col=None,<EOL>mixing_vars=None): | <EOL>ensure_valid_model_type(model_type, valid_model_types)<EOL>model_kwargs = {"<STR_LIT>": intercept_ref_pos,<EOL>"<STR_LIT>": shape_ref_pos,<EOL>"<STR_LIT>": names,<EOL>"<STR_LIT>": intercept_names,<EOL>"<STR_LIT>": shape_names,<EOL>"<STR_LIT>": nest_spec,<EOL>"<STR_LIT>": mixing_id_col,<EOL>"<STR_LIT>": mixing_vars... | Parameters
----------
data : string or pandas dataframe.
If `data` is a string, it should be an absolute or relative path to
a CSV file containing the long format data for this choice model.
Note long format has one row per available alternative for each
observation. If `data` is a pandas dataframe, `da... | f7691:m1 |
def get_dataframe_from_data(data): | if isinstance(data, str):<EOL><INDENT>if data.endswith("<STR_LIT>"):<EOL><INDENT>dataframe = pd.read_csv(data)<EOL><DEDENT>else:<EOL><INDENT>msg_1 = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg_1.format(data) + msg_2)<EOL><DEDENT><DEDENT>elif isinstance(data, pd.DataFrame):<EOL><INDENT>dataframe = data<... | 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
has one row per available alternative for each observation. If pandas
dataframe, the dataframe should be t... | f7692:m0 |
def ensure_object_is_ordered_dict(item, title): | assert isinstance(title, str)<EOL>if not isinstance(item, OrderedDict):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise TypeError(msg.format(title, type(item)))<EOL><DEDENT>return None<EOL> | Checks that the item is an OrderedDict. If not, raises ValueError. | f7692:m1 |
def ensure_object_is_string(item, title): | assert isinstance(title, str)<EOL>if not isinstance(item, str):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise TypeError(msg.format(title, type(item)))<EOL><DEDENT>return None<EOL> | Checks that the item is a string. If not, raises ValueError. | f7692:m2 |
def ensure_object_is_ndarray(item, title): | assert isinstance(title, str)<EOL>if not isinstance(item, np.ndarray):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise TypeError(msg.format(title, type(item)))<EOL><DEDENT>return None<EOL> | Ensures that a given mapping matrix is a dense numpy array. Raises a
helpful TypeError if otherwise. | f7692:m3 |
def ensure_columns_are_in_dataframe(columns,<EOL>dataframe,<EOL>col_title='<STR_LIT>',<EOL>data_title='<STR_LIT:data>'): | <EOL>assert isinstance(columns, Iterable)<EOL>assert isinstance(dataframe, pd.DataFrame)<EOL>assert isinstance(col_title, str)<EOL>assert isinstance(data_title, str)<EOL>problem_cols = [col for col in columns if col not in dataframe.columns]<EOL>if problem_cols != []:<EOL><INDENT>if col_title == '<STR_LIT>':<EOL><INDEN... | Checks whether each column in `columns` is in `dataframe`. Raises
ValueError if any of the columns are not in the dataframe.
Parameters
----------
columns : list of strings.
Each string should represent a column heading in dataframe.
dataframe : pandas DataFrame.
Dataframe containing the data for the choice mo... | f7692:m4 |
def check_argument_type(long_form, specification_dict): | if not isinstance(long_form, pd.DataFrame):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise TypeError(msg.format(type(long_form)))<EOL><DEDENT>ensure_object_is_ordered_dict(specification_dict, "<STR_LIT>")<EOL>return None<EOL> | Ensures that long_form is a pandas dataframe and that specification_dict
is an OrderedDict, raising a ValueError otherwise.
Parameters
----------
long_form : pandas dataframe.
Contains one row for each available alternative, for each observation.
specification_dict : OrderedDict.
Keys are a proper subset of th... | f7692:m5 |
def ensure_alt_id_in_long_form(alt_id_col, long_form): | if alt_id_col not in long_form.columns:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(alt_id_col))<EOL><DEDENT>return None<EOL> | Ensures alt_id_col is in long_form, and raises a ValueError if not.
Parameters
----------
alt_id_col : str.
Column name which denotes the column in `long_form` that contains the
alternative ID for each row in `long_form`.
long_form : pandas dataframe.
Contains one row for each available alternative, for ea... | f7692:m6 |
def ensure_specification_cols_are_in_dataframe(specification, dataframe): | <EOL>try:<EOL><INDENT>assert isinstance(specification, OrderedDict)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>assert isinstance(dataframe, pd.DataFrame)<EOL>problem_cols = []<EOL>dataframe_cols = dataframe.columns<EOL>for key in specification:<EOL><INDENT>if key not in data... | Checks whether each column in `specification` is in `dataframe`. Raises
ValueError if any of the columns are not in the dataframe.
Parameters
----------
specification : OrderedDict.
Keys are a proper subset of the columns in `data`. Values are either a
list or a single string, "all_diff" or "all_same". If a li... | f7692:m7 |
def check_type_and_values_of_specification_dict(specification_dict,<EOL>unique_alternatives): | for key in specification_dict:<EOL><INDENT>specification = specification_dict[key]<EOL>if isinstance(specification, str):<EOL><INDENT>if specification not in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg.format(key))<EOL><DEDENT><DEDENT>elif isinstance(specification, list):<EOL><IND... | Verifies that the values of specification_dict have the correct type, have
the correct structure, and have valid values (i.e. are actually in the set
of possible alternatives). Will raise various errors if / when appropriate.
Parameters
----------
specification_dict : OrderedDict.
Keys are a proper subset of the c... | f7692:m8 |
def check_keys_and_values_of_name_dictionary(names,<EOL>specification_dict,<EOL>num_alts): | if names.keys() != specification_dict.keys():<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>for key in names:<EOL><INDENT>specification = specification_dict[key]<EOL>name_object = names[key]<EOL>if isinstance(specification, list):<EOL><INDENT>try:<EOL><INDENT>assert isinstance(name_object, list)<E... | Check the validity of the keys and values in the names dictionary.
Parameters
----------
names : OrderedDict, optional.
Should have the same keys as `specification_dict`. For each key:
- if the corresponding value in `specification_dict` is "all_same",
then there should be a single string as the... | f7692:m9 |
def ensure_all_columns_are_used(num_vars_accounted_for,<EOL>dataframe,<EOL>data_title='<STR_LIT>'): | dataframe_vars = set(dataframe.columns.tolist())<EOL>num_dataframe_vars = len(dataframe_vars)<EOL>if num_vars_accounted_for == num_dataframe_vars:<EOL><INDENT>pass<EOL><DEDENT>elif num_vars_accounted_for < num_dataframe_vars:<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>msg_3 = "<STR_LIT>"<EOL>warnings.war... | Ensure that all of the columns from dataframe are in the list of used_cols.
Will raise a helpful UserWarning if otherwise.
Parameters
----------
num_vars_accounted_for : int.
Denotes the number of variables used in one's function.
dataframe : pandas dataframe.
Contains all of the data to be converted from one ... | f7692:m10 |
def check_dataframe_for_duplicate_records(obs_id_col, alt_id_col, df): | if df.duplicated(subset=[obs_id_col, alt_id_col]).any():<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>return None<EOL> | Checks a cross-sectional dataframe of long-format data for duplicate
observations. Duplicate observations are defined as rows with the same
observation id value and the same alternative id value.
Parameters
----------
obs_id_col : str.
Denotes the column in `df` that contains the observation ID
values for each... | f7692:m11 |
def ensure_num_chosen_alts_equals_num_obs(obs_id_col, choice_col, df): | num_obs = df[obs_id_col].unique().shape[<NUM_LIT:0>]<EOL>num_choices = df[choice_col].sum()<EOL>if num_choices < num_obs:<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg + msg_2)<EOL><DEDENT>if num_choices > num_obs:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>retu... | Checks that the total number of recorded choices equals the total number of
observations. If this is not the case, raise helpful ValueError messages.
Parameters
----------
obs_id_col : str.
Denotes the column in `df` that contains the observation ID values for
each row.
choice_col : str.
Denotes the column... | f7692:m12 |
def check_type_and_values_of_alt_name_dict(alt_name_dict, alt_id_col, df): | if not isinstance(alt_name_dict, dict):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise TypeError(msg.format(type(alt_name_dict)))<EOL><DEDENT>if not all([x in df[alt_id_col].values for x in alt_name_dict.keys()]):<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg + msg_2)<EOL><DEDENT>return None<E... | Ensures that `alt_name_dict` is a dictionary and that its keys are in the
alternative id column of `df`. Raises helpful errors if either condition
is not met.
Parameters
----------
alt_name_dict : dict.
A dictionary whose keys are the possible values in
`df[alt_id_col].unique()`. The values should be the name ... | f7692:m13 |
def ensure_ridge_is_scalar_or_none(ridge): | if (ridge is not None) and not isinstance(ridge, Number):<EOL><INDENT>msg_1 = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>".format(type(ridge))<EOL>raise TypeError(msg_1 + msg_2)<EOL><DEDENT>return None<EOL> | Ensures that `ridge` is either None or a scalar value. Raises a helpful
TypeError otherwise.
Parameters
----------
ridge : int, float, long, or None.
Scalar value or None, determining the L2-ridge regression penalty.
Returns
-------
None. | f7692:m14 |
def create_design_matrix(long_form,<EOL>specification_dict,<EOL>alt_id_col,<EOL>names=None): | <EOL>check_argument_type(long_form, specification_dict)<EOL>ensure_alt_id_in_long_form(alt_id_col, long_form)<EOL>ensure_specification_cols_are_in_dataframe(specification_dict, long_form)<EOL>unique_alternatives = np.sort(long_form[alt_id_col].unique())<EOL>num_alternatives = len(unique_alternatives)<EOL>check_type_and... | Parameters
----------
long_form : pandas dataframe.
Contains one row for each available alternative, for each observation.
specification_dict : OrderedDict.
Keys are a proper subset of the columns in `long_form_df`. Values are
either a list or a single string, `"all_diff"` or `"all_same"`. If a
list, th... | f7692:m15 |
def get_original_order_unique_ids(id_array): | assert isinstance(id_array, np.ndarray)<EOL>assert len(id_array.shape) == <NUM_LIT:1><EOL>original_unique_id_indices =np.sort(np.unique(id_array, return_index=True)[<NUM_LIT:1>])<EOL>original_order_unique_ids = id_array[original_unique_id_indices]<EOL>return original_order_unique_ids<EOL> | Get the unique id's of id_array, in their original order of appearance.
Parameters
----------
id_array : 1D ndarray.
Should contain the ids that we want to extract the unique values from.
Returns
-------
original_order_unique_ids : 1D ndarray.
Contains the unique ids from `id_array`, in their original order o... | f7692:m16 |
def create_row_to_some_id_col_mapping(id_array): | <EOL>original_order_unique_ids = get_original_order_unique_ids(id_array)<EOL>rows_to_ids = (id_array[:, None] ==<EOL>original_order_unique_ids[None, :]).astype(int)<EOL>return rows_to_ids<EOL> | Parameters
----------
id_array : 1D ndarray.
All elements of the array should be ints representing some id related
to the corresponding row.
Returns
-------
rows_to_ids : 2D scipy sparse array.
Will map each row of id_array to the unique values of `id_array`. The
columns of the returned sparse array wi... | f7692:m17 |
def create_sparse_mapping(id_array, unique_ids=None): | <EOL>if unique_ids is None:<EOL><INDENT>unique_ids = get_original_order_unique_ids(id_array)<EOL><DEDENT>assert isinstance(unique_ids, np.ndarray)<EOL>assert isinstance(id_array, np.ndarray)<EOL>assert unique_ids.ndim == <NUM_LIT:1><EOL>assert id_array.ndim == <NUM_LIT:1><EOL>represented_ids = np.in1d(id_array, unique_... | Will create a scipy.sparse compressed-sparse-row matrix that maps
each row represented by an element in id_array to the corresponding
value of the unique ids in id_array.
Parameters
----------
id_array : 1D ndarray of ints.
Each element should represent some id related to the corresponding row.
unique_ids : 1D nda... | f7692:m18 |
def create_long_form_mappings(long_form,<EOL>obs_id_col,<EOL>alt_id_col,<EOL>choice_col=None,<EOL>nest_spec=None,<EOL>mix_id_col=None,<EOL>dense=False): | <EOL>obs_id_values = long_form[obs_id_col].values<EOL>alt_id_values = long_form[alt_id_col].values<EOL>rows_to_obs = create_sparse_mapping(obs_id_values)<EOL>all_alternatives = np.sort(np.unique(alt_id_values))<EOL>rows_to_alts = create_sparse_mapping(alt_id_values,<EOL>unique_ids=all_alternatives)<EOL>if choice_col is... | Parameters
----------
long_form : pandas dataframe.
Contains one row for each available alternative for each observation.
obs_id_col : str.
Denotes the column in `long_form` which contains the choice situation
observation ID values for each row of `long_form`. Note each value in
this column must be uniq... | f7692:m19 |
def convert_long_to_wide(long_data,<EOL>ind_vars,<EOL>alt_specific_vars,<EOL>subset_specific_vars,<EOL>obs_id_col,<EOL>alt_id_col,<EOL>choice_col,<EOL>alt_name_dict=None,<EOL>null_value=np.nan): | <EOL>num_vars_accounted_for = sum([len(x) for x in<EOL>[ind_vars, alt_specific_vars,<EOL>subset_specific_vars,<EOL>[obs_id_col, alt_id_col, choice_col]]])<EOL>ensure_all_columns_are_used(num_vars_accounted_for, long_data)<EOL>ensure_columns_are_in_dataframe(ind_vars,<EOL>long_data,<EOL>col_title="<STR_LIT>",<EOL>data_t... | Converts a 'long format' dataframe of cross-sectional discrete choice data
into a 'wide format' version of the same data.
Parameters
----------
long_data : pandas dataframe.
Contains one row for each available alternative for each observation.
Should have the specified `[obs_id_col, alt_id_col, choice_col]` co... | f7692:m20 |
def check_wide_data_for_blank_choices(choice_col, wide_data): | if wide_data[choice_col].isnull().any():<EOL><INDENT>msg_1 = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg_1 + msg_2)<EOL><DEDENT>return None<EOL> | Checks `wide_data` for null values in the choice column, and raises a
helpful ValueError if null values are found.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that is used to record each
observation's choice.
wide_data : pandas dataframe.
Contains one row for each observation.... | f7692:m21 |
def ensure_unique_obs_ids_in_wide_data(obs_id_col, wide_data): | if len(wide_data[obs_id_col].unique()) != wide_data.shape[<NUM_LIT:0>]:<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg + msg_2)<EOL><DEDENT>return None<EOL> | Ensures that there is one observation per row in wide_data. Raises a
helpful ValueError if otherwise.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for each row.
wide_data : pandas dataframe.
Contains one row for each observation. Should c... | f7692:m22 |
def ensure_chosen_alternatives_are_in_user_alt_ids(choice_col,<EOL>wide_data,<EOL>availability_vars): | if not wide_data[choice_col].isin(availability_vars.keys()).all():<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg + msg_2)<EOL><DEDENT>return None<EOL> | Ensures that all chosen alternatives in `wide_df` are present in the
`availability_vars` dict. Raises a helpful ValueError if not.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that contains a one if the
alternative pertaining to the given row was the observed outcome for
the ob... | f7692:m23 |
def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,<EOL>choice_col,<EOL>availability_vars,<EOL>wide_data): | <EOL>wide_availability_values = wide_data[list(<EOL>availability_vars.values())].values<EOL>unavailable_condition = ((wide_availability_values == <NUM_LIT:0>).sum(axis=<NUM_LIT:1>)<EOL>.astype(bool))<EOL>problem_obs = []<EOL>for idx, row in wide_data.loc[unavailable_condition].iterrows():<EOL><INDENT>if row.at[availabi... | Checks whether or not each observation with a restricted choice set chose
an alternative that was personally available to him or her. Will raise a
helpful ValueError if this is not the case.
Parameters
----------
obs_id_col : str.
Denotes the column in `wide_data` that contains the observation ID
values for ea... | f7692:m24 |
def ensure_all_wide_alt_ids_are_chosen(choice_col,<EOL>alt_specific_vars,<EOL>availability_vars,<EOL>wide_data): | sorted_alt_ids = np.sort(wide_data[choice_col].unique())<EOL>try:<EOL><INDENT>problem_ids = [x for x in availability_vars<EOL>if x not in sorted_alt_ids]<EOL>problem_type = "<STR_LIT>"<EOL>assert problem_ids == []<EOL>problem_ids = []<EOL>for new_column in alt_specific_vars:<EOL><INDENT>for alt_id in alt_specific_vars[... | Checks to make sure all user-specified alternative id's, both in
`alt_specific_vars` and `availability_vars` are observed in the choice
column of `wide_data`. | f7692:m25 |
def ensure_contiguity_in_observation_rows(obs_id_vector): | <EOL>contiguity_check_array = (obs_id_vector[<NUM_LIT:1>:] - obs_id_vector[:-<NUM_LIT:1>]) >= <NUM_LIT:0><EOL>if not contiguity_check_array.all():<EOL><INDENT>problem_ids = obs_id_vector[np.where(~contiguity_check_array)]<EOL>msg_1 = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>msg_3 = "<STR_LIT>"<EOL>raise ValueError(msg_1... | Ensures that all rows pertaining to a given choice situation are located
next to one another. Raises a helpful ValueError otherwise. This check is
needed because the hessian calculation function requires the design matrix
to have contiguity in rows with the same observation id.
Parameters
----------
rows_to_obs : 2D s... | f7692:m26 |
def convert_wide_to_long(wide_data,<EOL>ind_vars,<EOL>alt_specific_vars,<EOL>availability_vars,<EOL>obs_id_col,<EOL>choice_col,<EOL>new_alt_id_name=None): | <EOL>all_alt_specific_cols = []<EOL>for var_dict in alt_specific_vars.values():<EOL><INDENT>all_alt_specific_cols.extend(var_dict.values())<EOL><DEDENT>vars_accounted_for = set(ind_vars +<EOL>list(availability_vars.values()) +<EOL>[obs_id_col, choice_col] +<EOL>all_alt_specific_cols)<EOL>num_vars_accounted_for = len(va... | Will convert a cross-sectional dataframe of discrete choice data from wide
format to long format.
Parameters
----------
wide_data : pandas dataframe.
Contains one row for each observation. Should have the specified
`[obs_id_col, choice_col] + availability_vars.values()` columns.
ind_vars : list of strings.
... | f7692:m27 |
def convert_mixing_names_to_positions(mixing_names, ind_var_names): | return [ind_var_names.index(name) for name in mixing_names]<EOL> | Parameters
----------
mixing_names : list.
All elements should be strings. Denotes the names of the index
variables that are being treated as random variables.
ind_var_names : list.
All elements should be strings, representing (in order) the variables
in the index.
Returns
-------
list.
All eleme... | f7692:m28 |
def get_normal_draws(num_mixers,<EOL>num_draws,<EOL>num_vars,<EOL>seed=None): | <EOL>assert all([isinstance(x, int) for x in [num_mixers, num_draws, num_vars]])<EOL>assert all([x > <NUM_LIT:0> for x in [num_mixers, num_draws, num_vars]])<EOL>if seed is not None:<EOL><INDENT>assert isinstance(seed, int) and seed > <NUM_LIT:0><EOL><DEDENT>normal_dist = scipy.stats.norm(loc=<NUM_LIT:0.0>, scale=<NUM_... | Parameters
----------
num_mixers : int.
Should be greater than zero. Denotes the number of observations for
which we are making draws from a normal distribution for. I.e. the
number of observations with randomly distributed coefficients.
num_draws : int.
Should be greater than zero. Denotes the number o... | f7693:m0 |
def convert_mixing_names_to_positions(mixing_names, ind_var_names): | return [ind_var_names.index(name) for name in mixing_names]<EOL> | Parameters
----------
mixing_names : list of strings.
Denotes the names of the index variables that are being treated as
random variables.
ind_var_names : list of strings.
Each string should represent (in order) the variables in the index.
Returns
-------
list. All elements should be ints. Elements will be... | f7693:m1 |
def create_expanded_design_for_mixing(design,<EOL>draw_list,<EOL>mixing_pos,<EOL>rows_to_mixers): | if len(mixing_pos) != len(draw_list):<EOL><INDENT>msg = "<STR_LIT>".format(mixing_pos)<EOL>msg_2 = "<STR_LIT>".format(len(draw_list))<EOL>raise ValueError(msg + "<STR_LIT:\n>" + msg_2)<EOL><DEDENT>num_draws = draw_list[<NUM_LIT:0>].shape[<NUM_LIT:1>]<EOL>orig_num_vars = design.shape[<NUM_LIT:1>]<EOL>arrays_for_mixing =... | Parameters
----------
design : 2D ndarray.
All elements should be ints, floats, or longs. Each row corresponds to
an available alternative for a given individual. There should be one
column per index coefficient being estimated.
draw_list : list of 2D ndarrays.
All numpy arrays should have the same numb... | f7693:m2 |
def calc_choice_sequence_probs(prob_array,<EOL>choice_vec,<EOL>rows_to_mixers,<EOL>return_type=None): | if return_type not in [None, '<STR_LIT:all>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>log_chosen_prob_array = choice_vec[:, None] * np.log(prob_array)<EOL>expanded_log_sequence_probs = rows_to_mixers.T.dot(log_chosen_prob_array)<EOL>expanded_sequence_probs = np.exp(expanded_log_sequence_probs)<EOL>zero_i... | Parameters
----------
prob_array : 2D ndarray.
All elements should be ints, floats, or longs. All elements should be
between zero and one (exclusive). Each element should represent the
probability of the corresponding alternative being chosen by the
corresponding individual during the given choice situa... | f7693:m3 |
def calc_mixed_log_likelihood(params,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>rows_to_mixers,<EOL>choice_vector,<EOL>utility_transform,<EOL>ridge=None,<EOL>weights=None): | <EOL>if weights is None:<EOL><INDENT>weights = np.ones(design_3d.shape[<NUM_LIT:0>])<EOL><DEDENT>weights_per_obs =np.max(rows_to_mixers.toarray() * weights[:, None], axis=<NUM_LIT:0>)<EOL>prob_array = general_calc_probabilities(params,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>utility_transform... | Parameters
----------
params : 1D ndarray.
All elements should by ints, floats, or longs. Should have 1 element
for each utility coefficient being estimated (i.e. num_features +
num_coefs_being_mixed).
design_3d : 3D ndarray.
All elements should be ints, floats, or longs. Should have one row per
ob... | f7693:m4 |
def calc_mixed_logit_gradient(params,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>rows_to_mixers,<EOL>choice_vector,<EOL>utility_transform,<EOL>ridge=None,<EOL>weights=None): | <EOL>if weights is None:<EOL><INDENT>weights = np.ones(design_3d.shape[<NUM_LIT:0>])<EOL><DEDENT>prob_array = general_calc_probabilities(params,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>utility_transform,<EOL>return_long_probs=True)<EOL>prob_results = calc_choice_sequence_probs(prob_array,<EOL... | Parameters
----------
params : 1D ndarray.
All elements should by ints, floats, or longs. Should have 1 element
for each utility coefficient being estimated
(i.e. num_features + num_coefs_being_mixed).
design_3d : 3D ndarray.
All elements should be ints, floats, or longs. Should have one row per
ob... | f7693:m5 |
def calc_neg_log_likelihood_and_neg_gradient(beta,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>rows_to_mixers,<EOL>choice_vector,<EOL>utility_transform,<EOL>constrained_pos,<EOL>ridge=None,<EOL>weights=None,<EOL>*args): | neg_log_likelihood = -<NUM_LIT:1> * calc_mixed_log_likelihood(beta,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>rows_to_mixers,<EOL>choice_vector,<EOL>utility_transform,<EOL>ridge=ridge,<EOL>weights=weights)<EOL>neg_beta_gradient_vec = -<NUM_LIT:1> * calc_mixed_logit_gradient(beta,<EOL>design_3d,... | Parameters
----------
beta : 1D ndarray.
All elements should by ints, floats, or longs. Should have 1 element
for each utility coefficient being estimated (i.e. num_features +
num_coefs_being_mixed).
design_3d : 3D ndarray.
All elements should be ints, floats, or longs. Should have one row per
obse... | f7693:m6 |
def calc_bhhh_hessian_approximation_mixed_logit(params,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>rows_to_mixers,<EOL>choice_vector,<EOL>utility_transform,<EOL>ridge=None,<EOL>weights=None): | <EOL>if weights is None:<EOL><INDENT>weights = np.ones(design_3d.shape[<NUM_LIT:0>])<EOL><DEDENT>weights_per_obs =np.max(rows_to_mixers.toarray() * weights[:, None], axis=<NUM_LIT:0>)<EOL>prob_array = general_calc_probabilities(params,<EOL>design_3d,<EOL>alt_IDs,<EOL>rows_to_obs,<EOL>rows_to_alts,<EOL>utility_transform... | Parameters
----------
params : 1D ndarray.
All elements should by ints, floats, or longs. Should have 1 element
for each utility coefficient being estimated (i.e. num_features +
num_coefs_being_mixed).
design_3d : 3D ndarray.
All elements should be ints, floats, or longs. Should have one row per
ob... | f7693:m7 |
def calc_percentile_interval(bootstrap_replicates, conf_percentage): | <EOL>check_conf_percentage_validity(conf_percentage)<EOL>ensure_samples_is_ndim_ndarray(bootstrap_replicates, ndim=<NUM_LIT:2>)<EOL>alpha = get_alpha_from_conf_percentage(conf_percentage)<EOL>lower_percent = alpha / <NUM_LIT><EOL>upper_percent = <NUM_LIT> - lower_percent<EOL>lower_endpoint = np.percentile(bootstrap_rep... | Calculate bootstrap confidence intervals based on raw percentiles of the
bootstrap distribution of samples.
Parameters
----------
bootstrap_replicates : 2D ndarray.
Each row should correspond to a different bootstrap parameter sample.
Each column should correspond to an element of the parameter vector
bein... | f7694:m0 |
def calc_bias_correction_bca(bootstrap_replicates, mle_estimate): | numerator = (bootstrap_replicates < mle_estimate[None, :]).sum(axis=<NUM_LIT:0>)<EOL>denominator = float(bootstrap_replicates.shape[<NUM_LIT:0>])<EOL>bias_correction = norm.ppf(numerator / denominator)<EOL>return bias_correction<EOL> | Calculate the bias correction for the Bias Corrected and Accelerated (BCa)
bootstrap confidence intervals.
Parameters
----------
bootstrap_replicates : 2D ndarray.
Each row should correspond to a different bootstrap parameter sample.
Each column should correspond to an element of the parameter vector
being... | f7694:m1 |
def calc_acceleration_bca(jackknife_replicates): | <EOL>jackknife_mean = jackknife_replicates.mean(axis=<NUM_LIT:0>)[None, :]<EOL>differences = jackknife_mean - jackknife_replicates<EOL>numerator = (differences**<NUM_LIT:3>).sum(axis=<NUM_LIT:0>)<EOL>denominator = <NUM_LIT:6> * ((differences**<NUM_LIT:2>).sum(axis=<NUM_LIT:0>))**<NUM_LIT><EOL>zero_denom = np.where(deno... | Calculate the acceleration constant for the Bias Corrected and Accelerated
(BCa) bootstrap confidence intervals.
Parameters
----------
jackknife_replicates : 2D ndarray.
Each row should correspond to a different jackknife parameter sample,
formed by deleting a particular observation and then re-estimating the
... | f7694:m2 |
def calc_lower_bca_percentile(alpha_percent, bias_correction, acceleration): | z_lower = norm.ppf(alpha_percent / (<NUM_LIT> * <NUM_LIT:2>))<EOL>numerator = bias_correction + z_lower<EOL>denominator = <NUM_LIT:1> - acceleration * numerator<EOL>lower_percentile =norm.cdf(bias_correction + numerator / denominator) * <NUM_LIT:100><EOL>return lower_percentile<EOL> | Calculate the lower values of the Bias Corrected and Accelerated (BCa)
bootstrap confidence intervals.
Parameters
----------
alpha_percent : float in (0.0, 100.0).
`100 - confidence_percentage`, where `confidence_percentage` is the
confidence level (such as 95%), expressed as a percent.
bias_correction : 1D nd... | f7694:m3 |
def calc_upper_bca_percentile(alpha_percent, bias_correction, acceleration): | z_upper = norm.ppf(<NUM_LIT:1> - alpha_percent / (<NUM_LIT> * <NUM_LIT:2>))<EOL>numerator = bias_correction + z_upper<EOL>denominator = <NUM_LIT:1> - acceleration * numerator<EOL>upper_percentile =norm.cdf(bias_correction + numerator / denominator) * <NUM_LIT:100><EOL>return upper_percentile<EOL> | Calculate the lower values of the Bias Corrected and Accelerated (BCa)
bootstrap confidence intervals.
Parameters
----------
alpha_percent : float in (0.0, 100.0).
`100 - confidence_percentage`, where `confidence_percentage` is the
confidence level (such as 95%), expressed as a percent.
bias_correction : 1D nd... | f7694:m4 |
def calc_bca_interval(bootstrap_replicates,<EOL>jackknife_replicates,<EOL>mle_params,<EOL>conf_percentage): | <EOL>check_conf_percentage_validity(conf_percentage)<EOL>ensure_samples_is_ndim_ndarray(bootstrap_replicates, ndim=<NUM_LIT:2>)<EOL>ensure_samples_is_ndim_ndarray(jackknife_replicates,<EOL>name='<STR_LIT>', ndim=<NUM_LIT:2>)<EOL>alpha_percent = get_alpha_from_conf_percentage(conf_percentage)<EOL>bias_correction =calc_b... | Calculate 'bias-corrected and accelerated' bootstrap confidence intervals.
Parameters
----------
bootstrap_replicates : 2D ndarray.
Each row should correspond to a different bootstrap parameter sample.
Each column should correspond to an element of the parameter vector
being estimated.
jackknife_replicates... | f7694:m5 |
def identify_degenerate_nests(nest_spec): | degenerate_positions = []<EOL>for pos, key in enumerate(nest_spec):<EOL><INDENT>if len(nest_spec[key]) == <NUM_LIT:1>:<EOL><INDENT>degenerate_positions.append(pos)<EOL><DEDENT><DEDENT>return degenerate_positions<EOL> | Identify the nests within nest_spec that are degenerate, i.e. those nests
with only a single alternative within the nest.
Parameters
----------
nest_spec : OrderedDict.
Keys are strings that define the name of the nests. Values are lists
of alternative ids, denoting which alternatives belong to which nests.
... | f7696:m0 |
def split_param_vec(all_params, rows_to_nests, return_all_types=False): | <EOL>num_nests = rows_to_nests.shape[<NUM_LIT:1>]<EOL>orig_nest_coefs = all_params[:num_nests]<EOL>index_coefs = all_params[num_nests:]<EOL>if return_all_types:<EOL><INDENT>return orig_nest_coefs, None, None, index_coefs<EOL><DEDENT>else:<EOL><INDENT>return orig_nest_coefs, index_coefs<EOL><DEDENT> | Parameters
----------
all_params : 1D ndarray.
Should contain all of the parameters being estimated (i.e. all the
nest coefficients and all of the index coefficients). All elements
should be ints, floats, or longs.
rows_to_nests : 2D scipy sparse array.
There should be one row per observation per availa... | f7696:m1 |
def check_length_of_initial_values(self, init_values): | <EOL>num_nests = self.rows_to_nests.shape[<NUM_LIT:1>]<EOL>num_index_coefs = self.design.shape[<NUM_LIT:1>]<EOL>assumed_param_dimensions = num_index_coefs + num_nests<EOL>if init_values.shape[<NUM_LIT:0>] != assumed_param_dimensions:<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_1 = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>rais... | Ensures that the initial values are of the correct length. | f7696:c0:m1 |
def convenience_split_params(self, params, return_all_types=False): | return split_param_vec(params,<EOL>self.rows_to_nests,<EOL>return_all_types=return_all_types)<EOL> | Splits parameter vector into nest parameters and index parameters.
Parameters
----------
all_params : 1D ndarray.
Should contain all of the parameters being estimated (i.e. all the
nest coefficients and all of the index coefficients). All elements
should be ints, floats, or longs.
rows_to_nests : 2D scipy ... | f7696:c0:m2 |
def convenience_calc_probs(self, params): | orig_nest_coefs, betas = self.convenience_split_params(params)<EOL>natural_nest_coefs = nc.naturalize_nest_coefs(orig_nest_coefs)<EOL>args = [natural_nest_coefs,<EOL>betas,<EOL>self.design,<EOL>self.rows_to_obs,<EOL>self.rows_to_nests]<EOL>kwargs = {"<STR_LIT>": self.chosen_row_to_obs,<EOL>"<STR_LIT>": "<STR_LIT>"}<EOL... | Calculates the probabilities of the chosen alternative, and the long
format probabilities for this model and dataset. | f7696:c0:m3 |
def convenience_calc_log_likelihood(self, params): | orig_nest_coefs, betas = self.convenience_split_params(params)<EOL>natural_nest_coefs = nc.naturalize_nest_coefs(orig_nest_coefs)<EOL>args = [natural_nest_coefs,<EOL>betas,<EOL>self.design,<EOL>self.rows_to_obs,<EOL>self.rows_to_nests,<EOL>self.choice_vector]<EOL>kwargs = {"<STR_LIT>": self.ridge, "<STR_LIT>": self.wei... | Calculates the log-likelihood for this model and dataset. | f7696:c0:m4 |
def convenience_calc_gradient(self, params): | orig_nest_coefs, betas = self.convenience_split_params(params)<EOL>args = [orig_nest_coefs,<EOL>betas,<EOL>self.design,<EOL>self.choice_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_nests]<EOL>return general_gradient(*args, ridge=self.ridge, weights=self.weights)<EOL> | Calculates the gradient of the log-likelihood for this model / dataset. | f7696:c0:m5 |
def convenience_calc_hessian(self, params): | orig_nest_coefs, betas = self.convenience_split_params(params)<EOL>args = [orig_nest_coefs,<EOL>betas,<EOL>self.design,<EOL>self.choice_vector,<EOL>self.rows_to_obs,<EOL>self.rows_to_nests]<EOL>approx_hess =bhhh_approx(*args, ridge=self.ridge, weights=self.weights)<EOL>if self.constrained_pos is not None:<EOL><INDENT>f... | Calculates the hessian of the log-likelihood for this model / dataset.
Note that this function name is INCORRECT with regard to the actual
actions performed. The Nested Logit model uses the BHHH approximation
to the Fisher Information Matrix in place of the actual hessian. | f7696:c0:m6 |
def convenience_calc_fisher_approx(self, params): | placeholder_bhhh = np.diag(-<NUM_LIT:1> * np.ones(params.shape[<NUM_LIT:0>]))<EOL>return placeholder_bhhh<EOL> | Calculates the BHHH approximation of the Fisher Information Matrix for
this model / dataset. Note that this function name is INCORRECT with
regard to the actual actions performed. The Nested Logit model uses a
placeholder for the BHHH approximation of the Fisher Information Matrix
because the BHHH approximation is alre... | f7696:c0:m7 |
def fit_mle(self,<EOL>init_vals,<EOL>constrained_pos=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>just_point=False,<EOL>**kwargs): | <EOL>kwargs_to_be_ignored = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>if any([x in kwargs for x in kwargs_to_be_ignored]):<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg_2 = "<STR_LIT>"<EOL>raise ValueError(msg.format(kwargs_to_be_ignored) + msg_2)<EOL><DEDENT>self.optimization_method = method<EOL>self.ridge_param = ridge<EOL... | Parameters
----------
init_vals : 1D ndarray.
Should containn the initial values to start the optimization
process with. There should be one value for each nest parameter
and utility coefficient. Nest parameters not being estimated
should still be included. Handle these parameters using the
`constra... | f7696:c1:m1 |
def split_param_vec(param_vec, rows_to_alts, design, return_all_types=False): | <EOL>num_shapes = rows_to_alts.shape[<NUM_LIT:1>] - <NUM_LIT:1><EOL>num_index_coefs = design.shape[<NUM_LIT:1>]<EOL>shapes = param_vec[:num_shapes]<EOL>betas = param_vec[-<NUM_LIT:1> * num_index_coefs:]<EOL>remaining_idx = param_vec.shape[<NUM_LIT:0>] - (num_shapes + num_index_coefs)<EOL>if remaining_idx > <NUM_LIT:0>:... | Parameters
----------
param_vec : 1D ndarray.
Should have as many elements as there are parameters being estimated.
rows_to_alts : 2D scipy sparse matrix.
There should be one row per observation per available alternative and
one column per possible alternative. This matrix maps the rows of the
design ma... | f7697:m0 |
def _convert_eta_to_c(eta, ref_position): | <EOL>exp_eta = np.exp(eta)<EOL>exp_eta[np.isposinf(exp_eta)] = max_comp_value<EOL>exp_eta[exp_eta == <NUM_LIT:0>] = min_comp_value<EOL>denom = exp_eta.sum(axis=<NUM_LIT:0>) + <NUM_LIT:1><EOL>replace_list = list(range(eta.shape[<NUM_LIT:0>] + <NUM_LIT:1>))<EOL>replace_list.remove(ref_position)<EOL>if len(eta.shape) > <N... | Parameters
----------
eta : 1D or 2D ndarray.
The elements of the array should be this model's 'transformed' shape
parameters, i.e. the natural log of (the corresponding shape parameter
divided by the reference shape parameter). This array's elements will
be real valued. If `eta` is 2D, then its shape s... | f7697:m1 |
def _calc_deriv_c_with_respect_to_eta(natural_shapes,<EOL>ref_position,<EOL>output_array=None): | <EOL>columns_to_be_kept = range(natural_shapes.shape[<NUM_LIT:0>])<EOL>columns_to_be_kept.remove(ref_position)<EOL>output_array[:, :] = (np.diag(natural_shapes) -<EOL>np.outer(natural_shapes,<EOL>natural_shapes))[:, columns_to_be_kept]<EOL>return output_array<EOL> | Parameters
----------
natural_shapes : 1D ndarray.
Should have one element per available alternative in the dataset whose
choice situations are being modeled. Should have at least
`ref_position` elements in it.
ref_position : int.
Specifies the position in the array of natural shape parameters that
... | f7697:m2 |
def _asym_utility_transform(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>eta,<EOL>intercept_params,<EOL>shape_ref_position=None,<EOL>intercept_ref_pos=None,<EOL>*args, **kwargs): | <EOL>natural_shape_params = _convert_eta_to_c(eta, shape_ref_position)<EOL>long_shapes = rows_to_alts.dot(natural_shape_params)<EOL>num_alts = rows_to_alts.shape[<NUM_LIT:1>]<EOL>log_long_shapes = np.log(long_shapes)<EOL>log_long_shapes[np.isneginf(log_long_shapes)] = -<NUM_LIT:1> * max_comp_value<EOL>log_1_sub_long_sh... | Parameters
----------
systematic_utilities : 1D ndarray.
Contains the systematic utilities for each each available alternative
for each observation. All elements should be ints, floats, or longs.
alt_IDs : 1D ndarray.
All elements should be ints. There should be one row per obervation per
available altern... | f7697:m3 |
def _asym_transform_deriv_v(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>eta,<EOL>ref_position=None,<EOL>output_array=None,<EOL>*args, **kwargs): | <EOL>natural_shape_params = _convert_eta_to_c(eta, ref_position)<EOL>long_shapes = rows_to_alts.dot(natural_shape_params)<EOL>num_alts = rows_to_alts.shape[<NUM_LIT:1>]<EOL>log_long_shapes = np.log(long_shapes)<EOL>log_long_shapes[np.isneginf(log_long_shapes)] = -<NUM_LIT:1> * max_comp_value<EOL>log_1_sub_long_shapes =... | Parameters
----------
systematic_utilities : 1D ndarray.
Contains the systematic utilities for each each available alternative
for each observation. All elements should be ints, floats, or longs.
alt_IDs : 1D ndarray.
All elements should be ints. There should be one row per obervation per
available altern... | f7697:m4 |
def _asym_transform_deriv_shape(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>eta,<EOL>ref_position=None,<EOL>dh_dc_array=None,<EOL>fill_dc_d_eta=None,<EOL>output_array=None,<EOL>*args, **kwargs): | <EOL>natural_shape_params = _convert_eta_to_c(eta, ref_position)<EOL>long_shapes = rows_to_alts.dot(natural_shape_params)<EOL>d_lnShape_dShape = <NUM_LIT:1.0> / long_shapes<EOL>d_lnShape_dShape[np.isposinf(d_lnShape_dShape)] = max_comp_value<EOL>d_lnShapeComp_dShape = -<NUM_LIT:1.0> / (<NUM_LIT:1> - long_shapes)<EOL>d_... | Parameters
----------
systematic_utilities : 1D ndarray.
Contains the systematic utilities for each each available alternative
for each observation. All elements should be ints, floats, or longs.
alt_IDs : 1D ndarray.
All elements should be ints. There should be one row per obervation per
available altern... | f7697:m5 |
def _asym_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.
Contains the systematic utilities for each each available alternative
for each observation. All elements should be ints, floats, or longs.
alt_IDs : 1D ndarray.
All elements should be ints. There should be one row per obervation per
available altern... | f7697:m6 |
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(_asym_transform_deriv_v,<EOL>ref_position=estimator.shape_ref_pos,<EOL>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... | f7697:m7 |
def create_calc_dh_d_shape(estimator): | num_alts = estimator.rows_to_alts.shape[<NUM_LIT:1>]<EOL>pre_dc_d_eta = np.zeros((num_alts, num_alts - <NUM_LIT:1>), dtype=float)<EOL>pre_dh_dc = estimator.rows_to_alts.copy()<EOL>pre_dh_d_eta = np.matrix(np.zeros((estimator.design.shape[<NUM_LIT:0>],<EOL>num_alts - <NUM_LIT:1>), dtype=float))<EOL>easy_calc_dc_d_eta = ... | 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... | f7697:m8 |
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... | f7697:m9 |
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 + ... | 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 optimization process with. There
should be one value for each index coefficient, outside intercept
parameter, and shape parameter be... | f7697:c0:m1 |
def fit_mle(self, 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... | f7697:c1:m1 |
def split_param_vec(param_vec, rows_to_alts, design, return_all_types=False): | <EOL>num_shapes = rows_to_alts.shape[<NUM_LIT:1>]<EOL>num_index_coefs = design.shape[<NUM_LIT:1>]<EOL>shapes = param_vec[:num_shapes]<EOL>betas = param_vec[-<NUM_LIT:1> * num_index_coefs:]<EOL>remaining_idx = param_vec.shape[<NUM_LIT:0>] - (num_shapes + num_index_coefs)<EOL>if remaining_idx > <NUM_LIT:0>:<EOL><INDENT>i... | Parameters
----------
param_vec : 1D ndarray.
Elements should all be ints, floats, or longs. Should have as many
elements as there are parameters being estimated.
rows_to_alts : 2D scipy sparse matrix.
There should be one row per observation per available alternative and
one column per possible alternat... | f7698:m0 |
def _uneven_utility_transform(systematic_utilities,<EOL>alt_IDs,<EOL>rows_to_alts,<EOL>shape_params,<EOL>intercept_params,<EOL>intercept_ref_pos=None,<EOL>*args, **kwargs): | <EOL>natural_shapes = np.exp(shape_params)<EOL>natural_shapes[np.isposinf(natural_shapes)] = max_comp_value<EOL>long_natural_shapes = rows_to_alts.dot(natural_shapes)<EOL>exp_neg_utilities = np.exp(-<NUM_LIT:1> * systematic_utilities)<EOL>log_1_plus_exp_neg_utilitiles = np.log1p(exp_neg_utilities)<EOL>inf_idx = np.isin... | 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:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.