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

在Keras序列模型中使用Lime工具时出现“invalid 'dimnames' given for data frame”错误

解决LIME与Keras回归模型结合时的维度名错误

我之前在R里用LIME解释Keras回归模型的时候也碰到过一模一样的invalid 'dimnames' given for data frame错误,核心问题是LIME默认的预测逻辑更适配分类模型,而咱们的回归模型返回的预测格式和LIME的预期不匹配,加上PCA数据可能存在列名不明确的情况,导致维度名出问题。咱们一步步来修复:

1. 给PCA特征数据补全明确列名

PCA生成的特征矩阵默认列名可能是V1、V2这类模糊命名,作为data.frame传入LIME时,明确的列名能避免很多隐性问题:

# 给PCA特征设置清晰的列名
colnames(X_pca_scores_scaled) <- paste0("PC", 1:ncol(X_pca_scores_scaled))

2. 自定义适配回归模型的预测函数

Keras的predict()返回的是矩阵格式,而LIME需要带有明确列名的data.frame格式预测结果。咱们写一个专门适配的预测函数:

predict_keras_regression <- function(model, newdata) {
  # 确保输入为Keras要求的矩阵格式,生成预测值
  predictions <- predict(model, as.matrix(newdata))
  # 转换为LIME可识别的data.frame并指定列名
  as.data.frame(predictions, col.names = "prediction")
}

3. 使用自定义预测函数创建LIME解释器

初始化解释器时,指定咱们刚才写的预测函数,覆盖LIME的默认逻辑:

explainer <- lime(X_pca_scores_scaled, model, 
                  bin_continuous = TRUE, 
                  n_bins = 4,
                  predict_function = predict_keras_regression)

4. 调用explain时明确回归标签

因为回归模型只有一个输出,咱们直接指定要解释的标签为prediction:

explanation <- lime::explain(X_pca_scores_scaled, explainer, 
                             n_features = 10,
                             labels = "prediction")

# 再次尝试绘制特征重要性图
plot_features(explanation)

额外验证步骤

在运行完整流程前,可以先测试自定义预测函数是否正常工作:

# 取前5条数据测试预测函数
test_preds <- predict_keras_regression(model, X_pca_scores_scaled[1:5,])
print(test_preds)

如果输出是带有prediction列名的data.frame,说明函数没问题,再跑LIME流程就不会出现维度名错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:23:14