predict.glmnet accepts a cv.glmnet object. But it seems that predict.aglm is not yet ready for a cv.aglm object. See an example code below.
It is problematic because the glmnet package recommends avoiding a usage like glmnet_pred1 below in the example but recommends a usage like glmnet_pred2 below.
Preamble starts
library(MASS) # For Boston
library(glmnet)
library(aglm)
Read data
xy <- Boston # xy is a data.frame to be processed.
colnames(xy)[ncol(xy)] <- "y" # Let medv be the objective variable, y.
Split data into train and test
n <- nrow(xy) # Sample size.
set.seed(2018) # For reproducibility.
test.id <- sample(n, round(n/4)) # ID numbers for test data.
test <- xy[test.id,] # test is the data.frame for testing.
train <- xy[-test.id,] # train is the data.frame for training.
x <- train[-ncol(xy)]
y <- train$y
newx <- test[-ncol(xy)]
y_true <- test$y
Preamble ends. No new information so far
predict.glmnet accepts a cv.glmnet object:
set.seed(2018)
glmnet_CV <- cv.glmnet(as.matrix(x), y)
glmnet_lambda <- glmnet_CV$lambda.min
glmnet_model <- glmnet(as.matrix(x), y, lambda = glmnet_lambda)
glmnet_pred1 <- predict(glmnet_model, newx = as.matrix(newx), type = "response")
cat("RMSE: ", sqrt(mean((y_true - glmnet_pred1)^2)), "\n")
#RMSE: 3.67907: Not recommended
glmnet_pred2 <- predict(glmnet_CV, s = glmnet_lambda,
newx = as.matrix(newx), type = "response")
cat("RMSE: ", sqrt(mean((y_true - glmnet_pred2)^2)), "\n")
#RMSE: 3.678105: Recommended
predict.aglm doesn't accept a cv.aglm object:
set.seed(2018)
aglm_CV <- cv.aglm(x, y)
aglm_lambda <- aglm_CV$lambda.min
aglm_model <- aglm(x, y, lambda = aglm_lambda)
aglm_pred1 <- predict(aglm_model, newx = newx, type = "response")
cat("RMSE: ", sqrt(mean((y_true - aglm_pred1)^2)), "\n")
#RMSE: 3.10334: Not recommended?
aglme_pred2 <- predict(aglm_CV, s = aglm_lambda,
newx = newx, type = "response")
#Error
cat("RMSE: ", sqrt(mean((y_true - aglm_pred2)^2)), "\n")
#Error