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)
#Rigde类实现
"""
ridge_reg = Ridge(alpha=1, solver='sag')
ridge_reg.fit(X, y)
print(ridge_reg.predict([[1.5],[2],[3]]))#打印预测值
print(ridge_reg.intercept_)#W0
print(ridge_reg.coef_)#W1
"""
#随机梯度下降类实现
sgd_reg = SGDRegressor(penalty='l2', max_iter=1000) #使用l2正则化惩罚项
sgd_reg.fit(X, y.ravel())#传入数据训练
print(sgd_reg.predict([[1.5]]))#打印预测值
print("W0=", sgd_reg.intercept_)#打印W0
print("W1=", sgd_reg.coef_)#打印W1
sklearn带惩罚项的线性回归
最新推荐文章于 2024-03-29 16:23:03 发布