Search code examples
rr-s4convex-optimizationcvx

CVXR: Problem with solve() - Error in as.vector(data): no method for coercing this s4 class to a vector


I'm trying to minimize this function:

\min_{\mu} \sum_{t=T}^T \| y_t - \mu_t \|2 + \lambda \sum{t=1}^{T-1} \|mu_{t+1}-\mu_{t}\|_2

where: y and mu are p*T matraxis. Everything compiles well until I use the solve() function.

Here is what I coded with y being a p*obs matrix

library(CVXR)

mu <- Variable(p, obs)

# group lasso ----
total_var <- lapply(X = seq_len(obs-1), FUN = function(j) mu[,j+1] - mu[,j])
total_var_norm <- lapply(X = total_var, FUN = cvxr_norm, p=2)
group_lasso <- Reduce(f = sum, x = total_var_norm)

# loss function ---- 
col_diff <- lapply( X = seq_len(obs), FUN = function(j) y[,j] - mu[,j])
col_diff_norm <- lapply( X = col_diff, FUN = cvxr_norm, p=2)
loss <- Reduce(f = sum, x = col_diff_norm)

# convex optimization ----
objective_mu <- loss + lambda * group_lasso
problem_mu <- Minimize(objective_mu)
result_mu <- solve(problem_mu)

All executes well until the result_mu <- solve(problem_mu). Where I get the following Error message:

> result_mu <- solve(problem_mu)
Error in as.vector(data) : 
  no method for coercing this S4 class to a vector

Everything is fine until this point.

I also tried with the following formulation:

# group lasso ----
group_lasso <- norm(mu[,2] - mu[,1], type = "2")
for (s in 2:obs-1){
  group_lasso <- group_lasso + norm(mu[,s] - mu[,s+1], type = "2")
}

# loss function ---- 
loss <- norm(y[,1] - mu[,1], type = "2")
for (s in 2:obs){
  loss <- group_lasso_2 + norm(y[,s] - mu[,s], type = "2")
}

with the same objective and problem function. And here again I get exactly the same error message at the same point.

I can't see at what point the code is wrong... Any pointers?
Thanks


Solution

  • Problem is missing in your code:

    problem_mu <- Problem(Minimize(objective_mu))