scikit-learn学习笔记(四)Ridge Regression ( 岭回归 )

岭回归通过对系数的大小施加惩罚来解决 普通最小二乘 的一些问题。 ridge coefficients ( 岭系数 ) 最小化了惩罚的残差平方和,

这里,  是控制收缩量的复杂度参数:  值越大,收缩量越大,因此系数变得对共线性变得更加鲁棒。

与其他线性模型一样,Ridge 将采用其拟合方法数组 X , y 并将其线性模型的系数  存储在其 coef_ 成员中:

>>> from sklearn import linear_model
>>> reg = linear_model.Ridge (alpha = .5)
>>> reg.fit ([[0, 0], [0, 0], [1, 1]], [0, .1, 1])
Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,
       normalize=False, random_state=None, solver= 'auto' , tol=0.001)
>>> reg.coef_
array([ 0.34545455,  0.34545455])
>>> reg.intercept_
0.13636...

Ridge Complexity ( 岭复杂性 )

这种方法与 Ordinary Least Squares ( 普通最小二乘方法 ) 的复杂度相同。

例子1: ( 作为正则化的函数,绘制岭系数 )

# -*- coding: utf-8 -*-
"""
Created on Sat Jul 29 21:27:04 2017

@author: Administrator
"""

import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model

# X is the 10x10 Hilbert matrix
X = 1. / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis])
y = np.ones(10)

n_alphas = 200
alphas = np.logspace(-10, -2, n_alphas)
clf = linear_model.Ridge(fit_intercept=False)

coefs = []
for a in alphas:
    clf.set_params(alpha=a)
    clf.fit(X, y)
    coefs.append(clf.coef_)
ax = plt.gca()
ax.plot(alphas, coefs)
ax.set_xscale('log')
ax.set_xlim(ax.get_xlim()[::-1])  # reverse axis
plt.xlabel('alpha')
plt.ylabel('weights')
plt.title('Ridge coefficients as a function of the regularization')
plt.axis('tight')
plt.show()  

你可能感兴趣的:(scikit-learn学习笔记(四)Ridge Regression ( 岭回归 ))