我正在与 keras 合作生成 LSTM 神经网络模型。我想使用 shap 包查找模型每个特征的 Shapley 值。当然,问题在于模型的 LSTM 层需要三维输入(样本、时间步长、特征),但 shap 包需要二维输入。无论如何,这个问题有解决办法吗?
下面我包含了一些重现该问题的代码。
import numpy as np
from random import uniform
N=100
#Initlaize input/output vectors
x1=[]
x2=[]
x3=[]
y1=[]
y2=[]
#Generate some data
for i in range(N):
x1.append(i/100+uniform(-.1,.1))
x2.append(i/100+uniform(-3,5)+2)
x3.append(uniform(0,1)/np.sqrt(i+1))
y1.append(2*x1[i]-.5*x2[i]+x3[i]+uniform(-1,1))
y2.append(x1[i]+3*x3[i]+5+uniform(-1,3))
#Convert lists to numpy arrays
x1=np.array(x1).reshape(N,1)
x2=np.array(x2).reshape(N,1)
x3=np.array(x3).reshape(N,1)
y1=np.array(y1).reshape(N,1)
#Assemble into matrices
X = np.hstack((x1, x2, x3))
Y = y1
# reshape input to be [samples, time steps, features]
X = np.reshape(X, (X.shape[0], 1, X.shape[1]))
#Import keras functions
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
#Lets build us a neural net!
model=Sequential()
model.add(LSTM(4, input_shape=(1,3)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam',run_eagerly=())
model.fit(X, Y, epochs=100, batch_size=10, verbose=2)
import shap
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
DE=shap.KernelExplainer(model.predict,shap.sample(X,10))
shap_values = DE.shap_values(X) # X is 3d numpy.ndarray
我尝试在 shap_values 函数中将 X 重塑为二维数组,但这不起作用。同样,尝试将二维数组输入 LSTM 层也会导致错误。