#!/usr/bin/env python#-*- coding: utf-8 -*-#@File : 波士顿房价预测.py#@Author: 赵路仓#@Date : 2020/4/11#@Desc :#@Contact : 398333404@qq.com
from sklearn.datasets importload_bostonfrom sklearn.model_selection importtrain_test_splitfrom sklearn.preprocessing importStandardScalerfrom sklearn.linear_model importLinearRegression, SGDRegressor, Ridgefrom sklearn.metrics importmean_squared_error#正规方程
deflinear1():"""正规方程的优化方法对波士顿房价进行预测
: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.标准化
transfer =StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)#4.预估器 正规方程优化 小于十万条
estimator =LinearRegression()
estimator.fit(x_train, y_train)#5.得出模型
print("正规方程权重系数为:", estimator.coef_)print("正规方程偏置:", estimator.intercept_)#6.模型评估
y_predit =estimator.predict(x_test)print("预测房价:", y_predit)
error=mean_squared_error(y_test, y_predit)print("正规方程-均方误差:", error)returnNone#梯度下降
deflinear2():"""梯度下降的优化方法对波士顿房价进行预测
: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.标准化
transfer =StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)#4.预估器 梯度下降,eta0学习率,max_iter迭代次数,大量数据推荐使用
estimator = SGDRegressor(learning_rate="constant", eta0=0.001, max_iter=10000)
estimator.fit(x_train, y_train)#5.得出模型
print("梯度下降权重系数为:", estimator.coef_)print("梯度下降偏置:", estimator.intercept_)#6.模型评估
y_predit =estimator.predict(x_test)print("预测房价:", y_predit)
error=mean_squared_error(y_test, y_predit)print("梯度下降-均方误差:", error)returnNone#岭回归
deflinear3():"""岭回归对波士顿房价进行预测
: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.标准化
transfer =StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)#4.预估器 梯度下降,eta0学习率,max_iter迭代次数,大量数据推荐使用
estimator = Ridge(max_iter=10000)
estimator.fit(x_train, y_train)#5.得出模型
print("岭回归权重系数为:", estimator.coef_)print("岭回归偏置:", estimator.intercept_)#6.模型评估
y_predit =estimator.predict(x_test)print("预测房价:", y_predit)
error=mean_squared_error(y_test, y_predit)print("岭回归-均方误差:", error)returnNoneif __name__ == "__main__":#代码1:正规方程
linear1()#代码2:梯度下降
linear2()#代码3:岭回归
linear3()