R: problems applying LIME to quanteda text model

ε祈祈猫儿з 提交于 2019-12-06 05:20:15

corpus doesn't have to be run. Try redefining predict_model.textmodel_nb_fitted as follows, where the only modification is to add the dfm_select step:

predict_model.textmodel_nb_fitted <- function(x, newdata, type, ...) {
  X <- dfm_select(dfm(newdata), x$data$x)   
  res <- predict(x, newdata = X, ...)
  switch(
    type,
    raw = data.frame(Response = res$nb.predicted, stringsAsFactors = FALSE),
    prob = as.data.frame(res$posterior.prob, check.names = FALSE)
  )  
}

As your traceback() output shows, corpus throws an error. To debug, I inserted print(str(newdata)) in the first line of the predict_model.textmodel_nb_fitted function. This shows that newdata is already a dfm object, so it can be passed directly into predict.textmodel_nb_fitted (after processing it with dfm_select).


In more recent versions of quanteda, textmodel_nb() returns an object of classes textmodel_nb,textmodel, and list. This would first require a corresponding method for model_type:

model_type.textmodel_nb <- function(x, ...) {
  return("classification")
}

We then also have to write a textmodel_nb method for predict_model:

predict_model.textmodel_nb <- function(x, newdata, type, ...) {
  X <- dfm_select(dfm(newdata), x$x)   
  res <- predict(x, newdata = X, ...)
  switch(
    type,
    raw = data.frame(Response = res$nb.predicted, stringsAsFactors = FALSE),
    prob = as.data.frame(res$posterior.prob, check.names = FALSE)
  )  
}

Notice that the second argument to dfm_select is different from that in predict_model.textmodel_nb_fitted (from the original version of the answer). This is because the structure of the x object -- the output from textmodel_nb() -- has changed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!