predict.glmnet: Some Factors Have Only One Level in New Data

白昼怎懂夜的黑 提交于 2019-12-13 04:25:17

问题


I've trained an elastic net model in R using glmnet and would like to use it to make predictions off of a new data set.

But I'm having trouble producing the matrix to use as an argument in the predict() method because some of my factor variables (dummy variables indicating the presence of comorbidities) in the new data set only have one level (the comorbidities were never observed), which means I can't use

model.matrix(RESPONSE ~ ., new_data)

because it gives me the (expected)

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

I'm at a loss for how to get around this issue. Is there a way in R that I can construct an appropriate matrix for use in predict() in this situation, or do I need to prepare the matrix outside of R? In either case, how might I go about doing it?

Here is a toy example that reproduces the issue I'm having:

x1 <- rnorm(100)
x2 <- as.factor(rbinom(100, 1, 0.6))
x3 <- as.factor(rbinom(100, 1, 0.4))
y <- rbinom(100, 1, 0.2)

toy_data <- data.frame(x1, x2, x3, y)
colnames(toy_data) = c("Continuous", "FactorA", "FactorB", "Outcome")

mat1 <- model.matrix(Outcome ~ ., toy_data)[,-1]
y1 <- toy_data$Outcome

new_data <- toy_data
new_data$FactorB <- as.factor(0)

#summary(new_data) # Just to verify that FactorB now only contains one level

mat2 <- model.matrix(Outcome ~ ., new_data)[,-1]

回答1:


You can set the levels of your dataset to match the levels of the complete dataset in your example. A factor can have values present in the levels even when that value isn't present in the variable.

You can do this with the levels argument in factor():

new_data$FactorB <- factor(0, levels = levels(toy_data$FactorB))

Or by using the levels() function with assignment:

levels(new_data$FactorB) <- levels(toy_data$FactorB)

Using either approach, model.matrix() works properly once you have more than one level:

head( model.matrix(Outcome ~ ., new_data)[,-1] )
   Continuous FactorA1 FactorB1
1 -1.91632972        0        0
2  1.11411267        0        0
3 -1.21333837        1        0
4 -0.06311276        0        0
5  1.31599915        0        0
6  0.36374591        1        0


来源:https://stackoverflow.com/questions/51952588/predict-glmnet-some-factors-have-only-one-level-in-new-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!