基于线性回归的波士顿房价预测

该博客对比了正规方程和梯度下降两种方法在预测波士顿房价中的应用。正规方程一次性求解权重,不需要选择学习率,而梯度下降则需要选择学习率并多次迭代。通过 sklearn 库实现线性回归模型,对数据进行预处理、训练和评估。最终展示了两种方法的模型权重、偏置以及预测结果的均方误差。
摘要由CSDN通过智能技术生成

采用正规方程方法和梯度下降方法对波士顿房价进行预测

正规方程和梯度下降对比:

正规方程对比梯度下降
梯度下降正规方程
需要选择学习率不需要选择学习率
需要大量迭代一次运行就可得出
特征数量较大时使用需要计算方程,时间复杂度高

流程:

  1. 获取数据
  2. 数据集划分
  3. 标椎化
  4. 预估器流程
  5. 模型评估

 代码如下:

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression,SGDRegressor
from sklearn.metrics import mean_squared_error

def linear1():
    """
    正规方程的优化方法对波士顿房价进行预测
    :return: 
    """
    #1.获取数据
    boston = load_boston()
    print("特征数量:\n",boston.data.shape)

    #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("正规方程-权重系数为:\n",estimator.coef_)
    print("正规方程-偏置为:\n",estimator.intercept_)

    #6.模型评估
    y_predict = estimator.predict(x_test)
    print("预测房价:\n",y_predict)
    error = mean_squared_error(y_test,y_predict)
    print("正规方程均方误差为:\n",error)


    return None

def linear2():
    """
    梯度下降的优化方法对波士顿房价进行预测
    :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 = SGDRegressor(learning_rate="constant",eta0=0.001,max_iter=10000)    
    estimator.fit(x_train,y_train)

    #5.得出模型
    print("梯度下降-权重系数为:\n",estimator.coef_)
    print("梯度下降-偏置为:\n",estimator.intercept_)

    #6.模型评估
    y_predict = estimator.predict(x_test)
    print("预测房价:\n", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("梯度下降均方误差为:\n", error)

    return None

if __name__ =="__main__":
    #正规方程的优化方法对波士顿房价进行预测
    linear1()
    #梯度下降的优化方法对波士顿房价进行预测
    linear2()

运行截图:

正规方程运行结果
梯度下降运行结果

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lc_MVP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值