Note
Go to the end to download the full example code.
3.4.8.6. Use the RidgeCV and LassoCV to set the regularization parameterΒΆ
Load the diabetes dataset
from sklearn.datasets import load_diabetes
data = load_diabetes()
X, y = data.data, data.target
print(X.shape)
(442, 10)
Compute the cross-validation score with the default hyper-parameters
Ridge: 0.410174971340889
Lasso: 0.3375593674654274
We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso and Ridge
import numpy as np
import matplotlib.pyplot as plt
alphas = np.logspace(-3, -1, 30)
plt.figure(figsize=(5, 3))
for Model in [Lasso, Ridge]:
scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas]
plt.plot(alphas, scores, label=Model.__name__)
plt.legend(loc="lower left")
plt.xlabel("alpha")
plt.ylabel("cross validation score")
plt.tight_layout()
plt.show()
Total running time of the script: (0 minutes 0.389 seconds)