Search is not available for this dataset
text stringlengths 75 104k |
|---|
def create_row_to_some_id_col_mapping(id_array):
"""
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... |
def create_sparse_mapping(id_array, unique_ids=None):
"""
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.
E... |
def create_long_form_mappings(long_form,
obs_id_col,
alt_id_col,
choice_col=None,
nest_spec=None,
mix_id_col=None,
dense=False):
"""
... |
def convert_long_to_wide(long_data,
ind_vars,
alt_specific_vars,
subset_specific_vars,
obs_id_col,
alt_id_col,
choice_col,
alt_name_dict=None,
... |
def check_wide_data_for_blank_choices(choice_col, wide_data):
"""
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
... |
def ensure_unique_obs_ids_in_wide_data(obs_id_col, wide_data):
"""
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
val... |
def ensure_chosen_alternatives_are_in_user_alt_ids(choice_col,
wide_data,
availability_vars):
"""
Ensures that all chosen alternatives in `wide_df` are present in the
`availability_vars` dict. Raises a help... |
def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,
choice_col,
availability_vars,
wide_data):
"""
Checks whether or not each ob... |
def ensure_all_wide_alt_ids_are_chosen(choice_col,
alt_specific_vars,
availability_vars,
wide_data):
"""
Checks to make sure all user-specified alternative id's, both in
`alt_specific_vars` a... |
def ensure_contiguity_in_observation_rows(obs_id_vector):
"""
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 contigui... |
def convert_wide_to_long(wide_data,
ind_vars,
alt_specific_vars,
availability_vars,
obs_id_col,
choice_col,
new_alt_id_name=None):
"""
Will convert a cross-sectio... |
def relate_obs_ids_to_chosen_alts(obs_id_array,
alt_id_array,
choice_array):
"""
Creates a dictionary that relates each unique alternative id to the set of
observations ids that chose the given alternative.
Parameters
----------
... |
def get_num_obs_choosing_each_alternative(obs_per_alt_dict):
"""
Will create an ordered dictionary that records the number of units of
observation that have chosen the given alternative (i.e. the associated
dictionary key). Will also determine the total number of unique
observations in the dataset.
... |
def create_cross_sectional_bootstrap_samples(obs_id_array,
alt_id_array,
choice_array,
num_samples,
seed=None):
"""
Determines the u... |
def create_bootstrap_id_array(obs_id_per_sample):
"""
Creates a 2D ndarray that contains the 'bootstrap ids' for each replication
of each unit of observation that is an the set of bootstrap samples.
Parameters
----------
obs_id_per_sample : 2D ndarray of ints.
Should have one row for ea... |
def create_deepcopied_groupby_dict(orig_df, obs_id_col):
"""
Will create a dictionary where each key corresponds to a unique value in
`orig_df[obs_id_col]` and each value corresponds to all of the rows of
`orig_df` where `orig_df[obs_id_col] == key`.
Parameters
----------
orig_df : pandas D... |
def check_column_existence(col_name, df, presence=True):
"""
Checks whether or not `col_name` is in `df` and raises a helpful error msg
if the desired condition is not met.
Parameters
----------
col_name : str.
Should represent a column whose presence in `df` is to be checked.
df : ... |
def ensure_resampled_obs_ids_in_df(resampled_obs_ids, orig_obs_id_array):
"""
Checks whether all ids in `resampled_obs_ids` are in `orig_obs_id_array`.
Raises a helpful ValueError if not.
Parameters
----------
resampled_obs_ids : 1D ndarray of ints.
Should contain the observation ids of... |
def create_bootstrap_dataframe(orig_df,
obs_id_col,
resampled_obs_ids_1d,
groupby_dict,
boot_id_col="bootstrap_id"):
"""
Will create the altered dataframe of data needed to estimate a choi... |
def get_param_names(model_obj):
"""
Extracts all the names to be displayed for the estimated parameters.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`.
R... |
def get_param_list_for_prediction(model_obj, replicates):
"""
Create the `param_list` argument for use with `model_obj.predict`.
Parameters
----------
model_obj : an instance of an MNDC object.
Should have the following attributes:
`['ind_var_names', 'intercept_names', 'shape_names'... |
def generate_bootstrap_replicates(self,
num_samples,
mnl_obj=None,
mnl_init_vals=None,
mnl_fit_kwargs=None,
extract_init_vals=None... |
def generate_jackknife_replicates(self,
mnl_obj=None,
mnl_init_vals=None,
mnl_fit_kwargs=None,
extract_init_vals=None,
print_res=F... |
def calc_log_likes_for_replicates(self,
replicates='bootstrap',
num_draws=None,
seed=None):
"""
Calculate the log-likelihood value of one's replicates, given one's
dataset.
... |
def calc_gradient_norm_for_replicates(self,
replicates='bootstrap',
ridge=None,
constrained_pos=None,
weights=None):
"""
Calculate the E... |
def calc_percentile_interval(self, conf_percentage):
"""
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
... |
def calc_bca_interval(self, 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... |
def calc_abc_interval(self,
conf_percentage,
init_vals,
epsilon=0.001,
**fit_kwargs):
"""
Calculates Approximate Bootstrap Confidence Intervals for one's model.
Parameters
----------
... |
def calc_conf_intervals(self,
conf_percentage,
interval_type='all',
init_vals=None,
epsilon=abc.EPSILON,
**fit_kwargs):
"""
Calculates percentile, bias-corrected an... |
def split_param_vec(param_vec, rows_to_alts, design, return_all_types=False):
"""
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.
... |
def _cloglog_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
intercept_params,
intercept_ref_pos=None,
*a... |
def _cloglog_transform_deriv_v(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
"""
Parameters
----------
... |
def create_calc_dh_d_alpha(estimator):
"""
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 estimatio... |
def calc_individual_chi_squares(residuals,
long_probabilities,
rows_to_obs):
"""
Calculates individual chi-squared values for each choice situation in the
dataset.
Parameters
----------
residuals : 1D ndarray.
The choice ve... |
def calc_rho_and_rho_bar_squared(final_log_likelihood,
null_log_likelihood,
num_est_parameters):
"""
Calculates McFadden's rho-squared and rho-bar squared for the given model.
Parameters
----------
final_log_likelihood : float.
... |
def calc_and_store_post_estimation_results(results_dict,
estimator):
"""
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 v... |
def estimate(init_values,
estimator,
method,
loss_tol,
gradient_tol,
maxiter,
print_results,
use_hessian=True,
just_point=False,
**kwargs):
"""
Estimate the given choice model that is defined by ... |
def convenience_split_params(self, params, return_all_types=False):
"""
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... |
def calc_neg_log_likelihood_and_neg_gradient(self, params):
"""
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.
"""
neg_log_likelihood = -1 * self.conve... |
def convenience_calc_probs(self, params):
"""
Calculates the probabilities of the chosen alternative, and the long
format probabilities for this model and dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
prob_args = [betas,
... |
def convenience_calc_log_likelihood(self, params):
"""
Calculates the log-likelihood for this model and dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
args = [betas,
self.design,
self.alt_id_vector,
... |
def convenience_calc_hessian(self, params):
"""
Calculates the hessian of the log-likelihood for this model / dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
args = [betas,
self.design,
self.alt_id_vector,
... |
def convenience_calc_fisher_approx(self, params):
"""
Calculates the BHHH approximation of the Fisher Information Matrix for
this model / dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
args = [betas,
self.design,
... |
def split_param_vec(beta,
rows_to_alts=None,
design=None,
return_all_types=False,
*args, **kwargs):
"""
Parameters
----------
beta : 1D ndarray.
All elements should by ints, floats, or longs. Should have 1 element
... |
def _mnl_utility_transform(systematic_utilities, *args, **kwargs):
"""
Parameters
----------
systematic_utilities : 1D ndarray.
Should contain the systematic utilities for each each available
alternative for each observation.
Returns
-------
`systematic_utilities[:, None]`
... |
def check_length_of_initial_values(self, init_values):
"""
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... |
def fit_mle(self,
init_vals,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
constrained_pos=None,
just_point=False,
... |
def get_normal_draws(num_mixers,
num_draws,
num_vars,
seed=None):
"""
Parameters
----------
num_mixers : int.
Should be greater than zero. Denotes the number of observations for
which we are making draws from a normal distrib... |
def create_expanded_design_for_mixing(design,
draw_list,
mixing_pos,
rows_to_mixers):
"""
Parameters
----------
design : 2D ndarray.
All elements should be ints, floats, or longs. Ea... |
def calc_choice_sequence_probs(prob_array,
choice_vec,
rows_to_mixers,
return_type=None):
"""
Parameters
----------
prob_array : 2D ndarray.
All elements should be ints, floats, or longs. All elements sh... |
def calc_mixed_log_likelihood(params,
design_3d,
alt_IDs,
rows_to_obs,
rows_to_alts,
rows_to_mixers,
choice_vector,
... |
def calc_mixed_logit_gradient(params,
design_3d,
alt_IDs,
rows_to_obs,
rows_to_alts,
rows_to_mixers,
choice_vector,
... |
def calc_neg_log_likelihood_and_neg_gradient(beta,
design_3d,
alt_IDs,
rows_to_obs,
rows_to_alts,
... |
def calc_bhhh_hessian_approximation_mixed_logit(params,
design_3d,
alt_IDs,
rows_to_obs,
rows_to_alts,
... |
def check_conf_percentage_validity(conf_percentage):
"""
Ensures that `conf_percentage` is in (0, 100). Raises a helpful ValueError
if otherwise.
"""
msg = "conf_percentage MUST be a number between 0.0 and 100."
condition_1 = isinstance(conf_percentage, Number)
if not condition_1:
ra... |
def ensure_samples_is_ndim_ndarray(samples, name='bootstrap', ndim=2):
"""
Ensures that `samples` is an `ndim` numpy array. Raises a helpful
ValueError if otherwise.
"""
assert isinstance(ndim, int)
assert isinstance(name, str)
if not isinstance(samples, np.ndarray) or not (samples.ndim == n... |
def create_estimation_obj(model_obj,
init_vals,
mappings=None,
ridge=None,
constrained_pos=None,
weights=None):
"""
Should return a model estimation object corresponding to the model... |
def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights):
"""
Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful
ValueError if otherwise.
"""
if not isinstance(wide_weights, np.ndarray):
msg = "wide_weights MUST be a ndarray."
raise ValueError(msg)
ndim = wide_w... |
def check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs):
"""
Ensures the args to `create_long_form_weights` have expected properties.
"""
# Ensure model_obj has the necessary method for create_long_form_weights
ensure_model_obj_has_mapping_constructor(model_obj)
# Ensure wide_... |
def create_long_form_weights(model_obj, wide_weights, rows_to_obs=None):
"""
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 inst... |
def calc_finite_diff_terms_for_abc(model_obj,
mle_params,
init_vals,
epsilon,
**fit_kwargs):
"""
Calculates the terms needed for the finite difference approximations of
... |
def calc_empirical_influence_abc(term_plus,
term_minus,
epsilon):
"""
Calculates the finite difference, midpoint / slope approximation to the
empirical influence array needed to compute the approximate boostrap
confidence (ABC) intervals.... |
def calc_2nd_order_influence_abc(mle_params,
term_plus,
term_minus,
epsilon):
"""
Calculates either a 'positive' finite difference approximation or an
approximation of a 'positive' finite difference approximat... |
def calc_influence_arrays_for_abc(model_obj,
mle_est,
init_values,
epsilon,
**fit_kwargs):
"""
Calculates the empirical influence array and the 2nd order empirical
influenc... |
def calc_std_error_abc(empirical_influence):
"""
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 ... |
def calc_acceleration_abc(empirical_influence):
"""
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 pa... |
def calc_bias_abc(second_order_influence):
"""
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 ha... |
def calc_quadratic_coef_abc(model_object,
mle_params,
init_vals,
empirical_influence,
std_error,
epsilon,
**fit_kwargs):
"""
Calculates the quad... |
def calc_bias_correction_abc(acceleration, total_curvature):
"""
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 constant... |
def calc_endpoint_from_percentile_abc(model_obj,
init_vals,
percentile,
bias_correction,
acceleration,
std_error,
... |
def efron_endpoints_for_abc_confidence_interval(conf_percentage,
model_obj,
init_vals,
bias_correction,
acceleration,
... |
def calc_abc_interval(model_obj,
mle_params,
init_vals,
conf_percentage,
epsilon=0.001,
**fit_kwargs):
"""
Calculate 'approximate bootstrap confidence' intervals.
Parameters
----------
mode... |
def calc_nested_probs(nest_coefs,
index_coefs,
design,
rows_to_obs,
rows_to_nests,
chosen_row_to_obs=None,
return_type="long_probs",
*args,
**kw... |
def calc_nested_log_likelihood(nest_coefs,
index_coefs,
design,
rows_to_obs,
rows_to_nests,
choice_vector,
ridge=None,
... |
def prep_vectors_for_gradient(nest_coefs,
index_coefs,
design,
choice_vec,
rows_to_obs,
rows_to_nests,
*args,
... |
def naturalize_nest_coefs(nest_coef_estimates):
"""
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
----... |
def calc_nested_gradient(orig_nest_coefs,
index_coefs,
design,
choice_vec,
rows_to_obs,
rows_to_nests,
ridge=None,
weights=None,
... |
def calc_bhhh_hessian_approximation(orig_nest_coefs,
index_coefs,
design,
choice_vec,
rows_to_obs,
rows_to_nests,
... |
def _uneven_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
intercept_params,
intercept_ref_pos=None,
*args, **... |
def _uneven_transform_deriv_v(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
"""
Parameters
----------
sy... |
def _uneven_transform_deriv_shape(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
"""
Paramete... |
def create_calc_dh_dv(estimator):
"""
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.
... |
def create_calc_dh_d_shape(estimator):
"""
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.LogitTypeE... |
def check_length_of_initial_values(self, init_values):
"""
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.... |
def mnl_utility_transform(sys_utility_array, *args, **kwargs):
"""
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_utili... |
def check_length_of_init_values(design_3d, init_values):
"""
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
----------
... |
def add_mixl_specific_results_to_estimation_res(estimator, results_dict):
"""
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 `... |
def convenience_split_params(self, params, return_all_types=False):
"""
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... |
def convenience_calc_probs(self, params):
"""
Calculates the probabilities of the chosen alternative, and the long
format probabilities for this model and dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
prob_args = (betas,
... |
def convenience_calc_log_likelihood(self, params):
"""
Calculates the log-likelihood for this model and dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
args = [betas,
self.design_3d,
self.alt_id_vector,
... |
def convenience_calc_gradient(self, params):
"""
Calculates the gradient of the log-likelihood for this model / dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
args = [betas,
self.design_3d,
self.alt_id_vector,
... |
def convenience_calc_hessian(self, params):
"""
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 Informatio... |
def convenience_calc_fisher_approx(self, params):
"""
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 t... |
def fit_mle(self,
init_vals,
num_draws,
seed=None,
constrained_pos=None,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=... |
def __filter_past_mappings(self,
past_mappings,
long_inclusion_array):
"""
Parameters
----------
past_mappings : dict.
All elements should be None or compressed sparse row matrices from
scipy.sparse. Th... |
def panel_predict(self,
data,
num_draws,
return_long_probs=True,
choice_col=None,
seed=None):
"""
Parameters
----------
data : string or pandas dataframe.
If string, ... |
def _convert_eta_to_c(eta, ref_position):
"""
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 ... |
def _calc_deriv_c_with_respect_to_eta(natural_shapes,
ref_position,
output_array=None):
"""
Parameters
----------
natural_shapes : 1D ndarray.
Should have one element per available alternative in the dataset whose
... |
def _asym_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
eta,
intercept_params,
shape_ref_position=None,
intercept_ref_pos=None,
... |
def _asym_transform_deriv_v(systematic_utilities,
alt_IDs,
rows_to_alts,
eta,
ref_position=None,
output_array=None,
*args, **kwargs):
"""
Parame... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.