Skip to content

Repository files navigation

Path Explain

A repository for explaining feature importances and feature interactions in deep neural networks using path attribution methods.

This repository contains tools to interpret and explain machine learning models using Integrated Gradients and Expected Gradients. In addition, it contains code to explain interactions in deep networks using Integrated Hessians and Expected Hessians - methods that we introduced in our most recent paper: "Explaining Explanations: Axiomatic Feature Interactions for Deep Networks". If you use our work to explain your networks, please cite this paper.

@article{janizek2020explaining,
author = {Joseph D. Janizek and Pascal Sturmfels and Su-In Lee},
title = {Explaining Explanations: Axiomatic Feature Interactions for Deep Networks},
journal = {Journal of Machine Learning Research},
year = {2021},
volume = {22},
number = {104},
pages = {1-54},
url = {http://jmlr.org/papers/v22/20-1223.html}
}

This repository contains two important directories: the path_explain directory, which contains the packages used to interpret and explain machine learning models, and the examples directory, which contains many examples using the path_explain module to explain different models on different data types.

Installation

The easiest way to install this package is by using pip:

pip install path-explain

Alternatively, you can clone this repository to re-run and explore the examples provided.

Compatibility

This package was written to support TensorFlow 2.0 (in eager execution mode) with Python 3. We have no current plans to support earlier versions of TensorFlow or Python.

API

Although we don't yet have formal API documentation, the underlying code does a pretty good job at explaining the API. See the code for generating attributions and interactions to better understand what the arguments to these functions mean.

Examples

For a simple, quick example to get started using this repository, see the example_usage.ipynb notebook in the top-level directory of this repository. It gives an overview of the functionality provided by this repository. For more advanced examples, keep reading on.

Tabular Data using Expected Gradients and Expected Hessians

Our repository can easily be adapted to explain attributions and interactions learned on tabular data.

# other import statements...frompath_explainimportPathExplainerTF, scatter_plot, summary_plot### Code to train a model would go herex_train, y_train, x_test, y_test=datset()
model= ...
model.fit(x_train, y_train, ...)
###### Generating attributions using expected gradientsexplainer=PathExplainerTF(model)
attributions=explainer.attributions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###### Generating interactions using expected hessiansinteractions=explainer.interactions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###

Once we've generated attributions and interactions, we can use the provided plotting modules to help visualize them. First we plot a summary of the top features and their attribution values:

### First we need a list of strings denoting the name of each featurefeature_names= ...
###summary_plot(attributions=attributions,
feature_values=x_test,
feature_names=feature_names,
plot_top_k=10)

Heart Disease Summary Plot

Second, we plot an interaction our model has learned between maximum achieved heart rate and gender:

scatter_plot(attributions=attributions,
feature_values=x_test,
feature_index='max. achieved heart rate',
interactions=interactions,
color_by='is male',
feature_names=feature_names,
scale_y_ind=True)

Interaction: Heart Rate and Gender

The model used to generate the above interactions is a two layer neural network trained on the UCI Heart Disease Dataset. Interactions learned by this model were featured in our paper. To learn more about this particular model and the experimental setup, see the notebook used to train and explain the model.

Explaining an NLP model using Integrated Gradients and Integrated Hessians

As discussed in our paper, we can use Integrated Hessians to get interactions in language models. We explain a transformer from the HuggingFace Transformers Repository.

fromtransformersimportDistilBertTokenizer, TFDistilBertForSequenceClassification, \
DistilBertConfig, glue_convert_examples_to_features, \
glue_processors# This is a custom explainer to explain huggingface modelsfrompath_explainimportEmbeddingExplainerTF, text_plot, matrix_interaction_plot, bar_interaction_plottokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
config=DistilBertConfig.from_pretrained('distilbert-base-uncased', num_labels=num_labels)
model=TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', config=config)
### Some custom code to fine-tune the model on a sentiment analysis task...max_length=128data, info=tensorflow_datasets.load('glue/sst-2', with_info=True)
train_dataset=glue_convert_examples_to_features(data['train'],
tokenizer,
max_length,
'sst-2)
valid_dataset=glue_convert_examples_to_features(data['validation'],
tokenizer,
max_length,
'sst-2')
...
### we won't include the whole fine-tuning code. See the HuggingFace repository for more.### Here we define functions that represent two pieces of the model:### embedding and predictiondefembedding_model(batch_ids):
batch_embedding=model.distilbert.embeddings(batch_ids)
returnbatch_embeddingdefprediction_model(batch_embedding):
# Note: this isn't exactly the right way to use the attention mask.# It should actually indicate which words are real words. This# makes the coding easier however, and the output is fairly similar,# so it suffices for this tutorial.attention_mask=tf.ones(batch_embedding.shape[:2])
attention_mask=tf.cast(attention_mask, dtype=tf.float32)
head_mask= [None] *model.distilbert.num_hidden_layerstransformer_output=model.distilbert.transformer([batch_embedding, attention_mask, head_mask], training=False)[0]
pooled_output=transformer_output[:, 0]
pooled_output=model.pre_classifier(pooled_output)
logits=model.classifier(pooled_output)
returnlogits###### We need some data to explainforbatchinvalid_dataset.take(1):
batch_input=batch[0]
batch_ids=batch_input['input_ids']
batch_embedding=embedding_model(batch_ids)
baseline_ids=np.zeros((1, 128), dtype=np.int64)
baseline_embedding=embedding_model(baseline_ids)
###### We are finally ready to explain our modelexplainer=EmbeddingExplainerTF(prediction_model)
attributions=explainer.attributions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=32,
num_samples=256,
use_expectation=False,
output_indices=1)
###### For interactions, the hessian is rather large so we use a very small batch sizeinteractions=explainer.interactions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=1,
num_samples=256,
use_expectation=False,
output_indices=1)
###

We can plot the learned attributions and interactions as follows. First we plot the attributions:

### First we need to decode the tokens from the batch ids.batch_sentences= ...
### Doing so will depend on how you tokenized your model!text_plot(batch_sentences[0],
attributions[0],
include_legend=True)

Showing feature attributions in text

