2011-07-08 17:16:56 +08:00
|
|
|
"""
|
|
|
|
|
===========================================================
|
|
|
|
|
Plot Ridge coefficients as a function of the regularization
|
|
|
|
|
===========================================================
|
|
|
|
|
|
2013-07-22 21:48:44 +08:00
|
|
|
Shows the effect of collinearity in the coefficients of an estimator.
|
|
|
|
|
|
2011-09-02 17:00:02 +08:00
|
|
|
.. currentmodule:: sklearn.linear_model
|
2011-07-08 17:16:56 +08:00
|
|
|
|
2013-07-22 21:48:44 +08:00
|
|
|
:class:`Ridge` Regression is the estimator used in this example.
|
|
|
|
|
Each color represents a different feature of the
|
2012-05-24 21:44:18 +08:00
|
|
|
coefficient vector, and this is displayed as a function of the
|
|
|
|
|
regularization parameter.
|
|
|
|
|
|
|
|
|
|
At the end of the path, as alpha tends toward zero
|
2011-07-08 17:16:56 +08:00
|
|
|
and the solution tends towards the ordinary least squares, coefficients
|
|
|
|
|
exhibit big oscillations.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
# Author: Fabian Pedregosa -- <fabian.pedregosa@inria.fr>
|
2013-04-30 14:23:46 +08:00
|
|
|
# License: BSD 3 clause
|
2011-07-08 17:16:56 +08:00
|
|
|
|
2013-02-01 22:04:03 +08:00
|
|
|
print(__doc__)
|
2011-07-08 17:16:56 +08:00
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
import pylab as pl
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import linear_model
|
2011-07-08 17:16:56 +08:00
|
|
|
|
|
|
|
|
# X is the 10x10 Hilbert matrix
|
|
|
|
|
X = 1. / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis])
|
|
|
|
|
y = np.ones(10)
|
|
|
|
|
|
2011-12-24 02:12:26 +08:00
|
|
|
###############################################################################
|
2011-07-08 17:16:56 +08:00
|
|
|
# Compute paths
|
|
|
|
|
|
|
|
|
|
n_alphas = 200
|
|
|
|
|
alphas = np.logspace(-10, -2, n_alphas)
|
|
|
|
|
clf = linear_model.Ridge(fit_intercept=False)
|
|
|
|
|
|
|
|
|
|
coefs = []
|
|
|
|
|
for a in alphas:
|
2011-09-01 17:20:05 +08:00
|
|
|
clf.set_params(alpha=a)
|
|
|
|
|
clf.fit(X, y)
|
2011-07-08 17:16:56 +08:00
|
|
|
coefs.append(clf.coef_)
|
|
|
|
|
|
2011-12-24 02:12:26 +08:00
|
|
|
###############################################################################
|
2011-07-08 17:16:56 +08:00
|
|
|
# Display results
|
|
|
|
|
|
|
|
|
|
ax = pl.gca()
|
|
|
|
|
ax.set_color_cycle(['b', 'r', 'g', 'c', 'k', 'y', 'm'])
|
|
|
|
|
|
|
|
|
|
ax.plot(alphas, coefs)
|
|
|
|
|
ax.set_xscale('log')
|
2011-12-24 02:12:26 +08:00
|
|
|
ax.set_xlim(ax.get_xlim()[::-1]) # reverse axis
|
2011-07-08 17:16:56 +08:00
|
|
|
pl.xlabel('alpha')
|
|
|
|
|
pl.ylabel('weights')
|
|
|
|
|
pl.title('Ridge coefficients as a function of the regularization')
|
|
|
|
|
pl.axis('tight')
|
|
|
|
|
pl.show()
|