Python 中的 SHAP 在使用 DeepExplainer 时是否支持 Keras 或 TensorFlow 模型?

Does SHAP in Python support Keras or TensorFlow models while using DeepExplainer?

我目前正在使用 SHAP 包来确定功能贡献。我已经将这种方法用于 XGBoost 和 RandomForest,并且效果非常好。由于我正在处理的数据是顺序数据,因此我尝试使用 LSTM 和 CNN 来训练模型,然后使用 SHAP 的 DeepExplainer 获得特征重要性;但它不断抛出错误。我得到的错误是:

AssertionError: <class 'keras.callbacks.History'> is not currently a supported model type!.

我也附上示例代码 (LSTM)。如果有人可以帮助我,那将会很有帮助。

shap.initjs()
model = Sequential()
model.add(LSTM(n_neurons, input_shape=(X.shape[1],X.shape[2]), return_sequences=True))
model.add(LSTM(n_neurons, return_sequences=False))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
h=model.fit(X, y, epochs=nb_epochs, batch_size=n_batch, verbose=1, shuffle=True)
background = X[np.random.choice(X.shape[0],100, replace=False)]
explainer = shap.DeepExplainer(h,background)

model.fit的返回值不是模型实例;相反,它是作为 keras.callbacks.History class 实例的训练历史(即损失和指标值等统计数据)。这就是为什么在将返回的 History 对象传递给 shap.DeepExplainer 时出现上述错误的原因。相反,您应该传递模型实例本身:

explainer = shap.DeepExplainer(model, background)