Then we plot the interactions:

bar_interaction_plot(interactions[0],
batch_sentences[0],
top_k=5)

Showing feature interactions in text

If you would rather plot the full matrix of attributions rather than the top interactions in a bar plot, our package also supports this. First we show the attributions:

text_plot(batch_sentences[1],
attributions[1],
include_legend=True)

Showing additional attributions

And then we show the full interaction matrix. Here we've zeroed out the diagonals so you can better see the off-diagonal terms.

matrix_interaction_plot(interaction_list[1],
token_list[1])

Showing the full matrix of feature interactions

This example - interpreting DistilBERT - was also featured in our paper. You can examine the setup more here. For more examples, see the examples directory in this repository.

About

A repository for explaining feature attributions and feature interactions in deep neural networks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - cothurn/path_explain: A repository for explaining feature attributions and feature interactions in deep neural networks. · GitHub
Skip to content

Repository files navigation

Path Explain

A repository for explaining feature importances and feature interactions in deep neural networks using path attribution methods.

This repository contains tools to interpret and explain machine learning models using Integrated Gradients and Expected Gradients. In addition, it contains code to explain interactions in deep networks using Integrated Hessians and Expected Hessians - methods that we introduced in our most recent paper: "Explaining Explanations: Axiomatic Feature Interactions for Deep Networks". If you use our work to explain your networks, please cite this paper.

@article{janizek2020explaining,
author = {Joseph D. Janizek and Pascal Sturmfels and Su-In Lee},
title = {Explaining Explanations: Axiomatic Feature Interactions for Deep Networks},
journal = {Journal of Machine Learning Research},
year = {2021},
volume = {22},
number = {104},
pages = {1-54},
url = {http://jmlr.org/papers/v22/20-1223.html}
}

This repository contains two important directories: the path_explain directory, which contains the packages used to interpret and explain machine learning models, and the examples directory, which contains many examples using the path_explain module to explain different models on different data types.

Installation

The easiest way to install this package is by using pip:

pip install path-explain

Alternatively, you can clone this repository to re-run and explore the examples provided.

Compatibility

This package was written to support TensorFlow 2.0 (in eager execution mode) with Python 3. We have no current plans to support earlier versions of TensorFlow or Python.

API

Although we don't yet have formal API documentation, the underlying code does a pretty good job at explaining the API. See the code for generating attributions and interactions to better understand what the arguments to these functions mean.

Examples

For a simple, quick example to get started using this repository, see the example_usage.ipynb notebook in the top-level directory of this repository. It gives an overview of the functionality provided by this repository. For more advanced examples, keep reading on.

Tabular Data using Expected Gradients and Expected Hessians

Our repository can easily be adapted to explain attributions and interactions learned on tabular data.

# other import statements...frompath_explainimportPathExplainerTF, scatter_plot, summary_plot### Code to train a model would go herex_train, y_train, x_test, y_test=datset()
model= ...
model.fit(x_train, y_train, ...)
###### Generating attributions using expected gradientsexplainer=PathExplainerTF(model)
attributions=explainer.attributions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###### Generating interactions using expected hessiansinteractions=explainer.interactions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###

Once we've generated attributions and interactions, we can use the provided plotting modules to help visualize them. First we plot a summary of the top features and their attribution values:

### First we need a list of strings denoting the name of each featurefeature_names= ...
###summary_plot(attributions=attributions,
feature_values=x_test,
feature_names=feature_names,
plot_top_k=10)

Heart Disease Summary Plot

Second, we plot an interaction our model has learned between maximum achieved heart rate and gender:

scatter_plot(attributions=attributions,
feature_values=x_test,
feature_index='max. achieved heart rate',
interactions=interactions,
color_by='is male',
feature_names=feature_names,
scale_y_ind=True)

Interaction: Heart Rate and Gender

The model used to generate the above interactions is a two layer neural network trained on the UCI Heart Disease Dataset. Interactions learned by this model were featured in our paper. To learn more about this particular model and the experimental setup, see the notebook used to train and explain the model.

Explaining an NLP model using Integrated Gradients and Integrated Hessians

As discussed in our paper, we can use Integrated Hessians to get interactions in language models. We explain a transformer from the HuggingFace Transformers Repository.

fromtransformersimportDistilBertTokenizer, TFDistilBertForSequenceClassification, \
DistilBertConfig, glue_convert_examples_to_features, \
glue_processors# This is a custom explainer to explain huggingface modelsfrompath_explainimportEmbeddingExplainerTF, text_plot, matrix_interaction_plot, bar_interaction_plottokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
config=DistilBertConfig.from_pretrained('distilbert-base-uncased', num_labels=num_labels)
model=TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', config=config)
### Some custom code to fine-tune the model on a sentiment analysis task...max_length=128data, info=tensorflow_datasets.load('glue/sst-2', with_info=True)
train_dataset=glue_convert_examples_to_features(data['train'],
tokenizer,
max_length,
'sst-2)
valid_dataset=glue_convert_examples_to_features(data['validation'],
tokenizer,
max_length,
'sst-2')
...
### we won't include the whole fine-tuning code. See the HuggingFace repository for more.### Here we define functions that represent two pieces of the model:### embedding and predictiondefembedding_model(batch_ids):
batch_embedding=model.distilbert.embeddings(batch_ids)
returnbatch_embeddingdefprediction_model(batch_embedding):
# Note: this isn't exactly the right way to use the attention mask.# It should actually indicate which words are real words. This# makes the coding easier however, and the output is fairly similar,# so it suffices for this tutorial.attention_mask=tf.ones(batch_embedding.shape[:2])
attention_mask=tf.cast(attention_mask, dtype=tf.float32)
head_mask= [None] *model.distilbert.num_hidden_layerstransformer_output=model.distilbert.transformer([batch_embedding, attention_mask, head_mask], training=False)[0]
pooled_output=transformer_output[:, 0]
pooled_output=model.pre_classifier(pooled_output)
logits=model.classifier(pooled_output)
returnlogits###### We need some data to explainforbatchinvalid_dataset.take(1):
batch_input=batch[0]
batch_ids=batch_input['input_ids']
batch_embedding=embedding_model(batch_ids)
baseline_ids=np.zeros((1, 128), dtype=np.int64)
baseline_embedding=embedding_model(baseline_ids)
###### We are finally ready to explain our modelexplainer=EmbeddingExplainerTF(prediction_model)
attributions=explainer.attributions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=32,
num_samples=256,
use_expectation=False,
output_indices=1)
###### For interactions, the hessian is rather large so we use a very small batch sizeinteractions=explainer.interactions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=1,
num_samples=256,
use_expectation=False,
output_indices=1)
###

