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

使用LIME Text Explainer解释Keras LSTM模型时遇索引错误求助

解决LIME与Keras LSTM二分类模型兼容的IndexError问题

问题场景

基于新闻标题搭建了Keras LSTM二分类情感模型,尝试用LIME TextExplainer解释模型预测逻辑。由于模型输入是填充后的序列而非原始字符串,自定义了预测函数,但运行时触发错误:

IndexError: index 1 is out of bounds for axis 1 with size 1

模型核心代码:

vocab_size = len(tokenizer.word_index) + 1
embedding_dim = 16
max_length = 3000
trunc_type='post'
padding_type='post'
oov_tok = "<OOV>"

training_sequences = tokenizer.texts_to_sequences(X_titles_tr) # 训练文本转序列
training_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)

testing_sequences = tokenizer.texts_to_sequences(X_titles_te) # 测试文本转序列
testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)

num_epochs = 4
model = tf.keras.Sequential([
        tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
        tf.keras.layers.MaxPooling1D(pool_size=2),
        tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
        tf.keras.layers.Dense(16, activation='relu'),
        tf.keras.layers.Dense(1, activation='sigmoid'),
    ])
model.compile(loss='binary_crossentropy',optimizer='adam', metrics=['AUC'])
model.fit(training_padded, y_train, epochs=num_epochs, validation_data=(testing_padded, y_test), verbose=1)

自定义的预测函数:

def my_predict_function(x):
    testing_sequences = tokenizer.texts_to_sequences(x)
    testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)
    return model.predict(testing_padded)

错误原因

LIME的explain_instance要求预测函数返回形状为(样本数, 类别数)的多类别概率矩阵。而当前二分类模型使用sigmoid激活输出,返回的是单维度数组(每个样本仅输出类别"good"的概率),形状为(样本数,1)。LIME尝试访问索引1的类别概率时,因数组仅1列导致越界。

解决方法

修改自定义预测函数,将单维度输出转换为两类别概率矩阵:类别"bad"的概率为1 - 模型输出概率,类别"good"的概率为模型原始输出,组合成(样本数,2)的矩阵。

修改后的预测函数:

import numpy as np

def my_predict_function(x):
    testing_sequences = tokenizer.texts_to_sequences(x)
    testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)
    pred_probs = model.predict(testing_padded)
    # 拼接两类别概率:第一列是bad的概率,第二列是good的概率
    return np.hstack([1 - pred_probs, pred_probs])

验证使用

调用LIME解释实例:

explainer = LimeTextExplainer(class_names=["bad", "good"])
exp = explainer.explain_instance("需要解释的新闻标题文本", my_predict_function, num_features=7)
# 在Notebook中可视化解释结果
exp.show_in_notebook(text=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:21:57