Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _asym_transform_deriv_shape(systematic_utilities,
alt_IDs,
rows_to_alts,
eta,
ref_position=None,
dh_dc_array=None,
fill_dc_d... |
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 _scobit_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
intercept_params,
intercept_ref_pos=None,
*args, **... |
def _scobit_transform_deriv_v(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
"""
Parameters
----------
sy... |
def _scobit_transform_deriv_shape(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
"""
Paramete... |
def fit_mle(self,
init_vals,
init_shapes=None,
init_intercepts=None,
init_coefs=None,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
... |
def identify_degenerate_nests(nest_spec):
"""
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
... |
def split_param_vec(all_params, rows_to_nests, return_all_types=False):
"""
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,... |
def check_length_of_initial_values(self, init_values):
"""
Ensures that the initial values are of the correct length.
"""
# Figure out how many shape parameters we should have and how many
# index coefficients we should have
num_nests = self.rows_to_nests.shape[1]
... |
def convenience_split_params(self, params, return_all_types=False):
"""
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
ne... |
def convenience_calc_probs(self, params):
"""
Calculates the probabilities of the chosen alternative, and the long
format probabilities for this model and dataset.
"""
orig_nest_coefs, betas = self.convenience_split_params(params)
natural_nest_coefs = nc.naturalize_nest_c... |
def convenience_calc_log_likelihood(self, params):
"""
Calculates the log-likelihood for this model and dataset.
"""
orig_nest_coefs, betas = self.convenience_split_params(params)
natural_nest_coefs = nc.naturalize_nest_coefs(orig_nest_coefs)
args = [natural_nest_coefs,
... |
def convenience_calc_gradient(self, params):
"""
Calculates the gradient of the log-likelihood for this model / dataset.
"""
orig_nest_coefs, betas = self.convenience_split_params(params)
args = [orig_nest_coefs,
betas,
self.design,
... |
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 Nested Logit model uses the BHHH approximation
to the Fisher Informati... |
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 Nested Logit model uses a
placeholder for ... |
def fit_mle(self,
init_vals,
constrained_pos=None,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
just_point=False,
... |
def calc_probabilities(beta,
design,
alt_IDs,
rows_to_obs,
rows_to_alts,
utility_transform,
intercept_params=None,
shape_params=None,
ch... |
def calc_log_likelihood(beta,
design,
alt_IDs,
rows_to_obs,
rows_to_alts,
choice_vector,
utility_transform,
intercept_params=None,
... |
def calc_gradient(beta,
design,
alt_IDs,
rows_to_obs,
rows_to_alts,
choice_vector,
utility_transform,
transform_first_deriv_c,
transform_first_deriv_v,
transf... |
def create_matrix_block_indices(row_to_obs):
"""
Parameters
----------
row_to_obs: 2D ndarray.
There should be one row per observation per available alternative and
one column per observation. This matrix maps the rows of the design
matrix to the unique observations (on the colum... |
def robust_outer_product(vec_1, vec_2):
"""
Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.
Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray
Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_... |
def create_matrix_blocks(long_probs, matrix_block_indices):
"""
Parameters
----------
long_probs : 1D ndarray.
There should be one row per observation per available alternative. The
elements of the array will indicate the probability of the alternative
being the outcome associate... |
def calc_hessian(beta,
design,
alt_IDs,
rows_to_obs,
rows_to_alts,
utility_transform,
transform_first_deriv_c,
transform_first_deriv_v,
transform_deriv_alpha,
block_ma... |
def calc_fisher_info_matrix(beta,
design,
alt_IDs,
rows_to_obs,
rows_to_alts,
choice_vector,
utility_transform,
transform_fi... |
def calc_asymptotic_covariance(hessian, fisher_info_matrix):
"""
Parameters
----------
hessian : 2D ndarray.
It should have shape `(num_vars, num_vars)`. It is the matrix of second
derivatives of the total loss across the dataset, with respect to each
pair of coefficients being e... |
def calc_percentile_interval(bootstrap_replicates, conf_percentage):
"""
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 bootstr... |
def calc_bias_correction_bca(bootstrap_replicates, mle_estimate):
"""
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 p... |
def calc_acceleration_bca(jackknife_replicates):
"""
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 sa... |
def calc_lower_bca_percentile(alpha_percent, bias_correction, acceleration):
"""
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 `conf... |
def calc_upper_bca_percentile(alpha_percent, bias_correction, acceleration):
"""
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 `conf... |
def calc_bca_interval(bootstrap_replicates,
jackknife_replicates,
mle_params,
conf_percentage):
"""
Calculate 'bias-corrected and accelerated' bootstrap confidence intervals.
Parameters
----------
bootstrap_replicates : 2D ndarray.
... |
def extract_default_init_vals(orig_model_obj, mnl_point_series, num_params):
"""
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 ... |
def get_model_abbrev(model_obj):
"""
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 MN... |
def get_model_creation_kwargs(model_obj):
"""
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 ... |
def get_mnl_point_est(orig_model_obj,
new_df,
boot_id_col,
num_params,
mnl_spec,
mnl_names,
mnl_init_vals,
mnl_fit_kwargs):
"""
Calculates the MLE for the des... |
def retrieve_point_est(orig_model_obj,
new_df,
new_id_col,
num_params,
mnl_spec,
mnl_names,
mnl_init_vals,
mnl_fit_kwargs,
extract_init_... |
def ensure_valid_model_type(specified_type, model_type_list):
"""
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... |
def create_choice_model(data,
alt_id_col,
obs_id_col,
choice_col,
specification,
model_type,
intercept_ref_pos=None,
shape_ref_pos=None,
... |
def ensure_valid_nums_in_specification_cols(specification, dataframe):
"""
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
---------... |
def ensure_ref_position_is_valid(ref_position, num_alts, param_title):
"""
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
... |
def check_length_of_shape_or_intercept_names(name_list,
num_alts,
constrained_param,
list_title):
"""
Ensures that the length of the parameter names matches the number of
pa... |
def check_type_of_nest_spec_keys_and_values(nest_spec):
"""
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 nest... |
def check_for_empty_nests_in_nest_spec(nest_spec):
"""
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 li... |
def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements):
"""
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 ... |
def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements):
"""
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... |
def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids):
"""
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 tha... |
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids):
"""
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.
... |
def check_num_rows_of_parameter_array(param_array, correct_num_rows, title):
"""
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.sh... |
def check_type_and_size_of_param_list(param_list, expected_length):
"""
Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case.
"""
try:
assert isinstance(param_list, list)
assert len(param_list) == expected_length
except As... |
def check_type_of_param_list_elements(param_list):
"""
Ensures that all elements of param_list are ndarrays or None. Raises a
helpful ValueError if otherwise.
"""
try:
assert isinstance(param_list[0], np.ndarray)
assert all([(x is None or isinstance(x, np.ndarray))
... |
def check_num_columns_in_param_list_arrays(param_list):
"""
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.
"""
... |
def check_dimensional_equality_of_param_list_arrays(param_list):
"""
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
--------... |
def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars,
name_dict,
ind_var_names):
"""
Ensures that all of the variables listed in `mixing_vars` are present in
`ind_var_names`. Raises a helpful ValueError if... |
def ensure_all_alternatives_are_chosen(alt_id_col, choice_col, dataframe):
"""
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 colu... |
def compute_aic(model_object):
"""
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... |
def compute_bic(model_object):
"""
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 `mode... |
def get_mappings_for_fit(self, dense=False):
"""
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", "r... |
def _store_basic_estimation_results(self, results_dict):
"""
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.
... |
def _create_results_summary(self):
"""
Create the dataframe that displays the estimation results, and store
it on the model instance.
Returns
-------
None.
"""
# Make sure we have all attributes needed to create the results summary
needed_attribut... |
def _record_values_for_fit_summary_and_statsmodels(self):
"""
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
sto... |
def _create_fit_summary(self):
"""
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.
"""
# Make sure we have all attrib... |
def _store_inferential_results(self,
value_array,
index_names,
attribute_name,
series_name=None,
column_names=None):
"""
Store th... |
def _store_generic_inference_results(self,
results_dict,
all_params,
all_names):
"""
Store the model inference values that are common to all choice models.
This includes thi... |
def _store_optional_parameters(self,
optional_params,
name_list_attr,
default_name_str,
all_names,
all_params,
... |
def _adjust_inferential_results_for_parameter_constraints(self,
constraints):
"""
Ensure that parameters that were constrained during estimation do not
have any values showed for inferential results. After all, no inference
wa... |
def _check_result_dict_for_needed_keys(self, results_dict):
"""
Ensure that `results_dict` has the needed keys to store all the
estimation results. Raise a helpful ValueError otherwise.
"""
missing_cols = [x for x in needed_result_keys if x not in results_dict]
if missing... |
def _add_mixing_variable_names_to_individual_vars(self):
"""
Ensure that the model objects mixing variables are added to its list of
individual variables.
"""
assert isinstance(self.ind_var_names, list)
# Note that if one estimates a mixed logit model, then the mixing
... |
def store_fit_results(self, results_dict):
"""
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 foll... |
def fit_mle(self,
init_vals,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
*args):
"""
Parameters
----------
init... |
def print_summaries(self):
"""
Returns None. Will print the measures of fit and the estimation results
for the model.
"""
if hasattr(self, "fit_summary") and hasattr(self, "summary"):
print("\n")
print(self.fit_summary)
print("=" * 30)
... |
def conf_int(self, alpha=0.05, coefs=None, return_df=False):
"""
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 :... |
def get_statsmodels_summary(self,
title=None,
alpha=.05):
"""
Parameters
----------
title : str, or None, optional.
Will be the title of the returned summary. If None, the default
title is used.
... |
def check_param_list_validity(self, param_list):
"""
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 s... |
def predict(self,
data,
param_list=None,
return_long_probs=True,
choice_col=None,
num_draws=None,
seed=None):
"""
Parameters
----------
data : string or pandas dataframe.
If string... |
def to_pickle(self, filepath):
"""
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`... |
def prefix(*kinds):
"""Decorate a method as handling prefix tokens of the given kinds"""
def wrap(fn):
try:
fn.prefix_kinds.extend(kinds)
except AttributeError:
fn.prefix_kinds = list(kinds)
return fn
return wrap |
def infix(*kinds):
"""Decorate a method as handling infix tokens of the given kinds"""
def wrap(fn):
try:
fn.infix_kinds.extend(kinds)
except AttributeError:
fn.infix_kinds = list(kinds)
return fn
return wrap |
def attempt(self, *kinds):
"""Try to get the next token if it matches one of the kinds given,
otherwise returning None. If no kinds are given, any kind is
accepted."""
if self._error:
raise self._error
token = self.next_token
if not token:
return N... |
def require(self, *kinds):
"""Get the next token, raising an exception if it doesn't match one of
the given kinds, or the input ends. If no kinds are given, returns the
next token of any kind."""
token = self.attempt()
if not token:
raise SyntaxError('Unexpected end o... |
def local_symbol_table(imports=None, symbols=()):
"""Constructs a local symbol table.
Args:
imports (Optional[SymbolTable]): Shared symbol tables to import.
symbols (Optional[Iterable[Unicode]]): Initial local symbols to add.
Returns:
SymbolTable: A mutable local symbol table with ... |
def shared_symbol_table(name, version, symbols, imports=None):
"""Constructs a shared symbol table.
Args:
name (unicode): The name of the shared symbol table.
version (int): The version of the shared symbol table.
symbols (Iterable[unicode]): The symbols to associate with the table.
... |
def placeholder_symbol_table(name, version, max_id):
"""Constructs a shared symbol table that consists symbols that all have no known text.
This is generally used for cases where a shared symbol table is not available by the
application.
Args:
name (unicode): The name of the shared symbol tabl... |
def substitute_symbol_table(table, version, max_id):
"""Substitutes a given shared symbol table for another version.
* If the given table has **more** symbols than the requested substitute, then the generated
symbol table will be a subset of the given table.
* If the given table has **less** symbols ... |
def __add(self, token):
"""Unconditionally adds a token to the table."""
self.__symbols.append(token)
text = token.text
if text is not None and text not in self.__mapping:
self.__mapping[text] = token |
def __add_shared(self, original_token):
"""Adds a token, normalizing the SID and import reference to this table."""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, self.__import_location(sid))
self.__add(token)
return token |
def __add_import(self, original_token):
"""Adds a token, normalizing only the SID"""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, original_token.location)
self.__add(token)
return token |
def __add_text(self, text):
"""Adds the given Unicode text as a locally defined symbol."""
if text is not None and not isinstance(text, six.text_type):
raise TypeError('Local symbol definition must be a Unicode sequence or None: %r' % text)
sid = self.__new_sid()
location = N... |
def intern(self, text):
"""Interns the given Unicode sequence into the symbol table.
Note:
This operation is only valid on local symbol tables.
Args:
text (unicode): The target to intern.
Returns:
SymbolToken: The mapped symbol token which may alrea... |
def get(self, key, default=None):
"""Returns a token by text or local ID, with a default.
A given text image may be associated with more than one symbol ID. This will return the first definition.
Note:
User defined symbol IDs are always one-based. Symbol zero is a special symbol ... |
def register(self, table):
"""Adds a shared table to the catalog.
Args:
table (SymbolTable): A non-system, shared symbol table.
"""
if table.table_type.is_system:
raise ValueError('Cannot add system table to catalog')
if not table.table_type.is_shared:
... |
def resolve(self, name, version, max_id):
"""Resolves the table for a given name and version.
Args:
name (unicode): The name of the table to resolve.
version (int): The version of the table to resolve.
max_id (Optional[int]): The maximum ID of the table requested.
... |
def start_container(self):
"""Add a node to the tree that represents the start of a container.
Until end_container is called, any nodes added through add_scalar_value
or start_container will be children of this new node.
"""
self.__container_lengths.append(self.current_container... |
def end_container(self, header_buf):
"""Add a node containing the container's header to the current subtree.
This node will be added as the leftmost leaf of the subtree that was
started by the matching call to start_container.
Args:
header_buf (bytearray): bytearray contain... |
def add_scalar_value(self, value_buf):
"""Add a node to the tree containing a scalar value.
Args:
value_buf (bytearray): bytearray containing the scalar value.
"""
self.__container_node.add_child(_Node(value_buf))
self.current_container_length += len(value_buf) |
def drain(self):
"""Walk the BufferTree and reset it when finished.
Yields:
any: The current node's value.
"""
if self.__container_nodes:
raise ValueError("Attempted to drain without ending all containers.")
for buf in self.__depth_traverse(self.__root):
... |
def ion_equals(a, b, timestamps_instants_only=False):
"""Tests two objects for equivalence under the Ion data model.
There are three important cases:
* When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the
values of both operands are equiva... |
def _ion_equals(a, b, timestamp_comparison_func, recursive_comparison_func):
"""Compares a and b according to the description of the ion_equals method."""
for a, b in ((a, b), (b, a)): # Ensures that operand order does not matter.
if isinstance(a, _IonNature):
if isinstance(b, _IonNature):
... |
def _timestamps_eq(a, b):
"""Compares two timestamp operands for equivalence under the Ion data model."""
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
# Local offsets must be equivalent.
if (a.tzinfo is None) ^ (b.tzinfo is None):
return False
if a.... |
def _timestamp_instants_eq(a, b):
"""Compares two timestamp operands for point-in-time equivalence only."""
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
# datetime's __eq__ can't compare a None offset and a non-None offset. For these equivalence semantics, a None
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.