We can plot the learned attributions and interactions as follows. First we plot the attributions:

### First we need to decode the tokens from the batch ids.batch_sentences= ...
### Doing so will depend on how you tokenized your model!text_plot(batch_sentences[0],
attributions[0],
include_legend=True)

Showing feature attributions in text

Then we plot the interactions:

bar_interaction_plot(interactions[0],
batch_sentences[0],
top_k=5)

Showing feature interactions in text

If you would rather plot the full matrix of attributions rather than the top interactions in a bar plot, our package also supports this. First we show the attributions:

text_plot(batch_sentences[1],
attributions[1],
include_legend=True)

Showing additional attributions

And then we show the full interaction matrix. Here we've zeroed out the diagonals so you can better see the off-diagonal terms.

matrix_interaction_plot(interaction_list[1],
token_list[1])

Showing the full matrix of feature interactions

This example - interpreting DistilBERT - was also featured in our paper. You can examine the setup more here. For more examples, see the examples directory in this repository.

About

A repository for explaining feature attributions and feature interactions in deep neural networks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - cothurn/path_explain: A repository for explaining feature attributions and feature interactions in deep neural networks. · GitHub
Skip to content

Repository files navigation

Path Explain

A repository for explaining feature importances and feature interactions in deep neural networks using path attribution methods.

This repository contains tools to interpret and explain machine learning models using Integrated Gradients and Expected Gradients. In addition, it contains code to explain interactions in deep networks using Integrated Hessians and Expected Hessians - methods that we introduced in our most recent paper: "Explaining Explanations: Axiomatic Feature Interactions for Deep Networks". If you use our work to explain your networks, please cite this paper.

@article{janizek2020explaining,
author = {Joseph D. Janizek and Pascal Sturmfels and Su-In Lee},
title = {Explaining Explanations: Axiomatic Feature Interactions for Deep Networks},
journal = {Journal of Machine Learning Research},
year = {2021},
volume = {22},
number = {104},
pages = {1-54},
url = {http://jmlr.org/papers/v22/20-1223.html}
}

This repository contains two important directories: the path_explain directory, which contains the packages used to interpret and explain machine learning models, and the examples directory, which contains many examples using the path_explain module to explain different models on different data types.

Installation

The easiest way to install this package is by using pip:

pip install path-explain

Alternatively, you can clone this repository to re-run and explore the examples provided.

Compatibility

This package was written to support TensorFlow 2.0 (in eager execution mode) with Python 3. We have no current plans to support earlier versions of TensorFlow or Python.

API

Although we don't yet have formal API documentation, the underlying code does a pretty good job at explaining the API. See the code for generating attributions and interactions to better understand what the arguments to these functions mean.

Examples

For a simple, quick example to get started using this repository, see the example_usage.ipynb notebook in the top-level directory of this repository. It gives an overview of the functionality provided by this repository. For more advanced examples, keep reading on.

Tabular Data using Expected Gradients and Expected Hessians

Our repository can easily be adapted to explain attributions and interactions learned on tabular data.

# other import statements...frompath_explainimportPathExplainerTF, scatter_plot, summary_plot### Code to train a model would go herex_train, y_train, x_test, y_test=datset()
model= ...
model.fit(x_train, y_train, ...)
###### Generating attributions using expected gradientsexplainer=PathExplainerTF(model)
attributions=explainer.attributions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###### Generating interactions using expected hessiansinteractions=explainer.interactions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###

Once we've generated attributions and interactions, we can use the provided plotting modules to help visualize them. First we plot a summary of the top features and their attribution values:

### First we need a list of strings denoting the name of each featurefeature_names= ...
###summary_plot(attributions=attributions,
feature_values=x_test,
feature_names=feature_names,
plot_top_k=10)

Heart Disease Summary Plot

Second, we plot an interaction our model has learned between maximum achieved heart rate and gender:

scatter_plot(attributions=attributions,
feature_values=x_test,
feature_index='max. achieved heart rate',
interactions=interactions,
color_by='is male',
feature_names=feature_names,
scale_y_ind=True)

Interaction: Heart Rate and Gender

The model used to generate the above interactions is a two layer neural network trained on the UCI Heart Disease Dataset. Interactions learned by this model were featured in our paper. To learn more about this particular model and the experimental setup, see the notebook used to train and explain the model.

Explaining an NLP model using Integrated Gradients and Integrated Hessians

As discussed in our paper, we can use Integrated Hessians to get interactions in language models. We explain a transformer from the HuggingFace Transformers Repository.

