Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def const_shuffle(arr, seed=23980):
old_seed = np.random.seed()
np.random.seed(seed)
np.random.shuffle(arr)
np.random.seed(old_seed) | [
" Shuffle an array in-place with a fixed seed.\n "
] |
Please provide a description of the function:def shap_values(self, X, **kwargs):
phi = None
if self.mimic_model_type == "xgboost":
if not str(type(X)).endswith("xgboost.core.DMatrix'>"):
X = xgboost.DMatrix(X)
phi = self.trees.predict(X, pred_contribs=Tr... | [
" Estimate the SHAP values for a set of samples.\n\n Parameters\n ----------\n X : numpy.array or pandas.DataFrame\n A matrix of samples (# samples x # features) on which to explain the model's output.\n\n Returns\n -------\n For a models with a single output thi... |
Please provide a description of the function:def image_plot(shap_values, x, labels=None, show=True, width=20, aspect=0.2, hspace=0.2, labelpad=None):
multi_output = True
if type(shap_values) != list:
multi_output = False
shap_values = [shap_values]
# make sure labels
if labels is ... | [
" Plots SHAP values for image inputs.\n "
] |
Please provide a description of the function:def hclust_ordering(X, metric="sqeuclidean"):
# compute a hierarchical clustering
D = sp.spatial.distance.pdist(X, metric)
cluster_matrix = sp.cluster.hierarchy.complete(D)
# merge clusters, rotating them to make the end points match as best we... | [
" A leaf ordering is under-defined, this picks the ordering that keeps nearby samples similar.\n "
] |
Please provide a description of the function:def approximate_interactions(index, shap_values, X, feature_names=None):
# convert from DataFrames if we got any
if str(type(X)).endswith("'pandas.core.frame.DataFrame'>"):
if feature_names is None:
feature_names = X.columns
X = X.va... | [
" Order other features by how much interaction they seem to have with the feature at the given index.\n\n This just bins the SHAP values for a feature along that feature's value. For true Shapley interaction\n index values for SHAP see the interaction_contribs option implemented in XGBoost.\n "
] |
Please provide a description of the function:def _human_score_map(human_consensus, methods_attrs):
v = 1 - min(np.sum(np.abs(methods_attrs - human_consensus)) / (np.abs(human_consensus).sum() + 1), 1.0)
return v | [
" Converts human agreement differences to numerical scores for coloring.\n "
] |
Please provide a description of the function:def draw_bars(out_value, features, feature_type, width_separators, width_bar):
rectangle_list = []
separator_list = []
pre_val = out_value
for index, features in zip(range(len(features)), features):
if feature_type == 'positive':
... | [
"Draw the bars and separators."
] |
Please provide a description of the function:def format_data(data):
# Format negative features
neg_features = np.array([[data['features'][x]['effect'],
data['features'][x]['value'],
data['featureNames'][x]]
for x in da... | [
"Format data."
] |
Please provide a description of the function:def draw_additive_plot(data, figsize, show, text_rotation=0):
# Turn off interactive plot
if show == False:
plt.ioff()
# Format data
neg_features, total_neg, pos_features, total_pos = format_data(data)
# Compute overall metrics
... | [
"Draw additive plot."
] |
Please provide a description of the function:def try_run_setup(**kwargs):
try:
run_setup(**kwargs)
except Exception as e:
print(str(e))
if "xgboost" in str(e).lower():
kwargs["test_xgboost"] = False
print("Couldn't install XGBoost for testing!")
... | [
" Fails gracefully when various install steps don't work.\n "
] |
Please provide a description of the function:def deeplift_grad(module, grad_input, grad_output):
# first, get the module type
module_type = module.__class__.__name__
# first, check the module is supported
if module_type in op_handler:
if op_handler[module_type].__name__ not in ['passthrough... | [
"The backward hook which computes the deeplift\n gradient for an nn.Module\n "
] |
Please provide a description of the function:def add_interim_values(module, input, output):
try:
del module.x
except AttributeError:
pass
try:
del module.y
except AttributeError:
pass
module_type = module.__class__.__name__
if module_type in op_handler:
... | [
"The forward hook used to save interim tensors, detached\n from the graph. Used to calculate the multipliers\n "
] |
Please provide a description of the function:def get_target_input(module, input, output):
try:
del module.target_input
except AttributeError:
pass
setattr(module, 'target_input', input) | [
"A forward hook which saves the tensor - attached to its graph.\n Used if we want to explain the interim outputs of a model\n "
] |
Please provide a description of the function:def add_handles(self, model, forward_handle, backward_handle):
handles_list = []
for child in model.children():
if 'nn.modules.container' in str(type(child)):
handles_list.extend(self.add_handles(child, forward_handle, bac... | [
"\n Add handles to all non-container layers in the model.\n Recursively for non-container layers\n "
] |
Please provide a description of the function:def get_xgboost_json(model):
fnames = model.feature_names
model.feature_names = None
json_trees = model.get_dump(with_stats=True, dump_format="json")
model.feature_names = fnames
# this fixes a bug where XGBoost can return invalid JSON
json_tree... | [
" This gets a JSON dump of an XGBoost model while ensuring the features names are their indexes.\n "
] |
Please provide a description of the function:def __dynamic_expected_value(self, y):
return self.model.predict(self.data, np.ones(self.data.shape[0]) * y, output=self.model_output).mean(0) | [
" This computes the expected value conditioned on the given label value.\n "
] |
Please provide a description of the function:def shap_values(self, X, y=None, tree_limit=None, approximate=False):
# see if we have a default tree_limit in place.
if tree_limit is None:
tree_limit = -1 if self.model.tree_limit is None else self.model.tree_limit
# shortcut ... | [
" Estimate the SHAP values for a set of samples.\n\n Parameters\n ----------\n X : numpy.array, pandas.DataFrame or catboost.Pool (for catboost)\n A matrix of samples (# samples x # features) on which to explain the model's output.\n\n y : numpy.array\n An array of ... |
Please provide a description of the function:def shap_interaction_values(self, X, y=None, tree_limit=None):
assert self.model_output == "margin", "Only model_output = \"margin\" is supported for SHAP interaction values right now!"
assert self.feature_dependence == "tree_path_dependent", "Only ... | [
" Estimate the SHAP interaction values for a set of samples.\n\n Parameters\n ----------\n X : numpy.array, pandas.DataFrame or catboost.Pool (for catboost)\n A matrix of samples (# samples x # features) on which to explain the model's output.\n\n y : numpy.array\n ... |
Please provide a description of the function:def get_transform(self, model_output):
if model_output == "margin":
transform = "identity"
elif model_output == "probability":
if self.tree_output == "log_odds":
transform = "logistic"
elif self.tre... | [
" A consistent interface to make predictions from this model.\n "
] |
Please provide a description of the function:def predict(self, X, y=None, output="margin", tree_limit=None):
# see if we have a default tree_limit in place.
if tree_limit is None:
tree_limit = -1 if self.tree_limit is None else self.tree_limit
# convert dataframes
... | [
" A consistent interface to make predictions from this model.\n\n Parameters\n ----------\n tree_limit : None (default) or int \n Limit the number of trees used by the model. By default None means no use the limit of the\n original model, and -1 means no limit.\n "
... |
Please provide a description of the function:def shap_values(self, X, nsamples=200, ranked_outputs=None, output_rank_order="max", rseed=None):
return self.explainer.shap_values(X, nsamples, ranked_outputs, output_rank_order, rseed) | [
" Return the values for the model applied to X.\n\n Parameters\n ----------\n X : list,\n if framework == 'tensorflow': numpy.array, or pandas.DataFrame\n if framework == 'pytorch': torch.tensor\n A tensor (or list of tensors) of samples (where X.shape[0] == # s... |
Please provide a description of the function:def force_plot(base_value, shap_values, features=None, feature_names=None, out_names=None, link="identity",
plot_cmap="RdBu", matplotlib=False, show=True, figsize=(20,3), ordering_keys=None, ordering_keys_time_format=None,
text_rotation=0):
... | [
" Visualize the given SHAP values with an additive force layout.\n \n Parameters\n ----------\n base_value : float\n This is the reference value that the feature contributions start from. For SHAP values it should\n be the value of explainer.expected_value.\n\n shap_values : numpy.array... |
Please provide a description of the function:def save_html(out_file, plot_html):
internal_open = False
if type(out_file) == str:
out_file = open(out_file, "w")
internal_open = True
out_file.write("<html><head><script>\n")
# dump the js code
bundle_path = os.path.join(os.path.s... | [
" Save html plots to an output file.\n "
] |
Please provide a description of the function:def tensors_blocked_by_false(ops):
blocked = []
def recurse(op):
if op.type == "Switch":
blocked.append(op.outputs[1]) # the true path is blocked since we assume the ops we trace are False
else:
for out in op.outputs:
... | [
" Follows a set of ops assuming their value is False and find blocked Switch paths.\n\n This is used to prune away parts of the model graph that are only used during the training\n phase (like dropout, batch norm, etc.).\n "
] |
Please provide a description of the function:def softmax(explainer, op, *grads):
in0 = op.inputs[0]
in0_max = tf.reduce_max(in0, axis=-1, keepdims=True, name="in0_max")
in0_centered = in0 - in0_max
evals = tf.exp(in0_centered, name="custom_exp")
rsum = tf.reduce_sum(evals, axis=-1, keepdims=Tru... | [
" Just decompose softmax into its components and recurse, we can handle all of them :)\n\n We assume the 'axis' is the last dimension because the TF codebase swaps the 'axis' to\n the last dimension before the softmax op if 'axis' is not already the last dimension.\n We also don't subtract the max before t... |
Please provide a description of the function:def _variable_inputs(self, op):
if op.name not in self._vinputs:
self._vinputs[op.name] = np.array([t.op in self.between_ops or t in self.model_inputs for t in op.inputs])
return self._vinputs[op.name] | [
" Return which inputs of this operation are variable (i.e. depend on the model inputs).\n "
] |
Please provide a description of the function:def phi_symbolic(self, i):
if self.phi_symbolics[i] is None:
# replace the gradients for all the non-linear activations
# we do this by hacking our way into the registry (TODO: find a public API for this if it exists)
reg... | [
" Get the SHAP value computation graph for a given model output.\n "
] |
Please provide a description of the function:def run(self, out, model_inputs, X):
feed_dict = dict(zip(model_inputs, X))
for t in self.learning_phase_flags:
feed_dict[t] = False
return self.session.run(out, feed_dict) | [
" Runs the model while also setting the learning phase flags to False.\n "
] |
Please provide a description of the function:def custom_grad(self, op, *grads):
return op_handlers[op.type](self, op, *grads) | [
" Passes a gradient op creation request to the correct handler.\n "
] |
Please provide a description of the function:def run_remote_experiments(experiments, thread_hosts, rate_limit=10):
global ssh_conn_per_min_limit
ssh_conn_per_min_limit = rate_limit
# first we kill any remaining workers from previous runs
# note we don't check_call because pkill kills our ssh ... | [
" Use ssh to run the experiments on remote machines in parallel.\n\n Parameters\n ----------\n experiments : iterable\n Output of shap.benchmark.experiments(...).\n\n thread_hosts : list of strings\n Each host has the format \"host_name:path_to_python_binary\" and can appear multiple times... |
Please provide a description of the function:def monitoring_plot(ind, shap_values, features, feature_names=None):
if str(type(features)).endswith("'pandas.core.frame.DataFrame'>"):
if feature_names is None:
feature_names = features.columns
features = features.values
... | [
" Create a SHAP monitoring plot.\n \n (Note this function is preliminary and subject to change!!)\n A SHAP monitoring plot is meant to display the behavior of a model\n over time. Often the shap_values given to this plot explain the loss\n of a model, so changes in a feature's impact on the model's l... |
Please provide a description of the function:def kmeans(X, k, round_values=True):
group_names = [str(i) for i in range(X.shape[1])]
if str(type(X)).endswith("'pandas.core.frame.DataFrame'>"):
group_names = X.columns
X = X.values
kmeans = KMeans(n_clusters=k, random_state=0).fit(X)
... | [
" Summarize a dataset with k mean samples weighted by the number of data points they\n each represent.\n\n Parameters\n ----------\n X : numpy.array or pandas.DataFrame\n Matrix of data samples to summarize (# samples x # features)\n\n k : int\n Number of means to use for approximation.... |
Please provide a description of the function:def shap_values(self, X, **kwargs):
# convert dataframes
if str(type(X)).endswith("pandas.core.series.Series'>"):
X = X.values
elif str(type(X)).endswith("'pandas.core.frame.DataFrame'>"):
if self.keep_index:
... | [
" Estimate the SHAP values for a set of samples.\n\n Parameters\n ----------\n X : numpy.array or pandas.DataFrame or any scipy.sparse matrix\n A matrix of samples (# samples x # features) on which to explain the model's output.\n\n nsamples : \"auto\" or int\n Numb... |
Please provide a description of the function:def embedding_plot(ind, shap_values, feature_names=None, method="pca", alpha=1.0, show=True):
if feature_names is None:
feature_names = [labels['FEATURE'] % str(i) for i in range(shap_values.shape[1])]
ind = convert_name(ind, shap_values, featu... | [
" Use the SHAP values as an embedding which we project to 2D for visualization.\n\n Parameters\n ----------\n ind : int or string\n If this is an int it is the index of the feature to use to color the embedding.\n If this is a string it is either the name of the feature, or it can have the\n ... |
Please provide a description of the function:def dependence_plot(ind, shap_values, features, feature_names=None, display_features=None,
interaction_index="auto",
color="#1E88E5", axis_color="#333333", cmap=colors.red_blue,
dot_size=16, x_jitter=0, alpha=1, tit... | [
" Create a SHAP dependence plot, colored by an interaction feature.\n\n Plots the value of the feature on the x-axis and the SHAP value of the same feature\n on the y-axis. This shows how the model depends on the given feature, and is like a\n richer extenstion of the classical parital dependence plots. Ve... |
Please provide a description of the function:def runtime(X, y, model_generator, method_name):
old_seed = np.random.seed()
np.random.seed(3293)
# average the method scores over several train/test splits
method_reps = []
for i in range(1):
X_train, X_test, y_train, _ = train_test_split(... | [
" Runtime\n transform = \"negate\"\n sort_order = 1\n "
] |
Please provide a description of the function:def local_accuracy(X, y, model_generator, method_name):
def score_map(true, pred):
v = min(1.0, np.std(pred - true) / (np.std(true) + 1e-8))
if v < 1e-6:
return 1.0
elif v < 0.01:
return 0.9
elif v <... | [
" Local Accuracy\n transform = \"identity\"\n sort_order = 2\n ",
" Converts local accuracy from % of standard deviation to numerical scores for coloring.\n "
] |
Please provide a description of the function:def keep_negative_mask(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_mask, X, y, model_generator, method_name, -1, num_fcounts, __mean_pred) | [
" Keep Negative (mask)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 5\n "
] |
Please provide a description of the function:def keep_absolute_mask__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_mask, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.r2_score) | [
" Keep Absolute (mask)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"R^2\"\n transform = \"identity\"\n sort_order = 6\n "
] |
Please provide a description of the function:def remove_positive_mask(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_mask, X, y, model_generator, method_name, 1, num_fcounts, __mean_pred) | [
" Remove Positive (mask)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 7\n "
] |
Please provide a description of the function:def remove_absolute_mask__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_mask, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.r2_score) | [
" Remove Absolute (mask)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"1 - R^2\"\n transform = \"one_minus\"\n sort_order = 9\n "
] |
Please provide a description of the function:def keep_negative_resample(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_resample, X, y, model_generator, method_name, -1, num_fcounts, __mean_pred) | [
" Keep Negative (resample)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 11\n "
] |
Please provide a description of the function:def keep_absolute_resample__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_resample, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.r2_score) | [
" Keep Absolute (resample)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"R^2\"\n transform = \"identity\"\n sort_order = 12\n "
] |
Please provide a description of the function:def keep_absolute_resample__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_resample, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.roc_auc_score) | [
" Keep Absolute (resample)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"ROC AUC\"\n transform = \"identity\"\n sort_order = 12\n "
] |
Please provide a description of the function:def remove_positive_resample(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_resample, X, y, model_generator, method_name, 1, num_fcounts, __mean_pred) | [
" Remove Positive (resample)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 13\n "
] |
Please provide a description of the function:def remove_absolute_resample__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_resample, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.r2_score) | [
" Remove Absolute (resample)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"1 - R^2\"\n transform = \"one_minus\"\n sort_order = 15\n "
] |
Please provide a description of the function:def remove_absolute_resample__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_resample, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.roc_auc_score) | [
" Remove Absolute (resample)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"1 - ROC AUC\"\n transform = \"one_minus\"\n sort_order = 15\n "
] |
Please provide a description of the function:def keep_negative_impute(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_impute, X, y, model_generator, method_name, -1, num_fcounts, __mean_pred) | [
" Keep Negative (impute)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 17\n "
] |
Please provide a description of the function:def keep_absolute_impute__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_impute, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.r2_score) | [
" Keep Absolute (impute)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"R^2\"\n transform = \"identity\"\n sort_order = 18\n "
] |
Please provide a description of the function:def keep_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_mask, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.roc_auc_score) | [
" Keep Absolute (impute)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"ROC AUC\"\n transform = \"identity\"\n sort_order = 19\n "
] |
Please provide a description of the function:def remove_positive_impute(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_impute, X, y, model_generator, method_name, 1, num_fcounts, __mean_pred) | [
" Remove Positive (impute)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 7\n "
] |
Please provide a description of the function:def remove_absolute_impute__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_impute, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.r2_score) | [
" Remove Absolute (impute)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"1 - R^2\"\n transform = \"one_minus\"\n sort_order = 9\n "
] |
Please provide a description of the function:def remove_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_mask, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.roc_auc_score) | [
" Remove Absolute (impute)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"1 - ROC AUC\"\n transform = \"one_minus\"\n sort_order = 9\n "
] |
Please provide a description of the function:def keep_negative_retrain(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_retrain, X, y, model_generator, method_name, -1, num_fcounts, __mean_pred) | [
" Keep Negative (retrain)\n xlabel = \"Max fraction of features kept\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 7\n "
] |
Please provide a description of the function:def remove_positive_retrain(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_retrain, X, y, model_generator, method_name, 1, num_fcounts, __mean_pred) | [
" Remove Positive (retrain)\n xlabel = \"Max fraction of features removed\"\n ylabel = \"Negative mean model output\"\n transform = \"negate\"\n sort_order = 11\n "
] |
Please provide a description of the function:def batch_remove_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_batch_abs_metric(measures.batch_remove_retrain, X, y, model_generator, method_name, sklearn.metrics.r2_score, num_fcounts) | [
" Batch Remove Absolute (retrain)\n xlabel = \"Fraction of features removed\"\n ylabel = \"1 - R^2\"\n transform = \"one_minus\"\n sort_order = 13\n "
] |
Please provide a description of the function:def batch_keep_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11):
return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, model_generator, method_name, sklearn.metrics.r2_score, num_fcounts) | [
" Batch Keep Absolute (retrain)\n xlabel = \"Fraction of features kept\"\n ylabel = \"R^2\"\n transform = \"identity\"\n sort_order = 13\n "
] |
Please provide a description of the function:def batch_remove_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_batch_abs_metric(measures.batch_remove_retrain, X, y, model_generator, method_name, sklearn.metrics.roc_auc_score, num_fcounts) | [
" Batch Remove Absolute (retrain)\n xlabel = \"Fraction of features removed\"\n ylabel = \"1 - ROC AUC\"\n transform = \"one_minus\"\n sort_order = 13\n "
] |
Please provide a description of the function:def batch_keep_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, model_generator, method_name, sklearn.metrics.roc_auc_score, num_fcounts) | [
" Batch Keep Absolute (retrain)\n xlabel = \"Fraction of features kept\"\n ylabel = \"ROC AUC\"\n transform = \"identity\"\n sort_order = 13\n "
] |
Please provide a description of the function:def __score_method(X, y, fcounts, model_generator, score_function, method_name, nreps=10, test_size=100, cache_dir="/tmp"):
old_seed = np.random.seed()
np.random.seed(3293)
# average the method scores over several train/test splits
method_reps = []
... | [
" Test an explanation method.\n "
] |
Please provide a description of the function:def human_and_00(X, y, model_generator, method_name):
return _human_and(X, model_generator, method_name, False, False) | [
" AND (false/false)\n\n This tests how well a feature attribution method agrees with human intuition\n for an AND operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2... |
Please provide a description of the function:def human_and_01(X, y, model_generator, method_name):
return _human_and(X, model_generator, method_name, False, True) | [
" AND (false/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for an AND operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 ... |
Please provide a description of the function:def human_and_11(X, y, model_generator, method_name):
return _human_and(X, model_generator, method_name, True, True) | [
" AND (true/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for an AND operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 p... |
Please provide a description of the function:def human_or_00(X, y, model_generator, method_name):
return _human_or(X, model_generator, method_name, False, False) | [
" OR (false/false)\n\n This tests how well a feature attribution method agrees with human intuition\n for an OR operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 p... |
Please provide a description of the function:def human_or_01(X, y, model_generator, method_name):
return _human_or(X, model_generator, method_name, False, True) | [
" OR (false/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for an OR operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 po... |
Please provide a description of the function:def human_or_11(X, y, model_generator, method_name):
return _human_or(X, model_generator, method_name, True, True) | [
" OR (true/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for an OR operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 poi... |
Please provide a description of the function:def human_xor_00(X, y, model_generator, method_name):
return _human_xor(X, model_generator, method_name, False, False) | [
" XOR (false/false)\n\n This tests how well a feature attribution method agrees with human intuition\n for an eXclusive OR operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if ... |
Please provide a description of the function:def human_xor_01(X, y, model_generator, method_name):
return _human_xor(X, model_generator, method_name, False, True) | [
" XOR (false/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for an eXclusive OR operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if f... |
Please provide a description of the function:def human_xor_11(X, y, model_generator, method_name):
return _human_xor(X, model_generator, method_name, True, True) | [
" XOR (true/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for an eXclusive OR operation combined with linear effects. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fe... |
Please provide a description of the function:def human_sum_00(X, y, model_generator, method_name):
return _human_sum(X, model_generator, method_name, False, False) | [
" SUM (false/false)\n\n This tests how well a feature attribution method agrees with human intuition\n for a SUM operation. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 points\n if cough: +2 poin... |
Please provide a description of the function:def human_sum_01(X, y, model_generator, method_name):
return _human_sum(X, model_generator, method_name, False, True) | [
" SUM (false/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for a SUM operation. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 points\n if cough: +2 point... |
Please provide a description of the function:def human_sum_11(X, y, model_generator, method_name):
return _human_sum(X, model_generator, method_name, True, True) | [
" SUM (true/true)\n\n This tests how well a feature attribution method agrees with human intuition\n for a SUM operation. This metric deals\n specifically with the question of credit allocation for the following function\n when all three inputs are true:\n if fever: +2 points\n if cough: +2 points... |
Please provide a description of the function:def _estimate_transforms(self, nsamples):
M = len(self.coef)
mean_transform = np.zeros((M,M))
x_transform = np.zeros((M,M))
inds = np.arange(M, dtype=np.int)
for _ in tqdm(range(nsamples), "Estimating transforms"):
... | [
" Uses block matrix inversion identities to quickly estimate transforms.\n\n After a bit of matrix math we can isolate a transform matrix (# features x # features)\n that is independent of any sample we are explaining. It is the result of averaging over\n all feature permutations, but we just u... |
Please provide a description of the function:def shap_values(self, X):
# convert dataframes
if str(type(X)).endswith("pandas.core.series.Series'>"):
X = X.values
elif str(type(X)).endswith("'pandas.core.frame.DataFrame'>"):
X = X.values
#assert str(type... | [
" Estimate the SHAP values for a set of samples.\n\n Parameters\n ----------\n X : numpy.array or pandas.DataFrame\n A matrix of samples (# samples x # features) on which to explain the model's output.\n\n Returns\n -------\n For models with a single output this ... |
Please provide a description of the function:def independentlinear60__ffnn():
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=60))
model.add(Dense(20, activation='relu'))
model.add(Dense(20, activation... | [
" 4-Layer Neural Network\n "
] |
Please provide a description of the function:def cric__lasso():
model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002)
# we want to explain the raw probability outputs of the trees
model.predict = lambda X: model.predict_proba(X)[:,1]
return model | [
" Lasso Regression\n "
] |
Please provide a description of the function:def cric__ridge():
model = sklearn.linear_model.LogisticRegression(penalty="l2")
# we want to explain the raw probability outputs of the trees
model.predict = lambda X: model.predict_proba(X)[:,1]
return model | [
" Ridge Regression\n "
] |
Please provide a description of the function:def cric__decision_tree():
model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)
# we want to explain the raw probability outputs of the trees
model.predict = lambda X: model.predict_proba(X)[:,1]
return model | [
" Decision Tree\n "
] |
Please provide a description of the function:def cric__random_forest():
model = sklearn.ensemble.RandomForestClassifier(100, random_state=0)
# we want to explain the raw probability outputs of the trees
model.predict = lambda X: model.predict_proba(X)[:,1]
return model | [
" Random Forest\n "
] |
Please provide a description of the function:def cric__gbm():
import xgboost
# max_depth and subsample match the params used for the full cric data in the paper
# learning_rate was set a bit higher to allow for faster runtimes
# n_estimators was chosen based on a train/test split of the data
m... | [
" Gradient Boosted Trees\n "
] |
Please provide a description of the function:def human__decision_tree():
# build data
N = 1000000
M = 3
X = np.zeros((N,M))
X.shape
y = np.zeros(N)
X[0, 0] = 1
y[0] = 8
X[1, 1] = 1
y[1] = 8
X[2, 0:2] = 1
y[2] = 4
# fit model
xor_model = sklearn.tree.Decisio... | [
" Decision Tree\n "
] |
Please provide a description of the function:def summary_plot(shap_values, features=None, feature_names=None, max_display=None, plot_type="dot",
color=None, axis_color="#333333", title=None, alpha=1, show=True, sort=True,
color_bar=True, auto_size_plot=True, layered_violin_max_num_bins... | [
"Create a SHAP summary plot, colored by feature values when they are provided.\n\n Parameters\n ----------\n shap_values : numpy.array\n Matrix of SHAP values (# samples x # features)\n\n features : numpy.array or pandas.DataFrame or list\n Matrix of feature values (# samples x # features)... |
Please provide a description of the function:def kernel_shap_1000_meanref(model, data):
return lambda X: KernelExplainer(model.predict, kmeans(data, 1)).shap_values(X, nsamples=1000, l1_reg=0) | [
" Kernel SHAP 1000 mean ref.\n color = red_blue_circle(0.5)\n linestyle = solid\n "
] |
Please provide a description of the function:def sampling_shap_1000(model, data):
return lambda X: SamplingExplainer(model.predict, data).shap_values(X, nsamples=1000) | [
" IME 1000\n color = red_blue_circle(0.5)\n linestyle = dashed\n "
] |
Please provide a description of the function:def tree_shap_independent_200(model, data):
data_subsample = sklearn.utils.resample(data, replace=False, n_samples=min(200, data.shape[0]), random_state=0)
return TreeExplainer(model, data_subsample, feature_dependence="independent").shap_values | [
" TreeExplainer (independent)\n color = red_blue_circle(0)\n linestyle = dashed\n "
] |
Please provide a description of the function:def mean_abs_tree_shap(model, data):
def f(X):
v = TreeExplainer(model).shap_values(X)
if isinstance(v, list):
return [np.tile(np.abs(sv).mean(0), (X.shape[0], 1)) for sv in v]
else:
return np.tile(np.abs(v).mean(0), (... | [
" mean(|TreeExplainer|)\n color = red_blue_circle(0.25)\n linestyle = solid\n "
] |
Please provide a description of the function:def saabas(model, data):
return lambda X: TreeExplainer(model).shap_values(X, approximate=True) | [
" Saabas\n color = red_blue_circle(0)\n linestyle = dotted\n "
] |
Please provide a description of the function:def lime_tabular_regression_1000(model, data):
return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000) | [
" LIME Tabular 1000\n "
] |
Please provide a description of the function:def deep_shap(model, data):
if isinstance(model, KerasWrap):
model = model.model
explainer = DeepExplainer(model, kmeans(data, 1).data)
def f(X):
phi = explainer.shap_values(X)
if type(phi) is list and len(phi) == 1:
retur... | [
" Deep SHAP (DeepLIFT)\n "
] |
Please provide a description of the function:def expected_gradients(model, data):
if isinstance(model, KerasWrap):
model = model.model
explainer = GradientExplainer(model, data)
def f(X):
phi = explainer.shap_values(X)
if type(phi) is list and len(phi) == 1:
return p... | [
" Expected Gradients\n "
] |
Please provide a description of the function:def shap_values(self, X, ranked_outputs=None, output_rank_order='max'):
return self.explainer.shap_values(X, ranked_outputs, output_rank_order) | [
" Return approximate SHAP values for the model applied to the data given by X.\n\n Parameters\n ----------\n X : list,\n if framework == 'tensorflow': numpy.array, or pandas.DataFrame\n if framework == 'pytorch': torch.tensor\n A tensor (or list of tensors) of s... |
Please provide a description of the function:def _agent_import_failed(trace):
class _AgentImportFailed(Trainer):
_name = "AgentImportFailed"
_default_config = with_common_config({})
def _setup(self, config):
raise ImportError(trace)
return _AgentImportFailed | [
"Returns dummy agent class for if PyTorch etc. is not installed."
] |
Please provide a description of the function:def run(run_or_experiment,
name=None,
stop=None,
config=None,
resources_per_trial=None,
num_samples=1,
local_dir=None,
upload_dir=None,
trial_name_creator=None,
loggers=None,
sync_function=None,
... | [
"Executes training.\n\n Args:\n run_or_experiment (function|class|str|Experiment): If\n function|class|str, this is the algorithm or model to train.\n This may refer to the name of a built-on algorithm\n (e.g. RLLib's DQN or PPO), a user-defined trainable\n func... |
Please provide a description of the function:def run_experiments(experiments,
search_alg=None,
scheduler=None,
with_server=False,
server_port=TuneServer.DEFAULT_PORT,
verbose=2,
resume=False,
... | [
"Runs and blocks until all trials finish.\n\n Examples:\n >>> experiment_spec = Experiment(\"experiment\", my_func)\n >>> run_experiments(experiments=experiment_spec)\n\n >>> experiment_spec = {\"experiment\": {\"run\": my_func}}\n >>> run_experiments(experiments=experiment_spec)\n\n ... |
Please provide a description of the function:def _flush(self, close=False):
for channel in self.forward_channels:
if close is True:
channel.queue.put_next(None)
channel.queue._flush_writes()
for channels in self.shuffle_channels:
for channel i... | [
"Flushes remaining output records in the output queues to plasma.\n\n None is used as special type of record that is propagated from sources\n to sink to notify that the end of data in a stream.\n\n Attributes:\n close (bool): A flag denoting whether the channel should be\n ... |
Please provide a description of the function:def get_preprocessor(space):
legacy_patch_shapes(space)
obs_shape = space.shape
if isinstance(space, gym.spaces.Discrete):
preprocessor = OneHotPreprocessor
elif obs_shape == ATARI_OBS_SHAPE:
preprocessor = GenericPixelPreprocessor
... | [
"Returns an appropriate preprocessor class for the given space."
] |
Please provide a description of the function:def legacy_patch_shapes(space):
if not hasattr(space, "shape"):
if isinstance(space, gym.spaces.Discrete):
space.shape = ()
elif isinstance(space, gym.spaces.Tuple):
shapes = []
for s in space.spaces:
... | [
"Assigns shapes to spaces that don't have shapes.\n\n This is only needed for older gym versions that don't set shapes properly\n for Tuple and Discrete spaces.\n "
] |
Please provide a description of the function:def transform(self, observation):
self.check_shape(observation)
scaled = observation[25:-25, :, :]
if self._dim < 84:
scaled = cv2.resize(scaled, (84, 84))
# OpenAI: Resize by half, then down to 42x42 (essentially mipmappi... | [
"Downsamples images from (210, 160, 3) by the configured factor."
] |
Please provide a description of the function:def get(self):
if self.ttl[self.idx] <= 0:
self.buffers[self.idx] = self.inqueue.get(timeout=300.0)
self.ttl[self.idx] = self.cur_max_ttl
if self.cur_max_ttl < self.max_ttl:
self.cur_max_ttl += 1
bu... | [
"Get a new batch from the internal ring buffer.\n\n Returns:\n buf: Data item saved from inqueue.\n released: True if the item is now removed from the ring buffer.\n "
] |
Please provide a description of the function:def train(self):
start = time.time()
result = self._train()
assert isinstance(result, dict), "_train() needs to return a dict."
# We do not modify internal state nor update this result if duplicate.
if RESULT_DUPLICATE in re... | [
"Runs one logical iteration of training.\n\n Subclasses should override ``_train()`` instead to return results.\n This class automatically fills the following fields in the result:\n\n `done` (bool): training is terminated. Filled only if not provided.\n\n `time_this_iter_s` (flo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.