为了解决Ridge产生的较大的计算,Lasso很好的解决了这一问题.
Ridge的规范化是 aΣw2
Lasso的规范化是aΣ|w|
但是Lasso的惩罚效果却比Ridge严厉的多.可以把很多的w都惩罚为0.
实战:
import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # 线性回归 # 初始化数据 def make_data(nDim): x0 = np.linspace(1,np.pi,50) x = np.vstack([[x0],[i**x0 for i in range(2,nDim+1)]]) # 按行不断相加 y = np.sin(x0) + np.random.normal(0,0.15,len(x0)) return x.transpose(),y # 关键是对X转置了 x,y = make_data(12) def lasso_regression(): alphas = [1e-10,1e-3,1,10] # a列表 for idx,i in enumerate(alphas): plt.subplot(2,len(alphas)/2,idx+1) reg = linear_model.Lasso(alpha = i) # 初始化Lasso对象 sub_x = x[:,0:12] # 取全部12维的特征 reg.fit(sub_x,y) # 进行训练 plt.plot(x[:,0],reg.predict(sub_x)) plt.plot(x[:,0],y,‘.‘) plt.title("dim=12,alpha=%e"%i) print("alpha %e"%i) print("intercept_ :"% (reg.intercept_)) print("coef_: %s"% (reg.coef_)) plt.show() lasso_regression()
Out:
alpha 1.000000e-10
intercept_ :
coef_: [ 2.04299371e+00 -8.51843390e-01 -4.24962643e-02 -1.84973826e-03
1.23358346e-03 1.04820524e-03 6.83173993e-04 4.30557304e-04
2.74201438e-04 1.78402076e-04 1.18808043e-04 8.09076056e-05]
alpha 1.000000e-03
intercept_ :
coef_: [ 1.34709178e+00 -2.25101225e-01 -1.24268682e-01 -1.06427929e-02
-2.54148588e-04 5.07251667e-04 7.93022205e-04 5.44370622e-04
3.66845898e-04 2.49812709e-04 1.73236411e-04 1.22468296e-04]
alpha 1.000000e+00
intercept_ :
coef_: [-0. -0. -0. -0. -0. -0.
-0. -0. -0. -0.0005254 -0.00026335 -0. ]
alpha 1.000000e+01
intercept_ :
coef_: [-0. -0. -0. -0. -0. -0.
-0. -0. -0. -0. -0. -0.00047827]
我们可以看出a越大,就有越来越多的回归参数被设为0.
原文:https://www.cnblogs.com/liu247/p/11068538.html