Comments (5)
Thanks for the report. Would you be so kind and provide some sample data
with which we can reproduce this?
from shap.
Hey, you can use this dataset : https://www.kaggle.com/datasets/uciml/sms-spam-collection-dataset
from shap.
Thanks for pointing us to the dataset. I don't want to sound rude but we have so many issues that we really need to choose what we are working on, so for us it is best if we can reproduce a bug directly with the code provided in the bug description. If your time allows, it would be great if you could add loading and defining the dataset in your issue, so that we can reproduce it without looking up how to load data from kaggle + defining the data
variable in the correct way.
from shap.
You can use this code snippet :
# !pip install datasets
# !pip install shap
import datasets
import numpy as np
import pandas as pd
import scipy as sp
import torch
import transformers
import shap
# load the emotion dataset
dataset = datasets.load_dataset("emotion", split="train")
data = pd.DataFrame({"text": dataset["text"], "emotion": dataset["label"]})
# load the model and tokenizer
tokenizer = transformers.AutoTokenizer.from_pretrained(
"nateraw/bert-base-uncased-emotion", use_fast=True
)
model = transformers.AutoModelForSequenceClassification.from_pretrained(
"nateraw/bert-base-uncased-emotion"
).cuda()
labels = sorted(model.config.label2id, key=model.config.label2id.get)
# this defines an explicit python function that takes a list of strings and outputs scores for each class
def f(x):
tv = torch.tensor(
[
tokenizer.encode(v, padding="max_length", max_length=128, truncation=True)
for v in x
]
).cuda()
attention_mask = (tv != 0).type(torch.int64).cuda()
outputs = model(tv, attention_mask=attention_mask)[0].detach().cpu().numpy()
scores = (np.exp(outputs).T / np.exp(outputs).sum(-1)).T
val = sp.special.logit(scores)
return val
method = "custom tokenizer"
# build an explainer by passing a transformers tokenizer
if method == "transformers tokenizer":
explainer = shap.Explainer(f, tokenizer, output_names=labels)
# build an explainer by explicitly creating a masker
elif method == "default masker":
masker = shap.maskers.Text(r"\W") # this will create a basic whitespace tokenizer
explainer = shap.Explainer(f, masker, output_names=labels)
# build a fully custom tokenizer
elif method == "custom tokenizer":
import re
def custom_tokenizer(s, return_offsets_mapping=True):
"""Custom tokenizers conform to a subset of the transformers API."""
pos = 0
offset_ranges = []
input_ids = []
for m in re.finditer(r"\W", s):
start, end = m.span(0)
offset_ranges.append((pos, start))
input_ids.append(s[pos:start])
pos = end
if pos != len(s):
offset_ranges.append((pos, len(s)))
input_ids.append(s[pos:])
out = {}
out["input_ids"] = input_ids
if return_offsets_mapping:
out["offset_mapping"] = offset_ranges
return out
masker = shap.maskers.Text(custom_tokenizer)
explainer = shap.Explainer(f, masker, output_names=labels)
test1 = pd.Series(["hi"])
test2 = pd.Series(["hi, how are you?"])
shap_values = explainer(test1)
shap_values = explainer(test2)
Error shown for test1 :
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
[<ipython-input-17-ffa091ba3e9d>](https://localhost:8080/#) in <cell line: 79>()
77 test1 = pd.Series(["hi"])
78 # test2 = pd.Series(["hi, how are you?"])
---> 79 shap_values = explainer(test1)
80 # shap_values = explainer(test2)
81
4 frames
[/usr/local/lib/python3.10/dist-packages/numpy/core/_methods.py](https://localhost:8080/#) in _amax(a, axis, out, keepdims, initial, where)
39 def _amax(a, axis=None, out=None, keepdims=False,
40 initial=_NoValue, where=True):
---> 41 return umr_maximum(a, axis, None, out, keepdims, initial, where)
42
43 def _amin(a, axis=None, out=None, keepdims=False,
ValueError: zero-size array to reduction operation maximum which has no identity
from shap.
Related Issues (20)
- BUG: Pytorch DeepExplainer SHAP explanations do not sum up to the model's output HOT 3
- BUG:
- BUG: NaN values created flattened Beeswarms HOT 1
- BUG: XGBRFRegressor invalid number of trees error with shap>=0.42 HOT 3
- BUG: TreeSHAP Interventional explanations segmentation fault HOT 3
- BUG: Problem of dimension during KernelExplainer HOT 6
- ENH: Not showing nan values on Beeswarm or violin plots
- BUG: Discrepancy among SHAP beeswarm and Seaborn swarmplots
- Intrepreting Siamese Network using SHAP values HOT 5
- ENH: Support SeLU activations for Tensorflow DeepExplainer
- BUG: AssertionError: The SHAP explanations do not sum up to the model's output HOT 1
- [Meta-issue] deprecation tracker for upcoming releases HOT 2
- BUG: missing **dmatrix_props in shape_interaction module HOT 1
- BUG: TreeExplainer ignores "link" argument passed by the Explainer API HOT 1
- BUG: Shap value cannot be calculated according to NLP tutorial on the original website HOT 17
- Segmentation Fault on MacOS with pytorch > 2.2.0 HOT 4
- ENH: Faster import performance HOT 1
- ENH: Label dots in scatterplot according to classes and add a legend
- BUG: SHAP DeepExplainer cannot get SHAP values from TorchScript model HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from shap.