在R中使用glm和cv.glmnet预测新数据(包括交互和分类变量)

时间:2020-03-31 12:41:00

标签: r regression prediction glm

我想建模一个回归公式,其中包括交互作用和分类变量。我有兴趣使用glm和glmnet :: cv.glmnet。我可以使用适合模型的功能,但不能确定我是否使用受过训练的模型正确预测出样本数据。这是一个例子。

Formula <- "Sepal.Length ~ Sepal.Width + Petal.Length + as.factor(Species):Petal.Width + Sepal.Width:Petal.Length +  as.factor(Species) +  bs(Petal.Width, df = 2, degree = 2)"

data("iris")
Inx <- sample( 1: nrow(iris), nrow(iris),  replace = F)

iris$Species <- as.factor(iris$Species)

train_data <- iris[Inx[1:100], ]
test_data <- iris[Inx[101:nrow(iris) ],]

#---- glm -----------------
ModelMatrix <- predict(caret::dummyVars(Formula, train_data, fullRank = T, sep = ""), train_data)
glmfit <- glm(formula = as.formula(Formula) , data = train_data)

prd_glm <- predict(glmfit, newx = ModelMatrix, type = "response")

#------- glm cross validation --------------
cvglm <- glmnet::cv.glmnet(x = ModelMatrix,
                           y = train_data$Sepal.Length,
                           nfolds = 4, keep = TRUE, alpha = 1, parallel = F, type.measure = 'mse')

ModelMatrix_test <- predict(caret::dummyVars(Formula, test_data, fullRank = T, sep = ""), test_data)
prd_cvglm <- predict(cvglm, newx = ModelMatrix_test,  s = "lambda.1se", type ='response')

1 个答案:

答案 0 :(得分:1)

您可以使用模型矩阵,也可以使用公式,但不能同时使用两者,因为一旦提供了公式,任何glm都会在内部生成模型矩阵。而且您只进行一次分解。因此,就您而言,假设直接适合模型matrx:

library(splines)
library(caret)
library(glmnet)

data(iris)
Inx <- sample(nrow(iris),100)
iris$Species <- factor(iris$Species)

train_data <- iris[Inx, ]
test_data <- iris[-Inx,]

Formula <- "Sepal.Length ~ Sepal.Width + Petal.Length + Species:Petal.Width + Sepal.Width:Petal.Length +  Species +  bs(Petal.Width, df = 2, degree = 2)"

glmfit <- glm(as.formula(Formula),data=train_data)

您可以看到这与使用公式拟合相同:

ModelMatrix <- predict(caret::dummyVars(Formula, train_data, fullRank = T, sep = ""), train_data)
y = train_data[,"Sepal.Length"]
fit_dummy = glm(y ~ ModelMatrix)
table(fitted(glmfit) == fitted(fit_dummy))
TRUE 
 100

我们根据测试数据进行预测:

prd_glm <- predict(glmfit, newdata = test_data, type = "response")

然后使用glmnet:

cvglm <- cv.glmnet(x = ModelMatrix,y = train_data$Sepal.Length,nfolds = 4, 
    keep = TRUE, alpha = 1, parallel = F, type.measure = 'mse')

ModelMatrix_test <- predict(caret::dummyVars(Formula, test_data, fullRank = T, sep = ""), test_data)
prd_cvglm <- predict(cvglm, newx = ModelMatrix_test,  s = "lambda.1se", type ='response')

您可以看到它们的不同之处:

plot(prd_glm,prd_cvglm)

enter image description here