我使用 glmnet 在具有约 200 个预测变量和 100 个样本的训练集上构建了一个预测模型,用于二项式回归/分类问题。
我选择了给我最大 AUC 的最佳模型(16 个预测变量)。我有一个独立的测试集,只有那些变量(16 个预测变量)从训练集中进入最终模型。
有什么方法可以使用基于来自训练集的最佳模型的 predict.glmnet 和新的测试集,其中只有那些变量的数据,这些变量从训练集中进入最终模型?
glmnet
要求训练数据集中完全相同数量/名称的变量位于验证/测试集中。例如:
library(caret)
library(glmnet)
df <- ... # a dataframe with 200 variables, some of which you want to predict on
# & some of which you don't care about.
# Variable 13 ('Response.Variable') is the dependent variable.
# Variables 1-12 & 14-113 are the predictor variables
# All training/testing & validation datasets are derived from this single df.
# Split dataframe into training & testing sets
inTrain <- createDataPartition(df$Response.Variable, p = .75, list = FALSE)
Train <- df[ inTrain, ] # Training dataset for all model development
Test <- df[ -inTrain, ] # Final sample for model validation
# Run logistic regression , using only specified predictor variables
logCV <- cv.glmnet(x = data.matrix(Train[, c(1:12,14:113)]), y = Train[,13],
family = 'binomial', type.measure = 'auc')
# Test model over final test set, using specified predictor variables
# Create field in dataset that contains predicted values
Test$prob <- predict(logCV,type="response", newx = data.matrix(Test[,
c(1:12,14:113) ]), s = 'lambda.min')
对于一组全新的数据,您可以使用以下方法的一些变体将新的 df 约束为必要的变量:
new.df <- ... # new df w/ 1,000 variables, which include all predictor variables used
# in developing the model
# Create object with requisite predictor variable names that we specified in the model
predictvars <- c('PredictorVar1', 'PredictorVar2', 'PredictorVar3',
... 'PredictorVarK')
new.df$prob <- predict(logCV,type="response", newx = data.matrix(new.df[names(new.df)
%in% predictvars ]), s = 'lambda.min')
# the above method limits the new df of 1,000 variables to
# whatever the requisite variable names or indices go into the
# model.
此外,glmnet
仅处理矩阵。这可能就是您在问题的评论中收到错误的原因。一些用户(包括我自己)发现as.matrix()
不能解决问题;data.matrix()
似乎可以工作(因此为什么它在上面的代码中)。这个问题在 SO 上的一两个线程中得到解决。
我假设要预测的新数据集中的所有变量也需要采用与用于模型开发的数据集中相同的格式。我通常从同一个源中提取所有数据,所以我还没有遇到glmnet
格式不同的情况下会发生什么。