I sometimes run into situations where glmnet
appears to be performing well but actually selects zero features. The AUC is near-perfect but the nzero
column shows that all the coefficients are zero. How is this possible?
# Load libraries.
library(glmnet)
library(pROC)
# Simulate data.
set.seed(123)
data <- replicate(3, rnorm(50))
colnames(data) <- paste0("Var", 1:3)
outcome <- gl(2, 25, labels = c("sick", "healthy"))
# Test/train Elastic Net models using LOOCV.
results <- lapply(1:nrow(data), function(i) {
fit <- cv.glmnet(
x = data[-i, ],
y = as.numeric(outcome[-i]),
family = "binomial"
)
pred <- predict(
fit,
newx = data[i, , drop = F],
lambda = "lambda.1se"
)
data.frame(
index = i,
pred = pred[1],
actual = outcome[i],
nzero = fit$nzero[fit$lambda == fit$lambda.1se]
)
})
# Evaluate performance.
results <- do.call(rbind, results)
roc(results$actual, results$pred) # AUC = 1
plot(results$actual, results$pred)
table(results$nzero) # all coefficients are 0