Search is not available for this dataset
text stringlengths 75 104k |
|---|
def get_outputs(sym, params, in_shape, in_label):
""" Infer output shapes and return dictionary of output name to shape
:param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on
:param dic of (str, nd.NDArray) params:
:param list of tuple(int, ...) in_shape: list of all... |
def convert_weights_to_numpy(weights_dict):
"""Convert weights to numpy"""
return dict([(k.replace("arg:", "").replace("aux:", ""), v.asnumpy())
for k, v in weights_dict.items()]) |
def create_onnx_graph_proto(self, sym, params, in_shape, in_type, verbose=False):
"""Convert MXNet graph to ONNX graph
Parameters
----------
sym : :class:`~mxnet.symbol.Symbol`
MXNet symbol object
params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray`
... |
def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio,
num_example, batch_size, begin_epoch):
"""
Compute learning rate and refactor scheduler
Parameters:
---------
learning_rate : float
original learning rate
lr_refactor_step : comma separated str... |
def train_net(net, train_path, num_classes, batch_size,
data_shape, mean_pixels, resume, finetune, pretrained, epoch,
prefix, ctx, begin_epoch, end_epoch, frequent, learning_rate,
momentum, weight_decay, lr_refactor_step, lr_refactor_ratio,
freeze_layer_pattern=''... |
def imagenet50(display=False, resolution=224):
""" This is a set of 50 images representative of ImageNet images.
This dataset was collected by randomly finding a working ImageNet link and then pasting the
original ImageNet image into Google image search restricted to images licensed for reuse. A
simila... |
def boston(display=False):
""" Return the boston housing data in a nice package. """
d = sklearn.datasets.load_boston()
df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101
return df, d.target |
def imdb(display=False):
""" Return the clssic IMDB sentiment analysis training data in a nice package.
Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015
"""
with open(cache(github_data_url... |
def communitiesandcrime(display=False):
""" Predict total number of non-violent crimes per 100K popuation.
This dataset is from the classic UCI Machine Learning repository:
https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized
"""
raw_data = pd.read_csv(
cache(github_d... |
def diabetes(display=False):
""" Return the diabetes data in a nice package. """
d = sklearn.datasets.load_diabetes()
df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101
return df, d.target |
def iris(display=False):
""" Return the classic iris data in a nice package. """
d = sklearn.datasets.load_iris()
df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101
if display:
return df, [d.target_names[v] for v in d.target] # pylint: disable=E1101
else:
... |
def adult(display=False):
""" Return the Adult census data in a nice package. """
dtypes = [
("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"),
("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"),
("Occupation", "category"), ("Relati... |
def nhanesi(display=False):
""" A nicely packaged version of NHANES I data with surivival times as labels.
"""
X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv"))
y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"]
if display:
X_display = X.copy()
X_dis... |
def cric(display=False):
""" A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label.
"""
X = pd.read_csv(cache(github_data_url + "CRIC_time_4yearESRD_X.csv"))
y = np.loadtxt(cache(github_data_url + "CRIC_time_4yearESRD_y.csv"))
if display:
X_display = X.c... |
def corrgroups60(display=False):
""" Correlated Groups 60
A simulated dataset with tight correlations among distinct groups of features.
"""
# set a constant seed
old_seed = np.random.seed()
np.random.seed(0)
# generate dataset with known correlation
N = 1000
M = 60
# set... |
def independentlinear60(display=False):
""" A simulated dataset with tight correlations among distinct groups of features.
"""
# set a constant seed
old_seed = np.random.seed()
np.random.seed(0)
# generate dataset with known correlation
N = 1000
M = 60
# set one coefficent from ea... |
def rank():
""" Ranking datasets from lightgbm repository.
"""
rank_data_url = 'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/'
x_train, y_train = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.train'))
x_test, y_test = sklearn.datasets.load_svmligh... |
def batch_remove_retrain(nmask_train, nmask_test, X_train, y_train, X_test, y_test, attr_train, attr_test, model_generator, metric):
""" An approximation of holdout that only retraines the model once.
This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally
efficient... |
def keep_retrain(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state):
""" The model is retrained for each test sample with the non-important features set to a constant.
If you want to know how important a set of features is you can ask how the model would b... |
def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state):
""" The model is revaluated for each test sample with the non-important features set to their mean.
"""
X_train, X_test = to_array(X_train, X_test)
# how many features to mask
a... |
def keep_impute(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state):
""" The model is revaluated for each test sample with the non-important features set to an imputed value.
Note that the imputation is done using a multivariate normality assumption on the ... |
def keep_resample(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state):
""" The model is revaluated for each test sample with the non-important features set to resample background values.
""" # why broken? overwriting?
X_train, X_test = to_array(X_train,... |
def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):
""" The how well do the features plus a constant base rate sum up to the model output.
"""
X_train, X_test = to_array(X_train, X_test)
# how many features to mask
assert X_train.shape[1] == X_t... |
def const_rand(size, seed=23980):
""" Generate a random array with a fixed seed.
"""
old_seed = np.random.seed()
np.random.seed(seed)
out = np.random.rand(size)
np.random.seed(old_seed)
return out |
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) |
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 ... |
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... |
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... |
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... |
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 |
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... |
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... |
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... |
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... |
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... |
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... |
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) |
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)):
... |
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... |
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... |
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) |
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... |
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... |
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... |
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... |
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... |
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... |
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.... |
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... |
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... |
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... |
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... |
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) |
def custom_grad(self, op, *grads):
""" Passes a gradient op creation request to the correct handler.
"""
return op_handlers[op.type](self, op, *grads) |
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 "... |
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... |
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... |
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 ... |
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... |
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):
... |
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, _ =... |
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) / ... |
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... |
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... |
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,... |
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... |
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... |
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,... |
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... |
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... |
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... |
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_... |
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... |
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... |
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... |
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... |
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... |
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... |
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,... |
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_... |
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... |
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... |
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... |
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, ... |
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... |
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
... |
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
... |
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
... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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
... |
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... |
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'))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.