Lasso
#include <Skigen/LinearModel>
template <typename Scalar = double>
class Skigen::Lasso(alpha=1, fit_intercept=true, max_iter=1000, tol=1e-4)
Linear Model trained with L1 prior as regularizer (aka the Lasso).
The optimization objective for Lasso is:
Technically the Lasso model is optimizing the same objective function as the ElasticNet with l1_ratio = 1.0 (no L2 penalty).
The L1 penalty induces sparsity, driving some coefficients exactly to zero.
Mirrors sklearn.linear_model.Lasso.
Read more in the User Guide.
Parameters:
-
alpha : Scalar, default=1 Constant that multiplies the L1 term (
Scalar, default1). Controls regularization strength.alpha = 0is equivalent to ordinary least squares (useLinearRegressioninstead for numerical stability). -
fit_intercept : bool, default=true Whether the intercept should be estimated (
bool, defaulttrue). Iffalse, the data is assumed to be already centered. -
max_iter : int, default=1000 The maximum number of iterations (
int, default1000). -
tol : Scalar, default=1e-4 The tolerance for the optimization (
Scalar, default1e-4): if the maximum coordinate update is smaller thantol, the solver stops.
Attributes:
-
coef : RowVectorType Parameter vector (1 × n_features).
-
intercept : Scalar Independent term in the decision function.
Methods
fit(X, y)
Fit the Lasso model via coordinate descent.
Centers the data when fit_intercept is true, then runs coordinate descent with soft-thresholding until convergence or max_iter iterations.
Parameters:
-
X : MatrixType Design matrix of shape (n_samples, n_features).
-
y : VectorType Target vector of shape (n_samples,). Will be cast to
Scalarif necessary.
Returns:
- result : Lasso
Reference to the fitted estimator (
*this).
sklearn parity gap: sample_weight and check_input parameters are not yet supported.
predict(X)
Predict using the linear model.
Computes where and are the fitted coefficients and intercept.
Parameters:
- X : MatrixType Sample matrix of shape (n_samples, n_features).
Returns:
- result : VectorType Predicted values of shape (n_samples,).
Throws:
std::runtime_error— if the model has not been fitted.
score(X, y)
Return the coefficient of determination on test data.
. Best possible score is 1.0; it can be negative if the model is arbitrarily worse than predicting the mean.
Parameters:
-
X : MatrixType Test samples of shape (n_samples, n_features).
-
y : VectorType True values of shape (n_samples,).
Returns:
- result : Scalar score.
Throws:
std::runtime_error— if the model has not been fitted.
Example
// Lasso with varying alpha — higher alpha = more sparsity
std::cout << "=== Lasso: feature selection via L1 ===\n";
for (double alpha : {0.001, 0.01, 0.1, 0.5}) {
Skigen::Lasso<double> model(alpha);
model.fit(X_tr, split.y_train);
int nonzero = (model.coef().array().abs() > 1e-10).count();
std::cout << " alpha=" << std::setw(5) << alpha
<< " non-zero=" << nonzero
<< " R²=" << model.score(X_te, split.y_test)
<< " coef=" << model.coef() << "\n";
}