Reputation: 31
I have a question on converting the glmnet predict
in R to Rcpp.
Currently I do this in R:
set.seed(0)
x1 <- matrix(runif(20), nrow = 4, ncol = 5)
y1 <- runif(4)
lasso_model <- glmnet(x1, y1, alpha = 1 ,lower.limits = 0, intercept = FALSE)
cv_model <- cv.glmnet(x1, y1, alpha = 1, lower.limits = 0)
optimal_lambda <- cv_model$lambda.min
# Get the coefficients for the optimal lambda
coefficients_vector <- predict(lasso_model, s = c(optimal_lambda), type = "coefficients")
# get the actual coefficients start from the second element
coefficients_vector <- coefficients_vector[-1,]
coefficients_vector
and I want to create a Rcpp function, here is what I have done so far:
#include <RcppArmadillo.h>
#include <Rcpp.h>
//[[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
arma::vec glmnetWithCV(const arma::mat& x, const arma::vec& y) {
// Use the global environment to find glmnet functions
Environment glmnet_env = Environment::namespace_env("glmnet");
Function cv_glmnet = glmnet_env["cv.glmnet"];
Function glmnet = glmnet_env["glmnet"];
Function predict_glmnet = glmnet_env["predict"];
NumericMatrix x_rcpp = wrap(x);
NumericVector y_rcpp = wrap(y);
// Fit the Lasso model
List lasso_model = glmnet(Named("x") = x_rcpp, Named("y") = y_rcpp, Named("alpha") = 1, Named("lower.limits") = 0);
// Perform cross-validation to find the optimal lambda
List cv_model = cv_glmnet(Named("x") = x_rcpp, Named("y") = y_rcpp, Named("alpha") = 1, Named("lower.limits") = 0);
NumericVector optimal_lambda = as<double>(cv_model["lambda.min"]);
//Rcout << "Optimal lambda: " << optimal_lambda << std::endl;
S4 coefficients_vector = predict_glmnet(lasso_model, Named("s") = optimal_lambda, Named("type") = "coefficients");
return List::create(Named("coefficients") = coefficients_vector,
Named("optimal_lambda") = optimal_lambda);
}
But I found I got error on passing S4 coefficients = predict_glmnet(lasso_model, Named("s") = optimal_lambda, Named("type") = "coefficients");
, when in R the coefficients_vector
is a dcgMatrix
, I have tried using sp_mat from arma, but it still don't work.
I'm wondering if there is any solution on this?
Thank you so much
Upvotes: 0
Views: 66