Search code examples
rpredictglmnet

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


One can make predictions using predict(fit,newx) method. But how to predict if I don't have the fit object itself but only the weights of the predictors as vector file and new observations for predictors as a matrix file? The predictors and the outcome both are continuous variables.


Solution

  • You can just use matrix multiplication, which is what glmnet does. In the predict function, it is: as.matrix(cbind2(1, x) %*% coefs)

    Example:

    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