fromtransformersimportDistilBertTokenizer, TFDistilBertForSequenceClassification, \
DistilBertConfig, glue_convert_examples_to_features, \
glue_processors# This is a custom explainer to explain huggingface modelsfrompath_explainimportEmbeddingExplainerTF, text_plot, matrix_interaction_plot, bar_interaction_plottokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
config=DistilBertConfig.from_pretrained('distilbert-base-uncased', num_labels=num_labels)
model=TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', config=config)
### Some custom code to fine-tune the model on a sentiment analysis task...max_length=128data, info=tensorflow_datasets.load('glue/sst-2', with_info=True)
train_dataset=glue_convert_examples_to_features(data['train'],
tokenizer,
max_length,
'sst-2)
valid_dataset=glue_convert_examples_to_features(data['validation'],
tokenizer,
max_length,
'sst-2')
...
### we won't include the whole fine-tuning code. See the HuggingFace repository for more.### Here we define functions that represent two pieces of the model:### embedding and predictiondefembedding_model(batch_ids):
batch_embedding=model.distilbert.embeddings(batch_ids)
returnbatch_embeddingdefprediction_model(batch_embedding):
# Note: this isn't exactly the right way to use the attention mask.# It should actually indicate which words are real words. This# makes the coding easier however, and the output is fairly similar,# so it suffices for this tutorial.attention_mask=tf.ones(batch_embedding.shape[:2])
attention_mask=tf.cast(attention_mask, dtype=tf.float32)
head_mask= [None] *model.distilbert.num_hidden_layerstransformer_output=model.distilbert.transformer([batch_embedding, attention_mask, head_mask], training=False)[0]
pooled_output=transformer_output[:, 0]
pooled_output=model.pre_classifier(pooled_output)
logits=model.classifier(pooled_output)
returnlogits###### We need some data to explainforbatchinvalid_dataset.take(1):
batch_input=batch[0]
batch_ids=batch_input['input_ids']
batch_embedding=embedding_model(batch_ids)
baseline_ids=np.zeros((1, 128), dtype=np.int64)
baseline_embedding=embedding_model(baseline_ids)
###### We are finally ready to explain our modelexplainer=EmbeddingExplainerTF(prediction_model)
attributions=explainer.attributions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=32,
num_samples=256,
use_expectation=False,
output_indices=1)
###### For interactions, the hessian is rather large so we use a very small batch sizeinteractions=explainer.interactions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=1,
num_samples=256,
use_expectation=False,
output_indices=1)
###

We can plot the learned attributions and interactions as follows. First we plot the attributions:

### First we need to decode the tokens from the batch ids.batch_sentences= ...
### Doing so will depend on how you tokenized your model!text_plot(batch_sentences[0],
attributions[0],
include_legend=True)

Showing feature attributions in text

Then we plot the interactions:

bar_interaction_plot(interactions[0],
batch_sentences[0],
top_k=5)

Showing feature interactions in text

If you would rather plot the full matrix of attributions rather than the top interactions in a bar plot, our package also supports this. First we show the attributions:

text_plot(batch_sentences[1],
attributions[1],
include_legend=True)

Showing additional attributions

And then we show the full interaction matrix. Here we've zeroed out the diagonals so you can better see the off-diagonal terms.

matrix_interaction_plot(interaction_list[1],
token_list[1])

Showing the full matrix of feature interactions

This example - interpreting DistilBERT - was also featured in our paper. You can examine the setup more here. For more examples, see the examples directory in this repository.

About

A repository for explaining feature attributions and feature interactions in deep neural networks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - cothurn/path_explain: A repository for explaining feature attributions and feature interactions in deep neural networks. · GitHub
Skip to content

Repository files navigation

Path Explain

A repository for explaining feature importances and feature interactions in deep neural networks using path attribution methods.

This repository contains tools to interpret and explain machine learning models using Integrated Gradients and Expected Gradients. In addition, it contains code to explain interactions in deep networks using Integrated Hessians and Expected Hessians - methods that we introduced in our most recent paper: "Explaining Explanations: Axiomatic Feature Interactions for Deep Networks". If you use our work to explain your networks, please cite this paper.

@article{janizek2020explaining,
author = {Joseph D. Janizek and Pascal Sturmfels and Su-In Lee},
title = {Explaining Explanations: Axiomatic Feature Interactions for Deep Networks},
journal = {Journal of Machine Learning Research},
year = {2021},
volume = {22},
number = {104},
pages = {1-54},
url = {http://jmlr.org/papers/v22/20-1223.html}
}

This repository contains two important directories: the path_explain directory, which contains the packages used to interpret and explain machine learning models, and the examples directory, which contains many examples using the path_explain module to explain different models on different data types.

Installation

The easiest way to install this package is by using pip:

pip install path-explain

Alternatively, you can clone this repository to re-run and explore the examples provided.

Compatibility

This package was written to support TensorFlow 2.0 (in eager execution mode) with Python 3. We have no current plans to support earlier versions of TensorFlow or Python.

API

Although we don't yet have formal API documentation, the underlying code does a pretty good job at explaining the API. See the code for generating attributions and interactions to better understand what the arguments to these functions mean.

Examples

For a simple, quick example to get started using this repository, see the example_usage.ipynb notebook in the top-level directory of this repository. It gives an overview of the functionality provided by this repository. For more advanced examples, keep reading on.

Tabular Data using Expected Gradients and Expected Hessians

Our repository can easily be adapted to explain attributions and interactions learned on tabular data.

# other import statements...frompath_explainimportPathExplainerTF, scatter_plot, summary_plot### Code to train a model would go herex_train, y_train, x_test, y_test=datset()
model= ...
model.fit(x_train, y_train, ...)
###### Generating attributions using expected gradientsexplainer=PathExplainerTF(model)
attributions=explainer.attributions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###### Generating interactions using expected hessiansinteractions=explainer.interactions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###

Once we've generated attributions and interactions, we can use the provided plotting modules to help visualize them. First we plot a summary of the top features and their attribution values:

### First we need a list of strings denoting the name of each featurefeature_names= ...
###summary_plot(attributions=attributions,
feature_values=x_test,
feature_names=feature_names,
plot_top_k=10)

Heart Disease Summary Plot

Second, we plot an interaction our model has learned between maximum achieved heart rate and gender:

scatter_plot(attributions=attributions,
feature_values=x_test,
feature_index='max. achieved heart rate',
interactions=interactions,
color_by='is male',
feature_names=feature_names,
scale_y_ind=True)

Interaction: Heart Rate and Gender

The model used to generate the above interactions is a two layer neural network trained on the UCI Heart Disease Dataset. Interactions learned by this model were featured in our paper. To learn more about this particular model and the experimental setup, see the notebook used to train and explain the model.

Explaining an NLP model using Integrated Gradients and Integrated Hessians

As discussed in our paper, we can use Integrated Hessians to get interactions in language models. We explain a transformer from the HuggingFace Transformers Repository.

