R:如何用分类模型输出预测概率

R: how to output prediction probabilities with classification models

当我用 glm 拟合逻辑回归模型时,我可以指定 type = "response" 以获得预测概率。

model <- glm(formula= vs ~ wt + disp, data=mtcars, family=binomial)
newdata = data.frame(wt = 2.1, disp = 180)
predict(model, newdata, type="response")
        1 
0.2361081 

我正在新包 RSSL 中试验逻辑回归函数。下面是一些示例代码(来自文档)

library(RSSL)
set.seed(1)
df <- generateSlicedCookie(1000,expected=FALSE) %>% 
  add_missinglabels_mar(Class~.,0.98)
class_lr <- LogisticRegression(Class~.,df,lambda = 0.01)
df_test <- generateSlicedCookie(1000,expected=FALSE)
predict(class_lr,df_test)

class_lr 对象上使用 predict 给我 class 标签。使用 predict(class_lr,df_test, type = "response") 会导致错误。有没有办法让R输出预测的概率?

查看 source code of LogisticRegression,对于预测,它计算对数优势比的预测并将其转换为概率,returns 仅 class,因此没有选项type="response":

setMethod("predict", signature(object="LogisticRegression"), function(object, newdata) {
ModelVariables<-PreProcessingPredict(object@modelform,newdata,scaling=object@scaling,intercept=object@intercept)
  X<-ModelVariables$X

  w <- matrix(object@w, nrow=ncol(X))
  expscore <- exp(cbind(rep(0,nrow(X)), X %*% w))
  probabilities <- expscore/rowSums(expscore)

  # If we need to return classes
  classes <- factor(apply(probabilities,1,which.max),levels=1:length(object@classnames), labels=object@classnames)
  return(classes)
})

与此 class 关联的另一个方法是 posterior,您可以看到代码非常相似,它 returns exp 形式的概率:

setMethod("posterior", signature(object="LogisticRegression"), function(object,newdata) {

  ModelVariables<-PreProcessingPredict(modelform=object@modelform,
                                       newdata=newdata,
                                       y=NULL,
                                       scaling=object@scaling,
                                       intercept=object@intercept)

  X<-ModelVariables$X

  w <- matrix(object@w, nrow=ncol(X))
  expscore <- exp(cbind(rep(0,nrow(X)), X %*% w))
  posteriors <- expscore/rowSums(expscore)

  posteriors <- exp(posteriors)
  colnames(posteriors) <- object@classnames
  return(posteriors)
})

抱歉回答有点长,如果你需要概率,你可以这样做:

probs = log(posterior(class_lr,df_test))

第一列是第一个 class 的概率,第二列依此类推。要检查标签是否相似:

pred_labels = predict(class_lr,df_test)
table(apply(probs,1,which.max) == as.numeric(pred_labels))
TRUE 
1000