机器学习案例(二):波士顿房价预测——基于正规方程优化及梯度下降优化(附源码)

波士顿房价预测——基于正规方程优化及梯度下降优化

数据代码下载地址

项目链接+源代码:https://github.com/w1449550206/Boston-house-price-forecast.git

数据介绍

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aGsuXyDc-1582643802633)(../images/%E6%88%BF%E4%BB%B7%E6%95%B0%E6%8D%AE%E9%9B%86%E4%BB%8B%E7%BB%8D.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tO98suMN-1582643802634)(../images/%E5%B1%9E%E6%80%A7.png)]

给定的这些特征,是专家们得出的影响房价的结果属性。我们此阶段不需要自己去探究特征是否有用,只需要使用这些特征。到后面量化很多特征需要我们自己去寻找

1 分析

回归当中的数据大小不一致,是否会导致结果影响较大。所以需要做标准化处理。

  • 数据分割与标准化处理
  • 回归预测
  • 线性回归的算法效果评估

2 回归性能评估

均方误差(Mean Squared Error)MSE)评价机制:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FeIX6ZgS-1582643802635)(../images/%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E8%AF%84%E4%BC%B0.png)]

注:yi为预测值,¯y为真实值

  • sklearn.metrics.mean_squared_error(y_true, y_pred)
    • 均方误差回归损失
    • y_true:真实值
    • y_pred:预测值
    • return:浮点数结果

详细步骤

#要用到的包
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
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import SGDRegressor

【正规方程优化的线性回归】

1.获取数据 load_boston

data = load_boston()

2.数据基本处理 划分数据集和测试集

x_train,x_test,y_train,y_test = train_test_split(data.data, data.target,test_size = 0.2, random_state = 10)#random_state = 10保证划分数据集一样的

3.特征工程 标准化

#用接口standardscaler
transfer  = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)

4.机器学习 线性回归(正规方程优化的,梯度下降优化的)

4.1创建模型 实例化估计器

estimator = LinearRegression()

4.2训练模型 fit 正规方程计算得到最优的可训练参数

estimator.fit(x_train,y_train)

在这里插入图片描述

5.模型评估 MSE(均方误差,越小越好) 预测值和真实值都需要

5.1获取预测值

y_predict = estimator.predict(x_test)

5.2计算MSE

mean_squared_error(y_pred=y_predict,y_true=y_test)#得到了均方误差,越小越好

在这里插入图片描述

【梯度下降优化的线性回归】

1.获取数据 load_boston

data = load_boston()

2.数据基本处理 划分数据集和测试集

x_train,x_test,y_train,y_test = train_test_split(data.data, data.target,test_size = 0.2, random_state = 10)#random_state = 10保证划分数据集一样的

3.特征工程 标准化

#用接口standardscaler
transfer  = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)

4.机器学习 线性回归(正规方程优化的,梯度下降优化的)

4.1创建模型 实例化估计器

estimator = SGDRegressor(max_iter=1000,tol=0.001)#tol=0.001是指的是每次迭代是否损失函数越来越小,如果损失函数的值小于0.001的话就停止迭代

4.2训练模型 fit 正规方程计算得到最优的可训练参数

estimator.fit(x_train,y_train)

在这里插入图片描述

5.模型评估 MSE(均方误差,越小越好) 预测值和真实值都需要

5.1获取预测值

y_predict = estimator.predict(x_test)

5.2计算MSE

mean_squared_error(y_pred=y_predict,y_true=y_test)#得到了均方误差,越小越好

在这里插入图片描述

我们也可以尝试去修改学习率

estimator = SGDRegressor(max_iter=1000,learning_rate="constant",eta0=0.1)

此时我们可以通过调参数,找到学习率效果更好的值。

发布了531 篇原创文章 · 获赞 666 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_35456045/article/details/104507704