实战代码
from sklearn.datasets import load_boston
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
def linearL2():
"""
用带L2正则化的线性回归——岭回归,实现波士顿房价预测
:return:
"""
# 1、获取数据集
boston = load_boston()
# 2、划分数据集
x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)
# 3、预估器流程,惩罚系数alpha=1.0
rd = Ridge(alpha=1.0)
rd.fit(x_train, y_train)
# 4、模型的评估
error = mean_squared_error(y_test, rd.predict(x_test))
print("均方误差为:\n", error)
print("岭回归的权重参数为:", rd.coef_)
print("岭回归的预测的结果为:", rd.predict(x_test))
return None
if __name__ == "__main__":
linearL2()