You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用LimeTabularExplainer解释Keras Sequential模型?报错求助

问题背景

基于Adult表格数据集开展二分类任务,使用sklearn独热编码后构建Keras Sequential模型:

from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

model = Sequential([
  Dense(104, activation='relu', input_shape = [X_train_ohe.shape[1]]),
  Dropout(0.2),
  Dense(256, activation='relu'),
  Dropout(0.2),
  Dense(32, activation='relu'),  
  Dropout(0.2),
  Dense(1, activation='sigmoid')                     
])

model.compile(optimizer=RMSprop(learning_rate = 0.0001),
              loss='binary_crossentropy',
              metrics=['accuracy'])

history = model.fit(X_train_ohe, y_train, epochs=20, validation_data=(X_test_ohe, y_test))

test_loss, test_acc = model.evaluate(X_test_ohe,  y_test, verbose=2)
报错分析与解决方案

1. LimeTabularExplainer的IndexError

报错原因

模型用sigmoid输出单列概率(形状(n_samples, 1)),仅代表正类概率,但LIME二分类场景要求输入双列概率矩阵(形状(n_samples, 2)),即每一行包含[负类概率, 正类概率],访问索引1时自然触发越界错误。

解决方法

修正预测函数,将模型输出转换为LIME要求的格式:

import lime
import lime.lime_tabular
import numpy as np

feature_names = list(data_enc.columns[:-1])
class_names = list(np.unique(data.salary))

# 修正预测函数:把单列正类概率转为双列[负类概率, 正类概率]
def predict_fn(x):
    x_ohe = encoder.transform(x)
    pos_probs = model.predict(x_ohe, verbose=0)
    return np.hstack([1 - pos_probs, pos_probs])

# 注意:explainer训练数据用原始未独热的X_train,而非独热后的X_train_ohe
explainer = lime.lime_tabular.LimeTabularExplainer(
    X_train,
    feature_names=feature_names,
    class_names=class_names,
    categorical_features=categorical_features, 
    categorical_names=categorical_names, 
    kernel_width=3
)

# 解释原始测试样本(未独热的X_test[0])
exp = explainer.explain_instance(X_test[0], predict_fn, num_features=5)
exp.show_in_notebook(show_all=False)

2. RecurrentTabularExplainer的ValueError

报错原因

RecurrentTabularExplainer是为**循环神经网络(如LSTM/GRU)**设计的,要求输入为3维格式(样本数, 时间步, 特征数),但你的任务是普通表格二分类,输入是2维(样本数, 特征数),完全不适用该解释器。

解决方法

直接放弃使用RecurrentTabularExplainer,采用上述修正后的LimeTabularExplainer即可满足需求。


内容的提问来源于stack exchange,提问作者Kainsha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:52:29