Fre*_*red 8 python keras tensorflow tf.keras shap
我尝试使用 DeepExplainer 计算 shap 值,但出现以下错误:
不再支持 keras,请改用 tf.keras
即使我使用 tf.keras?
KeyError Traceback(最近一次调用最后一次) 在 6 # ...或者直接传递张量 7 解释器 = shap.DeepExplainer((model.layers[0].input, model.layers[-1].output), 背景) 8 shap_values = 解释器.shap_values(X_test[1:5]) C:\ProgramData\Anaconda3\lib\site-packages\shap\explainers\_deep\__init__.py in shap_values(self、X、ranked_outputs、output_rank_order、check_additivity) 122 人被选为“顶级”。 [第 124 章] C:\ProgramData\Anaconda3\lib\site-packages\shap\explainers\_deep\deep_tf.py 在 shap_values(self、X、ranked_outputs、output_rank_order、check_additivity) [第 310 章] [第 311 章] [第 312 章] 313 第314章 C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py 中 __getitem__(self, key) 第2798章 第2799章 第2800章 第2801章 第2802章 get_loc 中的 C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py(self、key、method、tolerance) 第2646章 第2647章 第2648章 第2649章 第2650章 pandas\_libs\index.pyx 在 pandas._libs.index.IndexEngine.get_loc() pandas\_libs\index.pyx 在 pandas._libs.index.IndexEngine.get_loc() pandas\_libs\hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item() pandas\_libs\hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item() 密钥错误:0
import shap
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.keras.backend as K
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras import Sequential
from tensorflow.keras import optimizers
# print the JS visualization code to the notebook
shap.initjs()
X_train,X_test,Y_train,Y_test = train_test_split(*shap.datasets.iris(), test_size=0.2, random_state=0)
Y_train = to_categorical(Y_train, num_classes=3)
Y_test = to_categorical(Y_test, num_classes=3)
# Define baseline model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(8, input_dim=len(X_train.columns), activation="relu"))
model.add(tf.keras.layers.Dense(3, activation="softmax"))
model.summary()
# compile the model
model.compile(optimizer='adam', loss="categorical_crossentropy", metrics=['accuracy'])
hist = model.fit(X_train, Y_train, batch_size=5,epochs=200, verbose=0)
# select a set of background examples to take an expectation over
background = X_train.iloc[np.random.choice(X_train.shape[0], 100, replace=False)]
# Explain predictions of the model
#explainer = shap.DeepExplainer(model, background)
# ...or pass tensors directly
explainer = shap.DeepExplainer((model.layers[0].input, model.layers[-1].output), background)
shap_values = explainer.shap_values(X_test[1:5])
Run Code Online (Sandbox Code Playgroud)
Ser*_*nov 12
长话短说
tf.compat.v1.disable_v2_behavior()
在 TF 2.4+ 的顶部添加- 在 numpy 数组上计算 shap 值,而不是在 df 上计算
完全可重现的示例:
import shap
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
tf.compat.v1.disable_v2_behavior() # <-- HERE !
import tensorflow.keras.backend as K
from tensorflow.keras.utils import to_categorical
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras import Sequential
from tensorflow.keras import optimizers
print("SHAP version is:", shap.__version__)
print("Tensorflow version is:", tf.__version__)
X_train, X_test, Y_train, Y_test = train_test_split(
*shap.datasets.iris(), test_size=0.2, random_state=0
)
Y_train = to_categorical(Y_train, num_classes=3)
Y_test = to_categorical(Y_test, num_classes=3)
# Define baseline model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(8, input_dim=len(X_train.columns), activation="relu"))
model.add(tf.keras.layers.Dense(3, activation="softmax"))
# model.summary()
# compile the model
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
hist = model.fit(X_train, Y_train, batch_size=5, epochs=200, verbose=0)
# select a set of background examples to take an expectation over
background = X_train.iloc[np.random.choice(X_train.shape[0], 100, replace=False)]
explainer = shap.DeepExplainer(
(model.layers[0].input, model.layers[-1].output), background
)
shap_values = explainer.shap_values(X_test[:3].values) # <-- HERE !
# print the JS visualization code to the notebook
shap.initjs()
shap.force_plot(
explainer.expected_value[0], shap_values[0][0], feature_names=X_train.columns
)
Run Code Online (Sandbox Code Playgroud)
SHAP version is: 0.39.0
Tensorflow version is: 2.5.0
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10993 次 |
最近记录: |