如何仅使用从 R 中的 glmnet 获得的权重进行预测?

How to predict using only weights obtained from glmnet in R?

可以使用 predict(fit,newx) 方法进行预测。但是,如果我没有合适的对象本身,而只有预测变量的权重作为向量文件,而预测变量的新观察结果作为矩阵文件,如何预测呢?预测变量和结果都是连续变量。

您可以只使用矩阵乘法,这就是 glmnet 所做的。在predict函数中,是:as.matrix(cbind2(1, x) %*% coefs)

示例:

library(glmnet)

x=matrix(rnorm(100*20),100,20)
y=rnorm(100)
fit1=glmnet(x,y)
coefs <- coef(fit1,s=0.01) # extract coefficients at a single value of lambda

manaul_pred <- as.matrix(cbind2(1, x) %*% coefs)
pred <- predict(fit1,newx=x,s=0.01)

manual_pred - pred # there is a negligible difference due to numeric precision