gpt4 book ai didi

r - 我可以对具有不同数量的预测变量的测试数据进行 Predict.glmnet 吗?

转载 作者:行者123 更新时间:2023-12-02 16:36:27 27 4
gpt4 key购买 nike

我使用 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 在格式不同的情况下会执行的操作。

关于r - 我可以对具有不同数量的预测变量的测试数据进行 Predict.glmnet 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com