INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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. Parameters ---------- experiments : iterable Output of shap.benchmark.experiments(...). thread_hosts : list of strings Each host has the format "host_name:path_to_python_binary" and can appear multiple times in the ...
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 ...
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. Parameters ---------- X : numpy.array or pandas.DataFrame Matrix of data samples to summarize (# samples x # features) k : int Number of means to use for approximation. round_val...
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. 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 : "auto" or int Number of times to r...
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. Parameters ---------- ind : int or string If this is an int it is the index of the feature to use to color the embedding. If this is a string it is either the name of the feature, or it can have the form "...
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. Plots the value of the feature on the x-axis and the SHAP value of the same feature on the y-axis. This shows how the model depends on the given feature, and is like a richer extenstion of the classical parital dependence plots. Vertical dis...
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) 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 when all three inputs are true: if fever: +2 points ...
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) 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 when all three inputs are true: if fever: +2 points i...
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) 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 when all three inputs are true: if fever: +2 points if...
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) 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 when all three inputs are true: if fever: +2 points if...
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) 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 when all three inputs are true: if fever: +2 points if ...
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) 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 when all three inputs are true: if fever: +2 points if c...
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) 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 function when all three inputs are true: if fever: +2 po...
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) 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 function when all three inputs are true: if fever: +2 poi...
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) 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 function when all three inputs are true: if fever: +2 poin...
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/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: if fever: +2 points if cough: +2 points transf...
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 (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 true: if fever: +2 points if cough: +2 points trans...
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 (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: if fever: +2 points if cough: +2 points transfo...
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. 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 all feature permutations, but we just use a fixed...
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. 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 with a single output this returns a matri...
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. Parameters ---------- shap_values : numpy.array Matrix of SHAP values (# samples x # features) features : numpy.array or pandas.DataFrame or list Matrix of feature values (# samples x # features) or a feature...
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. Parameters ---------- X : list, if framework == 'tensorflow': numpy.array, or pandas.DataFrame if framework == 'pytorch': torch.tensor A tensor (or list of tensors) of samples (where...
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. Args: run_or_experiment (function|class|str|Experiment): If function|class|str, this is the algorithm or model to train. This may refer to the name of a built-on algorithm (e.g. RLLib's DQN or PPO), a user-defined trainable function or clas...
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. Examples: >>> experiment_spec = Experiment("experiment", my_func) >>> run_experiments(experiments=experiment_spec) >>> experiment_spec = {"experiment": {"run": my_func}} >>> run_experiments(experiments=experiment_spec) >>> run_exper...
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. 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 the channel should be also mar...
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. This is only needed for older gym versions that don't set shapes properly for Tuple and Discrete spaces.
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. Returns: buf: Data item saved from inqueue. released: True if the item is now removed from the 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...
Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the following fields in the result: `done` (bool): training is terminated. Filled only if not provided. `time_this_iter_s` (float): Time in...
def train(self): """Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the following fields in the result: `done` (bool): training is terminated. Filled only if not provided. `time_t...
Removes subdirectory within checkpoint_folder Parameters ---------- checkpoint_dir : path to checkpoint
def delete_checkpoint(self, checkpoint_dir): """Removes subdirectory within checkpoint_folder Parameters ---------- checkpoint_dir : path to checkpoint """ if os.path.isfile(checkpoint_dir): shutil.rmtree(os.path.dirname(checkpoint_dir)) else: ...
Saves the current model state to a checkpoint. Subclasses should override ``_save()`` instead to save state. This method dumps additional metadata alongside the saved path. Args: checkpoint_dir (str): Optional dir to place the checkpoint. Returns: Checkpoint pa...
def save(self, checkpoint_dir=None): """Saves the current model state to a checkpoint. Subclasses should override ``_save()`` instead to save state. This method dumps additional metadata alongside the saved path. Args: checkpoint_dir (str): Optional dir to place the checkpo...
Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object holding checkpoint data.
def save_to_object(self): """Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object holding checkpoint data. """ tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir) checkpoint...
Restores training state from a given model checkpoint. These checkpoints are returned from calls to save(). Subclasses should override ``_restore()`` instead to restore state. This method restores additional metadata saved with the checkpoint.
def restore(self, checkpoint_path): """Restores training state from a given model checkpoint. These checkpoints are returned from calls to save(). Subclasses should override ``_restore()`` instead to restore state. This method restores additional metadata saved with the checkpoint. ...
Restores training state from a checkpoint object. These checkpoints are returned from calls to save_to_object().
def restore_from_object(self, obj): """Restores training state from a checkpoint object. These checkpoints are returned from calls to save_to_object(). """ info = pickle.loads(obj) data = info["data"] tmpdir = tempfile.mkdtemp("restore_from_object", dir=self.logdir) ...
Exports model based on export_formats. Subclasses should override _export_model() to actually export model to local directory. Args: export_formats (list): List of formats that should be exported. export_dir (str): Optional dir to place the exported model. ...
def export_model(self, export_formats, export_dir=None): """Exports model based on export_formats. Subclasses should override _export_model() to actually export model to local directory. Args: export_formats (list): List of formats that should be exported. expor...
See Schedule.value
def value(self, t): """See Schedule.value""" fraction = min(float(t) / max(1, self.schedule_timesteps), 1.0) return self.initial_p + fraction * (self.final_p - self.initial_p)
Dump a whole json record into the given file. Overwrite the file if the overwrite flag set. Args: json_info (dict): Information dict to be dumped. json_file (str): File path to be dumped to. overwrite(boolean)
def dump_json(json_info, json_file, overwrite=True): """Dump a whole json record into the given file. Overwrite the file if the overwrite flag set. Args: json_info (dict): Information dict to be dumped. json_file (str): File path to be dumped to. overwrite(boolean) """ if o...
Parse a whole json record from the given file. Return None if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. Returns: A dict of json info.
def parse_json(json_file): """Parse a whole json record from the given file. Return None if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. Returns: A dict of json info. """ if not os.path.exists(json_file): return None...
Parse multiple json records from the given file. Seek to the offset as the start point before parsing if offset set. return empty list if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. offset (int): Initial seek position of the file. ...
def parse_multiple_json(json_file, offset=None): """Parse multiple json records from the given file. Seek to the offset as the start point before parsing if offset set. return empty list if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. ...
Convert the unicode element of the content to str recursively.
def unicode2str(content): """Convert the unicode element of the content to str recursively.""" if isinstance(content, dict): result = {} for key in content.keys(): result[unicode2str(key)] = unicode2str(content[key]) return result elif isinstance(content, list): r...
Computes the loss of the network.
def loss(self, xs, ys): """Computes the loss of the network.""" return float( self.sess.run( self.cross_entropy, feed_dict={ self.x: xs, self.y_: ys }))
Computes the gradients of the network.
def grad(self, xs, ys): """Computes the gradients of the network.""" return self.sess.run( self.cross_entropy_grads, feed_dict={ self.x: xs, self.y_: ys })
Creates the queue and preprocessing operations for the dataset. Args: data_path: Filename for cifar10 data. size: The number of images in the dataset. dataset: The dataset we are using. Returns: queue: A Tensorflow queue for extracting the images and labels.
def build_data(data_path, size, dataset): """Creates the queue and preprocessing operations for the dataset. Args: data_path: Filename for cifar10 data. size: The number of images in the dataset. dataset: The dataset we are using. Returns: queue: A Tensorflow queue for extr...
Create or update a Ray cluster.
def create_or_update(cluster_config_file, min_workers, max_workers, no_restart, restart_only, yes, cluster_name): """Create or update a Ray cluster.""" if restart_only or no_restart: assert restart_only != no_restart, "Cannot set both 'restart_only' " \ "and 'no_restart'...
Build CIFAR image and labels. Args: data_path: Filename for cifar10 data. batch_size: Input batch size. train: True if we are training and false if we are testing. Returns: images: Batches of images of size [batch_size, image_size, image_size, 3]. labels: Ba...
def build_input(data, batch_size, dataset, train): """Build CIFAR image and labels. Args: data_path: Filename for cifar10 data. batch_size: Input batch size. train: True if we are training and false if we are testing. Returns: images: Batches of images of size [...
Tear down the Ray cluster.
def teardown(cluster_config_file, yes, workers_only, cluster_name): """Tear down the Ray cluster.""" teardown_cluster(cluster_config_file, yes, workers_only, cluster_name)
Kills a random Ray node. For testing purposes only.
def kill_random_node(cluster_config_file, yes, cluster_name): """Kills a random Ray node. For testing purposes only.""" click.echo("Killed node with IP " + kill_node(cluster_config_file, yes, cluster_name))
Uploads and runs a script on the specified cluster. The script is automatically synced to the following location: os.path.join("~", os.path.basename(script))
def submit(cluster_config_file, docker, screen, tmux, stop, start, cluster_name, port_forward, script, script_args): """Uploads and runs a script on the specified cluster. The script is automatically synced to the following location: os.path.join("~", os.path.basename(script)) """ a...
Build a whole graph for the model.
def build_graph(self): """Build a whole graph for the model.""" self.global_step = tf.Variable(0, trainable=False) self._build_model() if self.mode == "train": self._build_train_op() else: # Additional initialization for the test network. self....
Build the core model within the graph.
def _build_model(self): """Build the core model within the graph.""" with tf.variable_scope("init"): x = self._conv("init_conv", self._images, 3, 3, 16, self._stride_arr(1)) strides = [1, 2, 2] activate_before_residual = [True, False, False] ...
Build training specific ops for the graph.
def _build_train_op(self): """Build training specific ops for the graph.""" num_gpus = self.hps.num_gpus if self.hps.num_gpus != 0 else 1 # The learning rate schedule is dependent on the number of gpus. boundaries = [int(20000 * i / np.sqrt(num_gpus)) for i in range(2, 5)] values...
Batch normalization.
def _batch_norm(self, name, x): """Batch normalization.""" with tf.variable_scope(name): params_shape = [x.get_shape()[-1]] beta = tf.get_variable( "beta", params_shape, tf.float32, initializer=tf.constant_initializ...
L2 weight decay loss.
def _decay(self): """L2 weight decay loss.""" costs = [] for var in tf.trainable_variables(): if var.op.name.find(r"DW") > 0: costs.append(tf.nn.l2_loss(var)) return tf.multiply(self.hps.weight_decay_rate, tf.add_n(costs))
Convolution.
def _conv(self, name, x, filter_size, in_filters, out_filters, strides): """Convolution.""" with tf.variable_scope(name): n = filter_size * filter_size * out_filters kernel = tf.get_variable( "DW", [filter_size, filter_size, in_filters, out_filters], ...