如何在LSTM神经网络中使用Shap?

4
我正在使用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层也会导致错误。

1个回答

0
你正在使用shap包中的错误模型,(KernelExplainer) 用于基本机器学习模型而不是深度模型。 你需要使用DeepExplainer 来处理LSTM和Keras中的任何网络。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接