首页 > 解决方案 > 使用 LIME 预测 R 中的 logit 模型?

问题描述

所以我试图使用 LIME 来理解 R 中 logit 模型的预测。我知道我不需要,但我试图说明它对一个可以简单理解为起点的模型的作用一个演讲。

但是我在让这个工作时遇到了麻烦。我确信这是由于 model.predict 方面,但我的几个解决方案没有奏效。

基本上这是我想做的:

model.logit <- glm(formula = formula, data = build.dat, family = binomial(link = "logit"))


train.x <- build.dat[ , all.vars(formula[[3]])] 
test.x <- reject.dat[1:100, all.vars(formula[[3]])]

explainer <- lime(train.x, as_classifier(model.logit ), n_bins = 20, quantile_bins = TRUE)

explain.me <- lime::explain(test.x[2 , ], explainer, n_labels = 1, n_features = 8, n_permutations = 5000, 
                        feature_select = "forward_selection", type = "response" )

现在我得到了错误

Error in match.arg(type) :'arg' should be one of “link”, “response”, “terms”

但是在 'lime' 代码中移动我的 'type = "response"' 并不能解决它。

我已经尝试创建一个函数'predict_model.glm',我认为可能会纠正这个问题,因为我在使用randomForest并让它工作时发生了什么:

predict_model.glm <- function(x, newdata, type = "response" ) {
res <- as.data.frame(c(predict(x, newdata = newdata, type = type), 1-predict(x, newdata = newdata, type = type)))

}

但这似乎只会增加错误。

我确信这是因为我错过了“石灰”方面正在寻找的确切内容(因此我无法用“predict_model.glm”函数纠正这个问题),但我似乎无法在任何地方找到澄清。

任何帮助都会很棒,谢谢!

标签: rglmlime

解决方案


您必须将 predict 的输出转换为 within predict_model.glm。作为第一步,我建议打印type和调用结果的第一行predict。根据传入的类型,对 glm 的调用和返回的结果会有所不同 -?predict_model提示:对于“原始”,它是一个单一的资源,对于“概率”,它是概率(或者对于真正的线性模型:数字结果)。

总的来说,就我(希望)了解您的情况而言,类似于该功能的功能可能会让您向前迈出一步:

predict_model.glm <- function(x, newdata, type, ...) { 
  print(type)
  res <- predict(x, newdata);
  print(res[1])
  data.frame(Response = res)
}

推荐阅读