【问题标题】:How to use Shap with a LSTM neural network?如何将 Shap 与 LSTM 神经网络一起使用?
【发布时间】:2023-01-01 12:01:21
【问题描述】:

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

【问题讨论】:

    标签: python neural-network lstm recurrent-neural-network shap


    【解决方案1】:

    我和你一样的问题,请问现在有更新吗?谢谢

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-25
    • 2022-08-15
    • 2020-04-16
    • 2019-01-09
    • 2017-07-09
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    相关资源
    最近更新 更多