假设我有数据集:
mydata=data.frame(
status = as.factor(c(0,0,0,0,0,1,1,1,1,1)),
a = c(1,3,4,5,6,1,2,3,4,5),
b = c(4,2,3,6,2,1,3,4,5,6)
)
我构建了一个 glm 模型,根据一半的观测值对其进行训练,然后使用该模型来预测另一半观测值的响应。
train=sample(1:nrow(mydata), nrow(mydata)/2)
test=mydata[-train,]
test.response=status[-train]
fit=glm(status~., data=mydata, family="binomial", subset=train)
probs=predict(fit, test, type="response")
pred=rep(0,5)
pred[probs>0.5]=1
table(pred, test.response)
这告诉我我预测了多少个真阳性和真阴性(分别有 2 个和 2 个)。
test.response
pred 0 1
0 2 0
1 1 2
我没有手动编码训练和测试数据集,而是转向 cv.glm
,以便 R 可以为我进行交叉验证。
library(boot)
fit2=glm(status~., data=mydata, family="binomial")
cv.fit=cv.glm(mydata, fit2, K=2)
我的问题是,如何使用交叉验证模型来预测我的响应变量?我之前使用的是 probs=predict(fit, test, type="response")
,但在本例中我不知道 test
是什么。
最佳答案
我相信这就是你想要的:
require(boot)
require(glmnet)
status <- c(0,0,0,0,0,1,1,1,1,1)
ymat <- as.matrix(status)
xdata <- data.frame(a,b)
xmat <- as.matrix(xdata)
fit.cv <- cv.glmnet(y = ymat, x = xmat, family="binomial")
lmin <- fit.cv$lambda.min
l1se <- fit.cv$lambda.1se
net <- glmnet(y = ymat, x = xmat, family="binomial")
predict(net, s=lmin, type = "nonzero")
colnames(status)[predict(net, s=lmin,type="nonzero")$X1]
plot(cv.glmnet(y = ymat,x = xmat, family= "binomial", type = "class"))
plot(cv.glmnet(y = ymat,x = xmat, family= "binomial", type = "mae"))
plot(cv.glmnet(y = ymat,x = xmat, family= "binomial", type = "deviance"))
plot(cv.glmnet(y = ymat,x = xmat, family= "binomial", type = "mse"))
plot(cv.glmnet(y = ymat,x = xmat, family= "binomial", type = "auc")) #needs more data
数据集非常小,因此我建议在更大的数据集上尝试此操作以避免警告/错误。
关于r - 如何在 R 中使用 cv.glm 进行预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25391623/