LASSO模型的预测函数中的下标超出范围误差

问题描述 投票:0回答:1

我正在使用LASSO模型进行预测,并且在预测中,运行预测功能时出现以下错误。有人可以帮助我克服这个问题吗?

错误MSG:预测错误(lasso_model,x,type =“ response”)[,2]: 下标超出范围

#convert data to matrix format
x <- model.matrix(St_recurrence~.,tr)

#convert class to numerical variable
y <- tr$St_recurrence

#Cross validation - perform grid search to find optimal value of lambda
cv_out <- cv.glmnet(x, y, alpha=1, family = 'binomial', nfolds = 5, type.measure = "auc")

#best value of lambda
best_lambda <- cv_out$lambda.1se

# Rebuilding the model with best lamda value identified
lasso_model <- glmnet(x, y, family = "binomial", alpha = 1, lambda = best_lambda)
coef(lasso_model)

# odds ratio
exp(coef(lasso_model))


library(ROCR)
# Calculate the probability of new observations belonging to "yes"
predprob <- predict(lasso_model, x, type = "response")[,2]      ## error comes in this line

# prediction is ROCR function
pred <- prediction(predprob, tr$Structural_recurrence)

# ROC curve (x-axis: fpr, y-axis: tpr)
perf <- performance(pred, measure = "tpr", x.measure = "fpr")
plot(perf, main="ROC Curve for LASSO model", col=rainbow(10))

#compute area under curve
aucperf <- performance(pred, measure="auc")
print([email protected])
r roc lasso-regression
1个回答
0
投票

对于glmnet,如果您执行?glmnet::predict.glmnet,则可以在详细信息下看到:

 type: Type of prediction required. Type ‘"link"’ gives the linear
          predictors for ‘"binomial"’, ‘"multinomial"’, ‘"poisson"’ or
          ‘"cox"’ models; for ‘"gaussian"’ models it gives the fitted
          values. Type ‘"response"’ gives the fitted probabilities for
          ‘"binomial"’ or ‘"multinomial"

并且它返回的向量为1,不像caret的返回2列。

因此您可以这样做:

library(glmnet)
library(ROCR)

data(Sonar)
y= as.numeric(Sonar$Class)-1
x=as.matrix(Sonar[,-ncol(Sonar)])
lasso_model = glmnet(x=x,y=y,family="binomial",alpha=1,lambda=0.001)

predprob <- predict(lasso_model, x, type = "response")
pred <- prediction(predprob, y)
perf <- performance(pred, measure = "tpr", x.measure = "fpr")
plot(perf, main="ROC Curve for LASSO model")
© www.soinside.com 2019 - 2024. All rights reserved.