fromtransformersimportDistilBertTokenizer, TFDistilBertForSequenceClassification, \
DistilBertConfig, glue_convert_examples_to_features, \
glue_processors# This is a custom explainer to explain huggingface modelsfrompath_explainimportEmbeddingExplainerTF, text_plot, matrix_interaction_plot, bar_interaction_plottokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
config=DistilBertConfig.from_pretrained('distilbert-base-uncased', num_labels=num_labels)
model=TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', config=config)
### Some custom code to fine-tune the model on a sentiment analysis task...max_length=128data, info=tensorflow_datasets.load('glue/sst-2', with_info=True)
train_dataset=glue_convert_examples_to_features(data['train'],
tokenizer,
max_length,
'sst-2)
valid_dataset=glue_convert_examples_to_features(data['validation'],
tokenizer,
max_length,
'sst-2')
...
### we won't include the whole fine-tuning code. See the HuggingFace repository for more.### Here we define functions that represent two pieces of the model:### embedding and predictiondefembedding_model(batch_ids):
batch_embedding=model.distilbert.embeddings(batch_ids)
returnbatch_embeddingdefprediction_model(batch_embedding):
# Note: this isn't exactly the right way to use the attention mask.# It should actually indicate which words are real words. This# makes the coding easier however, and the output is fairly similar,# so it suffices for this tutorial.attention_mask=tf.ones(batch_embedding.shape[:2])
attention_mask=tf.cast(attention_mask, dtype=tf.float32)
head_mask= [None] *model.distilbert.num_hidden_layerstransformer_output=model.distilbert.transformer([batch_embedding, attention_mask, head_mask], training=False)[0]
pooled_output=transformer_output[:, 0]
pooled_output=model.pre_classifier(pooled_output)
logits=model.classifier(pooled_output)
returnlogits###### We need some data to explainforbatchinvalid_dataset.take(1):
batch_input=batch[0]
batch_ids=batch_input['input_ids']
batch_embedding=embedding_model(batch_ids)
baseline_ids=np.zeros((1, 128), dtype=np.int64)
baseline_embedding=embedding_model(baseline_ids)
###### We are finally ready to explain our modelexplainer=EmbeddingExplainerTF(prediction_model)
attributions=explainer.attributions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=32,
num_samples=256,
use_expectation=False,
output_indices=1)
###### For interactions, the hessian is rather large so we use a very small batch sizeinteractions=explainer.interactions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=1,
num_samples=256,
use_expectation=False,
output_indices=1)
###

We can plot the learned attributions and interactions as follows. First we plot the attributions:

### First we need to decode the tokens from the batch ids.batch_sentences= ...
### Doing so will depend on how you tokenized your model!text_plot(batch_sentences[0],
attributions[0],
include_legend=True)

Showing feature attributions in text

Then we plot the interactions:

bar_interaction_plot(interactions[0],
batch_sentences[0],
top_k=5)

Showing feature interactions in text

If you would rather plot the full matrix of attributions rather than the top interactions in a bar plot, our package also supports this. First we show the attributions:

text_plot(batch_sentences[1],
attributions[1],
include_legend=True)

Showing additional attributions

And then we show the full interaction matrix. Here we've zeroed out the diagonals so you can better see the off-diagonal terms.

matrix_interaction_plot(interaction_list[1],
token_list[1])

Showing the full matrix of feature interactions

This example - interpreting DistilBERT - was also featured in our paper. You can examine the setup more here. For more examples, see the examples directory in this repository.

About

A repository for explaining feature attributions and feature interactions in deep neural networks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - cothurn/path_explain: A repository for explaining feature attributions and feature interactions in deep neural networks. · GitHub
Skip to content

Repository files navigation

Path Explain

A repository for explaining feature importances and feature interactions in deep neural networks using path attribution methods.

This repository contains tools to interpret and explain machine learning models using Integrated Gradients and Expected Gradients. In addition, it contains code to explain interactions in deep networks using Integrated Hessians and Expected Hessians - methods that we introduced in our most recent paper: "Explaining Explanations: Axiomatic Feature Interactions for Deep Networks". If you use our work to explain your networks, please cite this paper.

@article{janizek2020explaining,
author = {Joseph D. Janizek and Pascal Sturmfels and Su-In Lee},
title = {Explaining Explanations: Axiomatic Feature Interactions for Deep Networks},
journal = {Journal of Machine Learning Research},
year = {2021},
volume = {22},
number = {104},
pages = {1-54},
url = {http://jmlr.org/papers/v22/20-1223.html}
}

This repository contains two important directories: the path_explain directory, which contains the packages used to interpret and explain machine learning models, and the examples directory, which contains many examples using the path_explain module to explain different models on different data types.

Installation

The easiest way to install this package is by using pip:

pip install path-explain

Alternatively, you can clone this repository to re-run and explore the examples provided.

Compatibility

This package was written to support TensorFlow 2.0 (in eager execution mode) with Python 3. We have no current plans to support earlier versions of TensorFlow or Python.

API

Although we don't yet have formal API documentation, the underlying code does a pretty good job at explaining the API. See the code for generating attributions and interactions to better understand what the arguments to these functions mean.

Examples

For a simple, quick example to get started using this repository, see the example_usage.ipynb notebook in the top-level directory of this repository. It gives an overview of the functionality provided by this repository. For more advanced examples, keep reading on.

Tabular Data using Expected Gradients and Expected Hessians

Our repository can easily be adapted to explain attributions and interactions learned on tabular data.

# other import statements...frompath_explainimportPathExplainerTF, scatter_plot, summary_plot### Code to train a model would go herex_train, y_train, x_test, y_test=datset()
model= ...
model.fit(x_train, y_train, ...)
###### Generating attributions using expected gradientsexplainer=PathExplainerTF(model)
attributions=explainer.attributions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###### Generating interactions using expected hessiansinteractions=explainer.interactions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###

Once we've generated attributions and interactions, we can use the provided plotting modules to help visualize them. First we plot a summary of the top features and their attribution values:

### First we need a list of strings denoting the name of each featurefeature_names= ...
###summary_plot(attributions=attributions,
feature_values=x_test,
feature_names=feature_names,
plot_top_k=10)

Heart Disease Summary Plot

Second, we plot an interaction our model has learned between maximum achieved heart rate and gender:

