2013-08-24 61 views
4

我使用glmnet在200個預測變量和100個樣本的訓練集上構建預測模型,用於二項迴歸/分類問題。我可以使用不同數量的預測變量對測試數據進行預測嗎?

我選擇了最好的模型(16個預測變量),它給了我最大的AUC。我有一個獨立的測試集,只有那些變量(16個預測變量),它們從訓練集中變成了最終模型。

有沒有辦法使用基於訓練組新的測試集具有數據,只有那些使它成爲訓練組最終模型變量的最優模型predict.glmnet?

+0

您不應該使用懲罰性程序來分割樣本測試,特別是在使用小尺寸樣本時。 'glmnet'應該被賦予所有的數據。然後,只要'newx'具有與原始數據相同的結構,就可以爲未來的案例提供'newx'和擬合模型。 –

+0

對於newx而言是相同的數據結構,這是否意味着它必須具有與開始時的訓練數據中相同數量的預測變量,或者它是否只包含使其進入最終模型的變量? – user1407875

+1

我原以爲只能使用最終模型中有係數的X變量。 –

回答

3

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