'How to fill a non-zero coefficient/gamma plot when optimizing with CVXR package?

I'm replicating an article of Kozak, Nagel and Santosh; Shrinking the Cross-section. Therefore I'm creating a model that will select a few characteristics out of a large set of characteristics, that together are a good representation of an SDF.

In this model I make use of Ridge and Lasso techniques and my supervisor advised me to use the CVXR package. I minimize my objective with two loss functions which are multiplied with two sets of gammas. The main goal of my code is to end with a plot that has one of the gammas on the x-axis (the ridge) and the number of non-zero coefficients on the y-axis (so not the lasso parameter).

However, since the number of non-zero coefficients is an outcome of the optimizer I can not state that I want an optut with n non-zero coefficients.

Is there anyone who know how to produce my desired outcome? Code that I used is stated below.

# Grid for L1 penalty
  cv.gamma_1 <- seq(0.005,0.02, by = (0.0075/15) )
  
  # Grid for L2 penalty
  cv.kappa <- 10^seq(-2,0.5,(2/24))
  cv.Tt <- nrow(cv.train)
  cv.tau <- sum(diag(cv.Sigma.train))
  cv.gamma_2 <- as.numeric(cv.tau/((cv.kappa^2)*cv.Tt)) 
  
# Create results Matrix
  coef_matrix <- matrix(nrow = length(cv.gamma_2), ncol = Nn, data = 0)
  
  for (i in 1:length(cv.gamma_1)) {
    for (j in 1:length(cv.gamma_2)) {
      
      objective <- loss_1 + cv.gamma_2[j] * loss_2 + cv.gamma_1[i] * loss_3
      prob <- Problem(Minimize(objective))
      result <- solve(prob)
      model_betas <- result$getValue(beta)
      
      # Compute R-squared of model with these betas
      r_score <- Rsquared(Mu_OOS = cv.Mu.test, Sigma_OOS = cv.Sigma.test, betas = model_betas)
      
      # Coef matrix
      non_zeros <- sum( round(model_betas,2) != 0.00)
      if (non_zeros != 0){
        if (coef_matrix[j,non_zeros] < r_score){
          coef_matrix[j,non_zeros] <- r_score}
      }
    } 

For now I ran my optimizer and counted the number of non-zeros, made a matrix with non-zeros on the y-axis and gamma on x-axis. Therefore, I do not have values on all my non-zero values in the matrix.

my plot:

enter image description here

Desired plot:

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source