scatter_plot(attributions=attributions,
feature_values=x_test,
feature_index='max. achieved heart rate',
interactions=interactions,
color_by='is male',
feature_names=feature_names,
scale_y_ind=True)

Interaction: Heart Rate and Gender

The model used to generate the above interactions is a two layer neural network trained on the UCI Heart Disease Dataset. Interactions learned by this model were featured in our paper. To learn more about this particular model and the experimental setup, see the notebook used to train and explain the model.

Explaining an NLP model using Integrated Gradients and Integrated Hessians

As discussed in our paper, we can use Integrated Hessians to get interactions in language models. We explain a transformer from the HuggingFace Transformers Repository.

fromtransformersimportDistilBertTokenizer, TFDistilBertForSequenceClassification, \
DistilBertConfig, glue_convert_examples_to_features, \
glue_processors# This is a custom explainer to explain huggingface modelsfrompath_explainimportEmbeddingExplainerTF, text_plot, matrix_interaction_plot, bar_interaction_plottokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
config=DistilBertConfig.from_pretrained('distilbert-base-uncased', num_labels=num_labels)
model=TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', config=config)
### Some custom code to fine-tune the model on a sentiment analysis task...max_length=128data, info=tensorflow_datasets.load('glue/sst-2', with_info=True)
train_dataset=glue_convert_examples_to_features(data['train'],
tokenizer,
max_length,
'sst-2)
valid_dataset=glue_convert_examples_to_features(data['validation'],
tokenizer,
max_length,
'sst-2')
...
### we won't include the whole fine-tuning code. See the HuggingFace repository for more.### Here we define functions that represent two pieces of the model:### embedding and predictiondefembedding_model(batch_ids):
batch_embedding=model.distilbert.embeddings(batch_ids)
returnbatch_embeddingdefprediction_model(batch_embedding):
# Note: this isn't exactly the right way to use the attention mask.# It should actually indicate which words are real words. This# makes the coding easier however, and the output is fairly similar,# so it suffices for this tutorial.attention_mask=tf.ones(batch_embedding.shape[:2])
attention_mask=tf.cast(attention_mask, dtype=tf.float32)
head_mask= [None] *model.distilbert.num_hidden_layerstransformer_output=model.distilbert.transformer([batch_embedding, attention_mask, head_mask], training=False)[0]
pooled_output=transformer_output[:, 0]
pooled_output=model.pre_classifier(pooled_output)
logits=model.classifier(pooled_output)
returnlogits###### We need some data to explainforbatchinvalid_dataset.take(1):
batch_input=batch[0]
batch_ids=batch_input['input_ids']
batch_embedding=embedding_model(batch_ids)
baseline_ids=np.zeros((1, 128), dtype=np.int64)
baseline_embedding=embedding_model(baseline_ids)
###### We are finally ready to explain our modelexplainer=EmbeddingExplainerTF(prediction_model)
attributions=explainer.attributions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=32,
num_samples=256,
use_expectation=False,
output_indices=1)
###### For interactions, the hessian is rather large so we use a very small batch sizeinteractions=explainer.interactions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=1,
num_samples=256,
use_expectation=False,
output_indices=1)
###

We can plot the learned attributions and interactions as follows. First we plot the attributions:

### First we need to decode the tokens from the batch ids.batch_sentences= ...
### Doing so will depend on how you tokenized your model!text_plot(batch_sentences[0],
attributions[0],
include_legend=True)

Showing feature attributions in text

Then we plot the interactions:

bar_interaction_plot(interactions[0],
batch_sentences[0],
top_k=5)

Showing feature interactions in text

If you would rather plot the full matrix of attributions rather than the top interactions in a bar plot, our package also supports this. First we show the attributions:

text_plot(batch_sentences[1],
attributions[1],
include_legend=True)

Showing additional attributions

And then we show the full interaction matrix. Here we've zeroed out the diagonals so you can better see the off-diagonal terms.

matrix_interaction_plot(interaction_list[1],
token_list[1])

Showing the full matrix of feature interactions

This example - interpreting DistilBERT - was also featured in our paper. You can examine the setup more here. For more examples, see the examples directory in this repository.

About

A repository for explaining feature attributions and feature interactions in deep neural networks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - cothurn/path_explain: A repository for explaining feature attributions and feature interactions in deep neural networks. · GitHub
Skip to content

Repository files navigation

Path Explain

A repository for explaining feature importances and feature interactions in deep neural networks using path attribution methods.

This repository contains tools to interpret and explain machine learning models using Integrated Gradients and Expected Gradients. In addition, it contains code to explain interactions in deep networks using Integrated Hessians and Expected Hessians - methods that we introduced in our most recent paper: "Explaining Explanations: Axiomatic Feature Interactions for Deep Networks". If you use our work to explain your networks, please cite this paper.

@article{janizek2020explaining,
author = {Joseph D. Janizek and Pascal Sturmfels and Su-In Lee},
title = {Explaining Explanations: Axiomatic Feature Interactions for Deep Networks},
journal = {Journal of Machine Learning Research},
year = {2021},
volume = {22},
number = {104},
pages = {1-54},
url = {http://jmlr.org/papers/v22/20-1223.html}
}

This repository contains two important directories: the path_explain directory, which contains the packages used to interpret and explain machine learning models, and the examples directory, which contains many examples using the path_explain module to explain different models on different data types.

Installation

The easiest way to install this package is by using pip:

pip install path-explain

Alternatively, you can clone this repository to re-run and explore the examples provided.

Compatibility

This package was written to support TensorFlow 2.0 (in eager execution mode) with Python 3. We have no current plans to support earlier versions of TensorFlow or Python.

API

Although we don't yet have formal API documentation, the underlying code does a pretty good job at explaining the API. See the code for generating attributions and interactions to better understand what the arguments to these functions mean.

Examples

For a simple, quick example to get started using this repository, see the example_usage.ipynb notebook in the top-level directory of this repository. It gives an overview of the functionality provided by this repository. For more advanced examples, keep reading on.

Tabular Data using Expected Gradients and Expected Hessians

Our repository can easily be adapted to explain attributions and interactions learned on tabular data.

# other import statements...frompath_explainimportPathExplainerTF, scatter_plot, summary_plot### Code to train a model would go herex_train, y_train, x_test, y_test=datset()
model= ...
model.fit(x_train, y_train, ...)
###### Generating attributions using expected gradientsexplainer=PathExplainerTF(model)
attributions=explainer.attributions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###### Generating interactions using expected hessiansinteractions=explainer.interactions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###

Once we've generated attributions and interactions, we can use the provided plotting modules to help visualize them. First we plot a summary of the top features and their attribution values:

### First we need a list of strings denoting the name of each featurefeature_names= ...
###summary_plot(attributions=attributions,
feature_values=x_test,
feature_names=feature_names,
plot_top_k=10)

