libqe 0.2.6-dev.9001
QE C++ library
Loading...
Searching...
No Matches
lasso.hpp
Go to the documentation of this file.
1
23#ifndef LIBQE_LASSO_HPP
24#define LIBQE_LASSO_HPP
25
26#include <armadillo>
27#include <cmath>
28#include <limits>
29#include <stdexcept>
30
31namespace qe {
32
43inline double soft_threshold(double z, double gamma) noexcept {
44 return z > gamma ? z - gamma : z < -gamma ? z + gamma : 0.0;
45}
46
74inline arma::vec lasso_cd(
75 const arma::mat& X,
76 const arma::vec& y,
77 double lambda,
78 const arma::vec& pf,
79 arma::vec beta0 = {},
80 int max_iter = 1000,
81 double tol = 1e-7
82) {
83 const arma::uword p = X.n_cols;
84 const double n = static_cast<double>(X.n_rows);
85
86 // Precompute X_j'X_j / n for each predictor
87 arma::vec xTx(p);
88 for (arma::uword j = 0; j < p; ++j)
89 xTx(j) = arma::dot(X.col(j), X.col(j)) / n;
90
91 arma::vec beta = beta0.is_empty()
92 ? arma::vec(p, arma::fill::zeros)
93 : beta0;
94 arma::vec r = y - X * beta; // residual, maintained incrementally
95
96 for (int it = 0; it < max_iter; ++it) {
97 double max_delta = 0.0;
98
99 for (arma::uword j = 0; j < p; ++j) {
100 if (xTx(j) < 1e-14) continue; // skip zero-variance predictor
101
102 // Partial correlation statistic
103 double z = arma::dot(X.col(j), r) / n + xTx(j) * beta(j);
104
105 double b_new = (pf(j) < 1e-12)
106 ? z / xTx(j) // forced in: OLS
107 : soft_threshold(z, lambda * pf(j)) / xTx(j); // L1
108
109 double delta = b_new - beta(j);
110 if (std::abs(delta) > max_delta) max_delta = std::abs(delta);
111 r -= X.col(j) * delta;
112 beta(j) = b_new;
113 }
114
115 if (max_delta < tol) break;
116 }
117 return beta;
118}
119
135inline double lasso_lambda_max(
136 const arma::mat& X, // column-standardized
137 const arma::mat& Yc, // column-centered responses
138 const arma::vec& pf
139) {
140 const double n = static_cast<double>(X.n_rows);
141 double lmax = 0.0;
142 for (arma::uword j = 0; j < X.n_cols; ++j) {
143 if (pf(j) < 1e-12) continue; // skip unpenalized predictors
144 for (arma::uword k = 0; k < Yc.n_cols; ++k) {
145 double v = std::abs(arma::dot(X.col(j), Yc.col(k))) / n;
146 if (v > lmax) lmax = v;
147 }
148 }
149 return lmax;
150}
151
195inline arma::mat lasso_x1_contribution(
196 const arma::mat& X_raw,
197 const arma::mat& Y,
198 const arma::uvec& x1_cols,
199 const arma::vec& pf,
200 int n_lambda = 50,
201 int k_folds = 5,
202 double eps = 0.01
203) {
204 const arma::uword n = X_raw.n_rows;
205 const arma::uword p = X_raw.n_cols;
206 const arma::uword q = Y.n_cols;
207
208 // Guard: need at least 2 folds and 2 observations per fold
209 k_folds = std::max(2, std::min(k_folds, static_cast<int>(n) / 2));
210
211 // ── Standardize X (μ=0, σ=1); guard zero-variance predictors ────────────
212 arma::rowvec xmu = arma::mean(X_raw, 0);
213 arma::rowvec xstd = arma::stddev(X_raw, 0, 0);
214 xstd.elem(arma::find(xstd < 1e-12)).ones(); // avoid divide-by-zero
215 arma::mat X = (X_raw.each_row() - xmu).each_row() / xstd;
216
217 // ── Center Y (absorbs intercept into the standardized-scale fit) ─────────
218 arma::rowvec ymu = arma::mean(Y, 0);
219 arma::mat Yc = Y.each_row() - ymu;
220
221 // ── Build lambda path: lambda_max → lambda_min on log scale ─────────────
222 double lmax = lasso_lambda_max(X, Yc, pf);
223 if (lmax < 1e-12) // target uncorrelated with Y after standardization
224 return arma::mat(n, q, arma::fill::zeros);
225
226 arma::vec lambdas = arma::exp(
227 arma::linspace(std::log(lmax),
228 std::log(eps * lmax),
229 n_lambda));
230
231 // ── Stratified k-fold CV (fold assignment: row i → fold i % k_folds) ────
232 arma::uvec fold_id(n);
233 for (arma::uword i = 0; i < n; ++i)
234 fold_id(i) = i % static_cast<arma::uword>(k_folds);
235
236 arma::vec cv_err(n_lambda, arma::fill::zeros);
237
238 for (int fold = 0; fold < k_folds; ++fold) {
239 arma::uvec tr = arma::find(fold_id != static_cast<arma::uword>(fold));
240 arma::uvec va = arma::find(fold_id == static_cast<arma::uword>(fold));
241
242 const arma::mat X_tr = X.rows(tr), X_va = X.rows(va);
243 const arma::mat Y_tr = Yc.rows(tr), Y_va = Yc.rows(va);
244 const double n_va_q = static_cast<double>(va.n_elem * q);
245
246 // Warm-start along path for this fold (start cold at lambda_max)
247 arma::mat bw(p, q, arma::fill::zeros);
248 for (int l = 0; l < n_lambda; ++l) {
249 arma::mat b(p, q);
250 for (arma::uword k = 0; k < q; ++k)
251 b.col(k) = lasso_cd(X_tr, Y_tr.col(k), lambdas(l), pf, bw.col(k));
252 bw = b;
253
254 arma::mat err = Y_va - X_va * b;
255 cv_err(l) += arma::accu(err % err) / n_va_q;
256 }
257 }
258 cv_err /= static_cast<double>(k_folds);
259
260 // ── Refit on full data at lambda_min, warming along the path ─────────────
261 arma::uword best = cv_err.index_min();
262 arma::mat bfull(p, q, arma::fill::zeros);
263 for (arma::uword l = 0; l <= best; ++l) {
264 arma::mat b(p, q);
265 for (arma::uword k = 0; k < q; ++k)
266 b.col(k) = lasso_cd(X, Yc.col(k), lambdas(l), pf, bfull.col(k));
267 bfull = b;
268 }
269
270 // ── Unstandardize: beta_orig[j] = beta_std[j] / xstd[j] ─────────────────
271 for (arma::uword j = 0; j < p; ++j)
272 bfull.row(j) /= xstd(j);
273
274 // ── Return fitted contribution from x1 columns only ──────────────────────
275 // This is the portion of Y (mean-removed) linearly explained by the target
276 // predictors after covariate adjustment. Constant shifts cancel in both
277 // the between-group scatter (categorical) and slope regression (numeric)
278 // that follow, so no ymu adjustment is needed here.
279 return X_raw.cols(x1_cols) * bfull.rows(x1_cols);
280}
281
282} // namespace qe
283#endif // LIBQE_LASSO_HPP
Definition adjacency.hpp:16
arma::mat lasso_x1_contribution(const arma::mat &X_raw, const arma::mat &Y, const arma::uvec &x1_cols, const arma::vec &pf, int n_lambda=50, int k_folds=5, double eps=0.01)
Cross-validated multivariate Lasso; returns fitted values for target columns only.
Definition lasso.hpp:195
double lasso_lambda_max(const arma::mat &X, const arma::mat &Yc, const arma::vec &pf)
Compute the smallest lambda that drives all penalized coefficients to zero.
Definition lasso.hpp:135
double soft_threshold(double z, double gamma) noexcept
Soft-threshold (shrinkage) operator used by coordinate descent.
Definition lasso.hpp:43
arma::vec lasso_cd(const arma::mat &X, const arma::vec &y, double lambda, const arma::vec &pf, arma::vec beta0={}, int max_iter=1000, double tol=1e-7)
Single-response Lasso via cyclic coordinate descent at a fixed lambda.
Definition lasso.hpp:74