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

当我使用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会给我类别标签。而使用predict(class_lr,df_test, type = "response")会导致错误。有没有办法让R输出预测的概率?


回答:

查看LogisticRegression的源代码,对于predict,它以对数几率比的形式计算预测并将其转换为概率,只返回类别,因此没有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)  # 如果我们需要返回类别  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 

Related Posts

如何对SVC进行超参数调优?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

如何在初始训练后向模型添加训练数据?

我想在我的scikit-learn模型已经训练完成后再…

使用Google Cloud Function并行运行带有不同用户参数的相同训练作业

我正在寻找一种方法来并行运行带有不同用户参数的相同训练…

加载Keras模型,TypeError: ‘module’ object is not callable

我已经在StackOverflow上搜索并阅读了文档,…

在计算KNN填补方法中特定列中NaN值的”距离平均值”时

当我从头开始实现KNN填补方法来处理缺失数据时,我遇到…

使用巨大的S3 CSV文件或直接从预处理的关系型或NoSQL数据库获取数据的机器学习训练/测试工作

已关闭。此问题需要更多细节或更清晰的说明。目前不接受回…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注