INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Shuffle an array in - place with a fixed seed. | def const_shuffle(arr, seed=23980):
""" Shuffle an array in-place with a fixed seed.
"""
old_seed = np.random.seed()
np.random.seed(seed)
np.random.shuffle(arr)
np.random.seed(old_seed) |
Estimate the SHAP values for a set of samples. | def shap_values(self, X, **kwargs):
""" Estimate the SHAP values for a set of samples.
Parameters
----------
X : numpy.array or pandas.DataFrame
A matrix of samples (# samples x # features) on which to explain the model's output.
Returns
-------
For ... |
Plots SHAP values for image inputs. | def image_plot(shap_values, x, labels=None, show=True, width=20, aspect=0.2, hspace=0.2, labelpad=None):
""" Plots SHAP values for image inputs.
"""
multi_output = True
if type(shap_values) != list:
multi_output = False
shap_values = [shap_values]
# make sure labels
if labels i... |
A leaf ordering is under - defined this picks the ordering that keeps nearby samples similar. | def hclust_ordering(X, metric="sqeuclidean"):
""" A leaf ordering is under-defined, this picks the ordering that keeps nearby samples similar.
"""
# compute a hierarchical clustering
D = sp.spatial.distance.pdist(X, metric)
cluster_matrix = sp.cluster.hierarchy.complete(D)
# merge clus... |
Order other features by how much interaction they seem to have with the feature at the given index. | def approximate_interactions(index, shap_values, X, feature_names=None):
""" Order other features by how much interaction they seem to have with the feature at the given index.
This just bins the SHAP values for a feature along that feature's value. For true Shapley interaction
index values for SHAP see th... |
Converts human agreement differences to numerical scores for coloring. | def _human_score_map(human_consensus, methods_attrs):
""" Converts human agreement differences to numerical scores for coloring.
"""
v = 1 - min(np.sum(np.abs(methods_attrs - human_consensus)) / (np.abs(human_consensus).sum() + 1), 1.0)
return v |
Draw the bars and separators. | def draw_bars(out_value, features, feature_type, width_separators, width_bar):
"""Draw the bars and separators."""
rectangle_list = []
separator_list = []
pre_val = out_value
for index, features in zip(range(len(features)), features):
if feature_type == 'positive':
left_boun... |
Format data. | def format_data(data):
"""Format data."""
# Format negative features
neg_features = np.array([[data['features'][x]['effect'],
data['features'][x]['value'],
data['featureNames'][x]]
for x in data['features'].keys() if da... |
Draw additive plot. | def draw_additive_plot(data, figsize, show, text_rotation=0):
"""Draw additive plot."""
# 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
base_value = data['b... |
Fails gracefully when various install steps don t work. | def try_run_setup(**kwargs):
""" Fails gracefully when various install steps don't work.
"""
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 t... |
The backward hook which computes the deeplift gradient for an nn. Module | def deeplift_grad(module, grad_input, grad_output):
"""The backward hook which computes the deeplift
gradient for an nn.Module
"""
# 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[m... |
The forward hook used to save interim tensors detached from the graph. Used to calculate the multipliers | def add_interim_values(module, input, output):
"""The forward hook used to save interim tensors, detached
from the graph. Used to calculate the multipliers
"""
try:
del module.x
except AttributeError:
pass
try:
del module.y
except AttributeError:
pass
modu... |
A forward hook which saves the tensor - attached to its graph. Used if we want to explain the interim outputs of a model | def get_target_input(module, input, output):
"""A forward hook which saves the tensor - attached to its graph.
Used if we want to explain the interim outputs of a model
"""
try:
del module.target_input
except AttributeError:
pass
setattr(module, 'target_input', input) |
Add handles to all non - container layers in the model. Recursively for non - container layers | def add_handles(self, model, forward_handle, backward_handle):
"""
Add handles to all non-container layers in the model.
Recursively for non-container layers
"""
handles_list = []
for child in model.children():
if 'nn.modules.container' in str(type(child)):
... |
Removes the x and y attributes which were added by the forward handles Recursively searches for non - container layers | def remove_attributes(self, model):
"""
Removes the x and y attributes which were added by the forward handles
Recursively searches for non-container layers
"""
for child in model.children():
if 'nn.modules.container' in str(type(child)):
self.remove_a... |
This gets a JSON dump of an XGBoost model while ensuring the features names are their indexes. | def get_xgboost_json(model):
""" This gets a JSON dump of an XGBoost model while ensuring the features names are their indexes.
"""
fnames = model.feature_names
model.feature_names = None
json_trees = model.get_dump(with_stats=True, dump_format="json")
model.feature_names = fnames
# this fi... |
This computes the expected value conditioned on the given label value. | def __dynamic_expected_value(self, y):
""" This computes the expected value conditioned on the given label value.
"""
return self.model.predict(self.data, np.ones(self.data.shape[0]) * y, output=self.model_output).mean(0) |
Estimate the SHAP values for a set of samples. | def shap_values(self, X, y=None, tree_limit=None, approximate=False):
""" Estimate the SHAP values for a set of samples.
Parameters
----------
X : numpy.array, pandas.DataFrame or catboost.Pool (for catboost)
A matrix of samples (# samples x # features) on which to explain t... |
Estimate the SHAP interaction values for a set of samples. | def shap_interaction_values(self, X, y=None, tree_limit=None):
""" Estimate the SHAP interaction values for a set of samples.
Parameters
----------
X : numpy.array, pandas.DataFrame or catboost.Pool (for catboost)
A matrix of samples (# samples x # features) on which to expl... |
A consistent interface to make predictions from this model. | def get_transform(self, model_output):
""" A consistent interface to make predictions from this model.
"""
if model_output == "margin":
transform = "identity"
elif model_output == "probability":
if self.tree_output == "log_odds":
transform = "logis... |
A consistent interface to make predictions from this model. | def predict(self, X, y=None, output="margin", tree_limit=None):
""" A consistent interface to make predictions from this model.
Parameters
----------
tree_limit : None (default) or int
Limit the number of trees used by the model. By default None means no use the limit of th... |
Return the values for the model applied to X. | def shap_values(self, X, nsamples=200, ranked_outputs=None, output_rank_order="max", rseed=None):
""" Return the values for the model applied to X.
Parameters
----------
X : list,
if framework == 'tensorflow': numpy.array, or pandas.DataFrame
if framework == 'pyt... |
Visualize the given SHAP values with an additive force layout. Parameters ---------- base_value: float This is the reference value that the feature contributions start from. For SHAP values it should be the value of explainer. expected_value. | 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 a... |
Save html plots to an output file. | def save_html(out_file, plot_html):
""" Save html plots to an output file.
"""
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.... |
Follows a set of ops assuming their value is False and find blocked Switch paths. | def tensors_blocked_by_false(ops):
""" Follows a set of ops assuming their value is False and find blocked Switch paths.
This is used to prune away parts of the model graph that are only used during the training
phase (like dropout, batch norm, etc.).
"""
blocked = []
def recurse(op):
i... |
Just decompose softmax into its components and recurse we can handle all of them: ) | def softmax(explainer, op, *grads):
""" Just decompose softmax into its components and recurse, we can handle all of them :)
We assume the 'axis' is the last dimension because the TF codebase swaps the 'axis' to
the last dimension before the softmax op if 'axis' is not already the last dimension.
We al... |
Return which inputs of this operation are variable ( i. e. depend on the model inputs ). | def _variable_inputs(self, op):
""" Return which inputs of this operation are variable (i.e. depend on the model inputs).
"""
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 sel... |
Get the SHAP value computation graph for a given model output. | def phi_symbolic(self, i):
""" Get the SHAP value computation graph for a given model output.
"""
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 t... |
Runs the model while also setting the learning phase flags to False. | def run(self, out, model_inputs, X):
""" Runs the model while also setting the learning phase flags to False.
"""
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) |
Passes a gradient op creation request to the correct handler. | def custom_grad(self, op, *grads):
""" Passes a gradient op creation request to the correct handler.
"""
return op_handlers[op.type](self, op, *grads) |
Use ssh to run the experiments on remote machines in parallel. | def run_remote_experiments(experiments, thread_hosts, rate_limit=10):
""" Use ssh to run the experiments on remote machines in parallel.
Parameters
----------
experiments : iterable
Output of shap.benchmark.experiments(...).
thread_hosts : list of strings
Each host has the format "... |
Create a SHAP monitoring plot. ( Note this function is preliminary and subject to change!! ) A SHAP monitoring plot is meant to display the behavior of a model over time. Often the shap_values given to this plot explain the loss of a model so changes in a feature s impact on the model s loss over time can help in monit... | def monitoring_plot(ind, shap_values, features, feature_names=None):
""" Create a SHAP monitoring plot.
(Note this function is preliminary and subject to change!!)
A SHAP monitoring plot is meant to display the behavior of a model
over time. Often the shap_values given to this plot explain the loss... |
Summarize a dataset with k mean samples weighted by the number of data points they each represent. | def kmeans(X, k, round_values=True):
""" Summarize a dataset with k mean samples weighted by the number of data points they
each represent.
Parameters
----------
X : numpy.array or pandas.DataFrame
Matrix of data samples to summarize (# samples x # features)
k : int
Number of m... |
Estimate the SHAP values for a set of samples. | def shap_values(self, X, **kwargs):
""" Estimate the SHAP values for a set of samples.
Parameters
----------
X : numpy.array or pandas.DataFrame or any scipy.sparse matrix
A matrix of samples (# samples x # features) on which to explain the model's output.
nsamples ... |
Use the SHAP values as an embedding which we project to 2D for visualization. | def embedding_plot(ind, shap_values, feature_names=None, method="pca", alpha=1.0, show=True):
""" Use the SHAP values as an embedding which we project to 2D for visualization.
Parameters
----------
ind : int or string
If this is an int it is the index of the feature to use to color the embeddin... |
Create a SHAP dependence plot colored by an interaction feature. | 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, title=None, xmin=None, xmax=None, show=True):
... |
Runtime transform = negate sort_order = 1 | def runtime(X, y, model_generator, method_name):
""" Runtime
transform = "negate"
sort_order = 1
"""
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, _ =... |
Local Accuracy transform = identity sort_order = 2 | def local_accuracy(X, y, model_generator, method_name):
""" Local Accuracy
transform = "identity"
sort_order = 2
"""
def score_map(true, pred):
""" Converts local accuracy from % of standard deviation to numerical scores for coloring.
"""
v = min(1.0, np.std(pred - true) / ... |
Keep Negative ( mask ) xlabel = Max fraction of features kept ylabel = Negative mean model output transform = negate sort_order = 5 | def keep_negative_mask(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Negative (mask)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 5
"""
return __run_measure(measures.keep_mask, X, y, model_generator, method_n... |
Keep Absolute ( mask ) xlabel = Max fraction of features kept ylabel = R^2 transform = identity sort_order = 6 | def keep_absolute_mask__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Absolute (mask)
xlabel = "Max fraction of features kept"
ylabel = "R^2"
transform = "identity"
sort_order = 6
"""
return __run_measure(measures.keep_mask, X, y, model_generator, method_name, 0, num_fcoun... |
Remove Positive ( mask ) xlabel = Max fraction of features removed ylabel = Negative mean model output transform = negate sort_order = 7 | def remove_positive_mask(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Positive (mask)
xlabel = "Max fraction of features removed"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 7
"""
return __run_measure(measures.remove_mask, X, y, model_generator,... |
Remove Absolute ( mask ) xlabel = Max fraction of features removed ylabel = 1 - R^2 transform = one_minus sort_order = 9 | def remove_absolute_mask__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (mask)
xlabel = "Max fraction of features removed"
ylabel = "1 - R^2"
transform = "one_minus"
sort_order = 9
"""
return __run_measure(measures.remove_mask, X, y, model_generator, method_name... |
Keep Negative ( resample ) xlabel = Max fraction of features kept ylabel = Negative mean model output transform = negate sort_order = 11 | def keep_negative_resample(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Negative (resample)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 11
"""
return __run_measure(measures.keep_resample, X, y, model_genera... |
Keep Absolute ( resample ) xlabel = Max fraction of features kept ylabel = R^2 transform = identity sort_order = 12 | def keep_absolute_resample__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Absolute (resample)
xlabel = "Max fraction of features kept"
ylabel = "R^2"
transform = "identity"
sort_order = 12
"""
return __run_measure(measures.keep_resample, X, y, model_generator, method_name,... |
Keep Absolute ( resample ) xlabel = Max fraction of features kept ylabel = ROC AUC transform = identity sort_order = 12 | def keep_absolute_resample__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Absolute (resample)
xlabel = "Max fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 12
"""
return __run_measure(measures.keep_resample, X, y, model_generator, met... |
Remove Positive ( resample ) xlabel = Max fraction of features removed ylabel = Negative mean model output transform = negate sort_order = 13 | def remove_positive_resample(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Positive (resample)
xlabel = "Max fraction of features removed"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 13
"""
return __run_measure(measures.remove_resample, X, y, mod... |
Remove Absolute ( resample ) xlabel = Max fraction of features removed ylabel = 1 - R^2 transform = one_minus sort_order = 15 | def remove_absolute_resample__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (resample)
xlabel = "Max fraction of features removed"
ylabel = "1 - R^2"
transform = "one_minus"
sort_order = 15
"""
return __run_measure(measures.remove_resample, X, y, model_generator... |
Remove Absolute ( resample ) xlabel = Max fraction of features removed ylabel = 1 - ROC AUC transform = one_minus sort_order = 15 | def remove_absolute_resample__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (resample)
xlabel = "Max fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 15
"""
return __run_measure(measures.remove_resample, X, y, model_... |
Keep Negative ( impute ) xlabel = Max fraction of features kept ylabel = Negative mean model output transform = negate sort_order = 17 | def keep_negative_impute(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Negative (impute)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 17
"""
return __run_measure(measures.keep_impute, X, y, model_generator, m... |
Keep Absolute ( impute ) xlabel = Max fraction of features kept ylabel = R^2 transform = identity sort_order = 18 | def keep_absolute_impute__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Absolute (impute)
xlabel = "Max fraction of features kept"
ylabel = "R^2"
transform = "identity"
sort_order = 18
"""
return __run_measure(measures.keep_impute, X, y, model_generator, method_name, 0, nu... |
Keep Absolute ( impute ) xlabel = Max fraction of features kept ylabel = ROC AUC transform = identity sort_order = 19 | def keep_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Absolute (impute)
xlabel = "Max fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 19
"""
return __run_measure(measures.keep_mask, X, y, model_generator, method_name... |
Remove Positive ( impute ) xlabel = Max fraction of features removed ylabel = Negative mean model output transform = negate sort_order = 7 | def remove_positive_impute(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Positive (impute)
xlabel = "Max fraction of features removed"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 7
"""
return __run_measure(measures.remove_impute, X, y, model_gene... |
Remove Absolute ( impute ) xlabel = Max fraction of features removed ylabel = 1 - R^2 transform = one_minus sort_order = 9 | def remove_absolute_impute__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (impute)
xlabel = "Max fraction of features removed"
ylabel = "1 - R^2"
transform = "one_minus"
sort_order = 9
"""
return __run_measure(measures.remove_impute, X, y, model_generator, metho... |
Remove Absolute ( impute ) xlabel = Max fraction of features removed ylabel = 1 - ROC AUC transform = one_minus sort_order = 9 | def remove_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (impute)
xlabel = "Max fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 9
"""
return __run_measure(measures.remove_mask, X, y, model_generator... |
Keep Negative ( retrain ) xlabel = Max fraction of features kept ylabel = Negative mean model output transform = negate sort_order = 7 | def keep_negative_retrain(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Negative (retrain)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 7
"""
return __run_measure(measures.keep_retrain, X, y, model_generator,... |
Remove Positive ( retrain ) xlabel = Max fraction of features removed ylabel = Negative mean model output transform = negate sort_order = 11 | def remove_positive_retrain(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Positive (retrain)
xlabel = "Max fraction of features removed"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 11
"""
return __run_measure(measures.remove_retrain, X, y, model_... |
Batch Remove Absolute ( retrain ) xlabel = Fraction of features removed ylabel = 1 - R^2 transform = one_minus sort_order = 13 | def batch_remove_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Batch Remove Absolute (retrain)
xlabel = "Fraction of features removed"
ylabel = "1 - R^2"
transform = "one_minus"
sort_order = 13
"""
return __run_batch_abs_metric(measures.batch_remove_retrain, X... |
Batch Keep Absolute ( retrain ) xlabel = Fraction of features kept ylabel = R^2 transform = identity sort_order = 13 | def batch_keep_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Batch Keep Absolute (retrain)
xlabel = "Fraction of features kept"
ylabel = "R^2"
transform = "identity"
sort_order = 13
"""
return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, model_gen... |
Batch Remove Absolute ( retrain ) xlabel = Fraction of features removed ylabel = 1 - ROC AUC transform = one_minus sort_order = 13 | def batch_remove_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Batch Remove Absolute (retrain)
xlabel = "Fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 13
"""
return __run_batch_abs_metric(measures.batch_remove_r... |
Batch Keep Absolute ( retrain ) xlabel = Fraction of features kept ylabel = ROC AUC transform = identity sort_order = 13 | def batch_keep_absolute_retrain__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Batch Keep Absolute (retrain)
xlabel = "Fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 13
"""
return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, ... |
Test an explanation method. | def __score_method(X, y, fcounts, model_generator, score_function, method_name, nreps=10, test_size=100, cache_dir="/tmp"):
""" Test an explanation method.
"""
old_seed = np.random.seed()
np.random.seed(3293)
# average the method scores over several train/test splits
method_reps = []
data... |
AND ( false/ false ) | def human_and_00(X, y, model_generator, method_name):
""" AND (false/false)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
... |
AND ( false/ true ) | def human_and_01(X, y, model_generator, method_name):
""" AND (false/true)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
... |
AND ( true/ true ) | def human_and_11(X, y, model_generator, method_name):
""" AND (true/true)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
... |
OR ( false/ false ) | def human_or_00(X, y, model_generator, method_name):
""" OR (false/false)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
w... |
OR ( false/ true ) | def human_or_01(X, y, model_generator, method_name):
""" OR (false/true)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
wh... |
OR ( true/ true ) | def human_or_11(X, y, model_generator, method_name):
""" OR (true/true)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
whe... |
XOR ( false/ false ) | def human_xor_00(X, y, model_generator, method_name):
""" XOR (false/false)
This tests how well a feature attribution method agrees with human intuition
for an eXclusive OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following fu... |
XOR ( false/ true ) | def human_xor_01(X, y, model_generator, method_name):
""" XOR (false/true)
This tests how well a feature attribution method agrees with human intuition
for an eXclusive OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following fun... |
XOR ( true/ true ) | def human_xor_11(X, y, model_generator, method_name):
""" XOR (true/true)
This tests how well a feature attribution method agrees with human intuition
for an eXclusive OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following func... |
SUM ( false/ false ) | def human_sum_00(X, y, model_generator, method_name):
""" SUM (false/false)
This tests how well a feature attribution method agrees with human intuition
for a SUM operation. This metric deals
specifically with the question of credit allocation for the following function
when all three inputs are tr... |
SUM ( false/ true ) | def human_sum_01(X, y, model_generator, method_name):
""" SUM (false/true)
This tests how well a feature attribution method agrees with human intuition
for a SUM operation. This metric deals
specifically with the question of credit allocation for the following function
when all three inputs are tru... |
SUM ( true/ true ) | def human_sum_11(X, y, model_generator, method_name):
""" SUM (true/true)
This tests how well a feature attribution method agrees with human intuition
for a SUM operation. This metric deals
specifically with the question of credit allocation for the following function
when all three inputs are true... |
Uses block matrix inversion identities to quickly estimate transforms. | def _estimate_transforms(self, nsamples):
""" Uses block matrix inversion identities to quickly estimate transforms.
After a bit of matrix math we can isolate a transform matrix (# features x # features)
that is independent of any sample we are explaining. It is the result of averaging over
... |
Estimate the SHAP values for a set of samples. | def shap_values(self, X):
""" Estimate the SHAP values for a set of samples.
Parameters
----------
X : numpy.array or pandas.DataFrame
A matrix of samples (# samples x # features) on which to explain the model's output.
Returns
-------
For models wit... |
4 - Layer Neural Network | def independentlinear60__ffnn():
""" 4-Layer Neural Network
"""
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='relu'))
... |
Lasso Regression | def cric__lasso():
""" Lasso Regression
"""
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 |
Ridge Regression | def cric__ridge():
""" Ridge Regression
"""
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 |
Decision Tree | def cric__decision_tree():
""" 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 |
Random Forest | def cric__random_forest():
""" 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 |
Gradient Boosted Trees | def cric__gbm():
""" Gradient Boosted Trees
"""
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
model = xgbo... |
Decision Tree | def human__decision_tree():
""" 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.DecisionTreeRegressor(max_d... |
Create a SHAP summary plot colored by feature values when they are provided. | 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=20, class_names=None):
"""Create a SHAP ... |
Kernel SHAP 1000 mean ref. color = red_blue_circle ( 0. 5 ) linestyle = solid | def kernel_shap_1000_meanref(model, data):
""" Kernel SHAP 1000 mean ref.
color = red_blue_circle(0.5)
linestyle = solid
"""
return lambda X: KernelExplainer(model.predict, kmeans(data, 1)).shap_values(X, nsamples=1000, l1_reg=0) |
IME 1000 color = red_blue_circle ( 0. 5 ) linestyle = dashed | def sampling_shap_1000(model, data):
""" IME 1000
color = red_blue_circle(0.5)
linestyle = dashed
"""
return lambda X: SamplingExplainer(model.predict, data).shap_values(X, nsamples=1000) |
TreeExplainer ( independent ) color = red_blue_circle ( 0 ) linestyle = dashed | def tree_shap_independent_200(model, data):
""" TreeExplainer (independent)
color = red_blue_circle(0)
linestyle = dashed
"""
data_subsample = sklearn.utils.resample(data, replace=False, n_samples=min(200, data.shape[0]), random_state=0)
return TreeExplainer(model, data_subsample, feature_depend... |
mean ( |TreeExplainer| ) color = red_blue_circle ( 0. 25 ) linestyle = solid | def mean_abs_tree_shap(model, data):
""" mean(|TreeExplainer|)
color = red_blue_circle(0.25)
linestyle = solid
"""
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:
... |
Saabas color = red_blue_circle ( 0 ) linestyle = dotted | def saabas(model, data):
""" Saabas
color = red_blue_circle(0)
linestyle = dotted
"""
return lambda X: TreeExplainer(model).shap_values(X, approximate=True) |
LIME Tabular 1000 | def lime_tabular_regression_1000(model, data):
""" LIME Tabular 1000
"""
return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000) |
Deep SHAP ( DeepLIFT ) | def deep_shap(model, data):
""" Deep SHAP (DeepLIFT)
"""
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:
return phi[0]
... |
Expected Gradients | def expected_gradients(model, data):
""" Expected Gradients
"""
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 phi[0]
e... |
Return approximate SHAP values for the model applied to the data given by X. | def shap_values(self, X, ranked_outputs=None, output_rank_order='max'):
""" Return approximate SHAP values for the model applied to the data given by X.
Parameters
----------
X : list,
if framework == 'tensorflow': numpy.array, or pandas.DataFrame
if framework ==... |
Returns dummy agent class for if PyTorch etc. is not installed. | def _agent_import_failed(trace):
"""Returns dummy agent class for if PyTorch etc. is not installed."""
class _AgentImportFailed(Trainer):
_name = "AgentImportFailed"
_default_config = with_common_config({})
def _setup(self, config):
raise ImportError(trace)
return _Age... |
Executes training. | 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,
checkpoint_freq=0,
checkpoint... |
Runs and blocks until all trials finish. | def run_experiments(experiments,
search_alg=None,
scheduler=None,
with_server=False,
server_port=TuneServer.DEFAULT_PORT,
verbose=2,
resume=False,
queue_trials=False,
... |
Flushes remaining output records in the output queues to plasma. | def _flush(self, close=False):
"""Flushes remaining output records in the output queues to plasma.
None is used as special type of record that is propagated from sources
to sink to notify that the end of data in a stream.
Attributes:
close (bool): A flag denoting whether t... |
Returns an appropriate preprocessor class for the given space. | def get_preprocessor(space):
"""Returns an appropriate preprocessor class for the given space."""
legacy_patch_shapes(space)
obs_shape = space.shape
if isinstance(space, gym.spaces.Discrete):
preprocessor = OneHotPreprocessor
elif obs_shape == ATARI_OBS_SHAPE:
preprocessor = Generi... |
Assigns shapes to spaces that don t have shapes. | def legacy_patch_shapes(space):
"""Assigns shapes to spaces that don't have shapes.
This is only needed for older gym versions that don't set shapes properly
for Tuple and Discrete spaces.
"""
if not hasattr(space, "shape"):
if isinstance(space, gym.spaces.Discrete):
space.shap... |
Downsamples images from ( 210 160 3 ) by the configured factor. | def transform(self, observation):
"""Downsamples images from (210, 160, 3) by the configured factor."""
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 42x... |
Get a new batch from the internal ring buffer. | def get(self):
"""Get a new batch from the internal ring buffer.
Returns:
buf: Data item saved from inqueue.
released: True if the item is now removed from the ring buffer.
"""
if self.ttl[self.idx] <= 0:
self.buffers[self.idx] = self.inqueue.get(timeou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.