Heart Disease Summary Plot

Second, we plot an interaction our model has learned between maximum achieved heart rate and gender:

scatter_plot(attributions=attributions,
feature_values=x_test,
feature_index='max. achieved heart rate',
interactions=interactions,
color_by='is male',
feature_names=feature_names,
scale_y_ind=True)

Interaction: Heart Rate and Gender

The model used to generate the above interactions is a two layer neural network trained on the UCI Heart Disease Dataset. Interactions learned by this model were featured in our paper. To learn more about this particular model and the experimental setup, see the notebook used to train and explain the model.

Explaining an NLP model using Integrated Gradients and Integrated Hessians

As discussed in our paper, we can use Integrated Hessians to get interactions in language models. We explain a transformer from the HuggingFace Transformers Repository.

fromtransformersimportDistilBertTokenizer, TFDistilBertForSequenceClassification, \
DistilBertConfig, glue_convert_examples_to_features, \
glue_processors# This is a custom explainer to explain huggingface modelsfrompath_explainimportEmbeddingExplainerTF, text_plot, matrix_interaction_plot, bar_interaction_plottokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
config=DistilBertConfig.from_pretrained('distilbert-base-uncased', num_labels=num_labels)
model=TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', config=config)
### Some custom code to fine-tune the model on a sentiment analysis task...max_length=128data, info=tensorflow_datasets.load('glue/sst-2', with_info=True)
train_dataset=glue_convert_examples_to_features(data['train'],
tokenizer,
max_length,
'sst-2)
valid_dataset=glue_convert_examples_to_features(data['validation'],
tokenizer,
max_length,
'sst-2')
...
### we won't include the whole fine-tuning code. See the HuggingFace repository for more.### Here we define functions that represent two pieces of the model:### embedding and predictiondefembedding_model(batch_ids):
batch_embedding=model.distilbert.embeddings(batch_ids)
returnbatch_embeddingdefprediction_model(batch_embedding):
# Note: this isn't exactly the right way to use the attention mask.# It should actually indicate which words are real words. This# makes the coding easier however, and the output is fairly similar,# so it suffices for this tutorial.attention_mask=tf.ones(batch_embedding.shape[:2])
attention_mask=tf.cast(attention_mask, dtype=tf.float32)
head_mask= [None] *model.distilbert.num_hidden_layerstransformer_output=model.distilbert.transformer([batch_embedding, attention_mask, head_mask], training=False)[0]
pooled_output=transformer_output[:, 0]
pooled_output=model.pre_classifier(pooled_output)
logits=model.classifier(pooled_output)
returnlogits###### We need some data to explainforbatchinvalid_dataset.take(1):
batch_input=batch[0]
batch_ids=batch_input['input_ids']
batch_embedding=embedding_model(batch_ids)
baseline_ids=np.zeros((1, 128), dtype=np.int64)
baseline_embedding=embedding_model(baseline_ids)
###### We are finally ready to explain our modelexplainer=EmbeddingExplainerTF(prediction_model)
attributions=explainer.attributions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=32,
num_samples=256,
use_expectation=False,
output_indices=1)
###### For interactions, the hessian is rather large so we use a very small batch sizeinteractions=explainer.interactions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=1,
num_samples=256,
use_expectation=False,
output_indices=1)
###

We can plot the learned attributions and interactions as follows. First we plot the attributions:

### First we need to decode the tokens from the batch ids.batch_sentences= ...
### Doing so will depend on how you tokenized your model!text_plot(batch_sentences[0],
attributions[0],
include_legend=True)

Showing feature attributions in text

Then we plot the interactions:

bar_interaction_plot(interactions[0],
batch_sentences[0],
top_k=5)

Showing feature interactions in text

If you would rather plot the full matrix of attributions rather than the top interactions in a bar plot, our package also supports this. First we show the attributions:

text_plot(batch_sentences[1],
attributions[1],
include_legend=True)

Showing additional attributions

And then we show the full interaction matrix. Here we've zeroed out the diagonals so you can better see the off-diagonal terms.

matrix_interaction_plot(interaction_list[1],
token_list[1])

Showing the full matrix of feature interactions

This example - interpreting DistilBERT - was also featured in our paper. You can examine the setup more here. For more examples, see the examples directory in this repository.

About

A repository for explaining feature attributions and feature interactions in deep neural networks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - cothurn/path_explain: A repository for explaining feature attributions and feature interactions in deep neural networks. · GitHub
Skip to content

Repository files navigation

Path Explain

A repository for explaining feature importances and feature interactions in deep neural networks using path attribution methods.

This repository contains tools to interpret and explain machine learning models using Integrated Gradients and Expected Gradients. In addition, it contains code to explain interactions in deep networks using Integrated Hessians and Expected Hessians - methods that we introduced in our most recent paper: "Explaining Explanations: Axiomatic Feature Interactions for Deep Networks". If you use our work to explain your networks, please cite this paper.

