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

时间:2020-02-26 04:07:57

标签: r machine-learning logistic-regression prediction

当我将逻辑回归模型与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)

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

1 个答案:

答案 0 :(得分:0)

source code of LogisticRegression为例进行预测,它以对数比计算预测,并将其转换为概率并仅返回类别,因此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)
})

与此类关联的另一个方法是posterior,您可以看到代码非常相似,并且它以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))

第一列是处于第一类的概率,第二列以此类推。要检查标签是否相似:

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