This example focuses on model selection for Lasso models that are
linear models with an L1 penalty for regression problems.
Indeed, several strategies can be used to select the value of the
regularization parameter: via cross-validation or using an information
criterion, namely AIC or BIC.
In what follows, we will discuss in details the different strategies.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
Dataset
In this example, we will use the diabetes dataset.
In addition, we add some random features to the original data to
better illustrate the feature selection performed by the Lasso model.
importnumpyasnpimportpandasaspdrng=np.random.RandomState(42)n_random_features=14X_random=pd.DataFrame(rng.randn(X.shape[0],n_random_features),columns=[f"random_{i:02d}"foriinrange(n_random_features)],)X=pd.concat([X,X_random],axis=1)# Show only a subset of the columnsX[X.columns[::3]].head()
age
bp
s3
s6
random_02
random_05
random_08
random_11
0
0.038076
0.021872
-0.043401
-0.017646
0.647689
-0.234137
-0.469474
-0.465730
1
-0.001882
-0.026328
0.074412
-0.092204
-1.012831
-1.412304
0.067528
0.110923
2
0.085299
-0.005670
-0.032356
-0.025930
-0.601707
-1.057711
0.208864
0.196861
3
-0.089063
-0.036656
-0.036038
-0.009362
-1.478522
1.057122
0.324084
0.611676
4
0.005383
0.021872
0.008142
-0.046641
0.331263
-0.185659
0.812526
1.003533
Selecting Lasso via an information criterion
LassoLarsIC provides a Lasso estimator that
uses the Akaike information criterion (AIC) or the Bayes information
criterion (BIC) to select the optimal value of the regularization
parameter alpha.
Before fitting the model, we will standardize the data with a
StandardScaler. In addition, we will
measure the time to fit and tune the hyperparameter alpha in order to
compare with the cross-validation strategy.
We will first fit a Lasso model with the AIC criterion.
Finally, we can plot the AIC and BIC values for the different alpha values.
The vertical lines in the plot correspond to the alpha chosen for each
criterion. The selected alpha corresponds to the minimum of the AIC or BIC
criterion.
Model selection with an information-criterion is very fast. It relies on
computing the criterion on the in-sample set provided to fit. Both criteria
estimate the model generalization error based on the training set error and
penalize this overly optimistic error. However, this penalty relies on a
proper estimation of the degrees of freedom and the noise variance. Both are
derived for large samples (asymptotic results) and assume the model is
correct, i.e. that the data are actually generated by this model.
These models also tend to break when the problem is badly conditioned (more
features than samples). It is then required to provide an estimate of the
noise variance.
Selecting Lasso via cross-validation
The Lasso estimator can be implemented with different solvers: coordinate
descent and least angle regression. They differ with regards to their
execution speed and sources of numerical errors.
In scikit-learn, two different estimators are available with integrated
cross-validation: LassoCV and
LassoLarsCV that respectively solve the
problem with coordinate descent and least angle regression.
In the remainder of this section, we will present both approaches. For both
algorithms, we will use a 20-fold cross-validation strategy.
Lasso via coordinate descent
Let’s start by making the hyperparameter tuning using
LassoCV.
Lars computes a solution path only for each kink in the path. As a result, it
is very efficient when there are only of few kinks, which is the case if
there are few features or samples. Also, it is able to compute the full path
without setting any hyperparameter. On the opposite, coordinate descent
computes the path points on a pre-specified grid (here we use the default).
Thus it is more efficient if the number of grid points is smaller than the
number of kinks in the path. Such a strategy can be interesting if the number
of features is really large and there are enough samples to be selected in
each of the cross-validation fold. In terms of numerical errors, for heavily
correlated variables, Lars will accumulate more errors, while the coordinate
descent algorithm will only sample the path on a grid.
Note how the optimal value of alpha varies for each fold. This illustrates
why nested-cross validation is a good strategy when trying to evaluate the
performance of a method for which a parameter is chosen by cross-validation:
this choice of parameter may not be optimal for a final evaluation on
unseen test set only.
Conclusion
In this tutorial, we presented two approaches for selecting the best
hyperparameter alpha: one strategy finds the optimal value of alpha
by only using the training set and some information criterion, and another
strategy is based on cross-validation.
In this example, both approaches are working similarly. The in-sample
hyperparameter selection even shows its efficacy in terms of computational
performance. However, it can only be used when the number of samples is large
enough compared to the number of features.
That’s why hyperparameter optimization via cross-validation is a safe
strategy: it works in different settings.
Total running time of the script: (0 minutes 0.984 seconds)
lasso=model[-1]plt.semilogx(lasso.cv_alphas_,lasso.mse_path_,":")plt.semilogx(lasso.cv_alphas_,lasso.mse_path_.mean(axis=-1),color="black",label="Average across the folds",linewidth=2,)plt.axvline(lasso.alpha_,linestyle="--",color="black",label="alpha CV")plt.ylim(ymin,ymax)plt.xlabel(r"$\alpha$")plt.ylabel("Mean square error")plt.legend()_=plt.title(f"Mean square error on each fold: Lars (train time: {fit_time:.2f}s)")