@article{janizek2020explaining,
author = {Joseph D. Janizek and Pascal Sturmfels and Su-In Lee},
title = {Explaining Explanations: Axiomatic Feature Interactions for Deep Networks},
journal = {Journal of Machine Learning Research},
year = {2021},
volume = {22},
number = {104},
pages = {1-54},
url = {http://jmlr.org/papers/v22/20-1223.html}
}

This repository contains two important directories: the path_explain directory, which contains the packages used to interpret and explain machine learning models, and the examples directory, which contains many examples using the path_explain module to explain different models on different data types.

Installation

The easiest way to install this package is by using pip:

pip install path-explain

Alternatively, you can clone this repository to re-run and explore the examples provided.

Compatibility

This package was written to support TensorFlow 2.0 (in eager execution mode) with Python 3. We have no current plans to support earlier versions of TensorFlow or Python.

API

Although we don't yet have formal API documentation, the underlying code does a pretty good job at explaining the API. See the code for generating attributions and interactions to better understand what the arguments to these functions mean.

Examples

For a simple, quick example to get started using this repository, see the example_usage.ipynb notebook in the top-level directory of this repository. It gives an overview of the functionality provided by this repository. For more advanced examples, keep reading on.

Tabular Data using Expected Gradients and Expected Hessians

Our repository can easily be adapted to explain attributions and interactions learned on tabular data.

# other import statements...frompath_explainimportPathExplainerTF, scatter_plot, summary_plot### Code to train a model would go herex_train, y_train, x_test, y_test=datset()
model= ...
model.fit(x_train, y_train, ...)
###### Generating attributions using expected gradientsexplainer=PathExplainerTF(model)
attributions=explainer.attributions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###### Generating interactions using expected hessiansinteractions=explainer.interactions(inputs=x_test,
baseline=x_train,
batch_size=100,
num_samples=200,
use_expectation=True,
output_indices=0)
###

Once we've generated attributions and interactions, we can use the provided plotting modules to help visualize them. First we plot a summary of the top features and their attribution values:

### First we need a list of strings denoting the name of each featurefeature_names= ...
###summary_plot(attributions=attributions,
feature_values=x_test,
feature_names=feature_names,
plot_top_k=10)

Heart Disease Summary Plot

Second, we plot an interaction our model has learned between maximum achieved heart rate and gender:

scatter_plot(attributions=attributions,
feature_values=x_test,
feature_index='max. achieved heart rate',
interactions=interactions,
color_by='is male',
feature_names=feature_names,
scale_y_ind=True)

Interaction: Heart Rate and Gender

The model used to generate the above interactions is a two layer neural network trained on the UCI Heart Disease Dataset. Interactions learned by this model were featured in our paper. To learn more about this particular model and the experimental setup, see the notebook used to train and explain the model.

Explaining an NLP model using Integrated Gradients and Integrated Hessians

As discussed in our paper, we can use Integrated Hessians to get interactions in language models. We explain a transformer from the HuggingFace Transformers Repository.

fromtransformersimportDistilBertTokenizer, TFDistilBertForSequenceClassification, \
DistilBertConfig, glue_convert_examples_to_features, \
glue_processors# This is a custom explainer to explain huggingface modelsfrompath_explainimportEmbeddingExplainerTF, text_plot, matrix_interaction_plot, bar_interaction_plottokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
config=DistilBertConfig.from_pretrained('distilbert-base-uncased', num_labels=num_labels)
model=TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', config=config)
### Some custom code to fine-tune the model on a sentiment analysis task...max_length=128data, info=tensorflow_datasets.load('glue/sst-2', with_info=True)
train_dataset=glue_convert_examples_to_features(data['train'],
tokenizer,
max_length,
'sst-2)
valid_dataset=glue_convert_examples_to_features(data['validation'],
tokenizer,
max_length,
'sst-2')
...
### we won't include the whole fine-tuning code. See the HuggingFace repository for more.### Here we define functions that represent two pieces of the model:### embedding and predictiondefembedding_model(batch_ids):
batch_embedding=model.distilbert.embeddings(batch_ids)
returnbatch_embeddingdefprediction_model(batch_embedding):
# Note: this isn't exactly the right way to use the attention mask.# It should actually indicate which words are real words. This# makes the coding easier however, and the output is fairly similar,# so it suffices for this tutorial.attention_mask=tf.ones(batch_embedding.shape[:2])
attention_mask=tf.cast(attention_mask, dtype=tf.float32)
head_mask= [None] *model.distilbert.num_hidden_layerstransformer_output=model.distilbert.transformer([batch_embedding, attention_mask, head_mask], training=False)[0]
pooled_output=transformer_output[:, 0]
pooled_output=model.pre_classifier(pooled_output)
logits=model.classifier(pooled_output)
returnlogits###### We need some data to explainforbatchinvalid_dataset.take(1):
batch_input=batch[0]
batch_ids=batch_input['input_ids']
batch_embedding=embedding_model(batch_ids)
baseline_ids=np.zeros((1, 128), dtype=np.int64)
baseline_embedding=embedding_model(baseline_ids)
###### We are finally ready to explain our modelexplainer=EmbeddingExplainerTF(prediction_model)
attributions=explainer.attributions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=32,
num_samples=256,
use_expectation=False,
output_indices=1)
###### For interactions, the hessian is rather large so we use a very small batch sizeinteractions=explainer.interactions(inputs=batch_embedding,
baseline=baseline_embedding,
batch_size=1,
num_samples=256,
use_expectation=False,
output_indices=1)
###

We can plot the learned attributions and interactions as follows. First we plot the attributions:

### First we need to decode the tokens from the batch ids.batch_sentences= ...
### Doing so will depend on how you tokenized your model!text_plot(batch_sentences[0],
attributions[0],
include_legend=True)

Showing feature attributions in text

Then we plot the interactions:

bar_interaction_plot(interactions[0],
batch_sentences[0],
top_k=5)

Showing feature interactions in text

If you would rather plot the full matrix of attributions rather than the top interactions in a bar plot, our package also supports this. First we show the attributions:

text_plot(batch_sentences[1],
attributions[1],
include_legend=True)

Showing additional attributions

And then we show the full interaction matrix. Here we've zeroed out the diagonals so you can better see the off-diagonal terms.

matrix_interaction_plot(interaction_list[1],
token_list[1])

Showing the full matrix of feature interactions

This example - interpreting DistilBERT - was also featured in our paper. You can examine the setup more here. For more examples, see the examples directory in this repository.

About

A repository for explaining feature attributions and feature interactions in deep neural networks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages