L1,L2正则化代码
# L1正则 import numpy as np from sklearn.linear_model import Lasso from sklearn.linear_model import SGDRegressor X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) lasso_reg = Lasso(alpha=0.15) lasso_reg.fit(X, y) print(lasso_reg.predict(1.5)) sgd_reg = SGDRegressor(penalty='l1') sgd_reg.fit(X, y.ravel()) print(sgd_reg.predict(1.5))
# L2正则 import numpy as np from sklearn.linear_model import Ridge from sklearn.linear_model import SGDRegressor X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) #两种方式第一种岭回归 ridge_reg = Ridge(alpha=1, solver='auto') ridge_reg.fit(X, y) print(ridge_reg.predict(1.5))#预测1.5的值 #第二种 使用随机梯度下降中L2正则 sgd_reg = SGDRegressor(penalty='l2') sgd_reg.fit(X, y.ravel()) print(sgd_reg.predict(1.5))
1 # elastic_net函数 2 import numpy as np 3 from sklearn.linear_model import ElasticNet 4 from sklearn.linear_model import SGDRegressor 5 6 7 X = 2 * np.random.rand(100, 1) 8 y = 4 + 3 * X + np.random.randn(100, 1) 9 #两种方式实现Elastic_net 10 elastic_net = ElasticNet(alpha=0.1, l1_ratio=0.5) 11 elastic_net.fit(X, y) 12 print(elastic_net.predict(1.5)) 13 14 sgd_reg = SGDRegressor(penalty='elasticnet') 15 sgd_reg.fit(X, y.ravel()) 16 print(sgd_reg.predict(1.5))