Python机器学习/数据挖掘项目实战 波士顿房价预测 回归分析

2023-11-19

Python机器学习/数据挖掘项目实战 波士顿房价预测 回归分析

  • 此数据源于美国某经济学杂志上,分析研究波士顿房价( Boston HousePrice)的数据集。
  • 在这个项目中,你将利用马萨诸塞州波士顿郊区的房屋信息数据训练和测试一个模型,并对模型的性能和预测能力进行测试。通过该数据训练后的好的模型可以被用来对房屋做特定预测—尤其是对房屋的价值。对于房地产经纪等人的日常工作来说,这样的预测模型被证明非常有价值。

数据集说明

  • 数据集中的每一行数据都是对波士顿周边或城镇房价的情况描述,对数据集变量说明如下。

CRIM: 城镇人均犯罪率
ZN: 住宅用地所占比例
INDUS: 城镇中非住宅用地所占比例
CHAS: 虚拟变量,用于回归分析
NOX: 环保指数
RM: 每栋住宅的房间数
AGE: 1940 年以前建成的自住单位的比例
DIS: 距离 5 个波士顿的就业中心的加权距离
RAD: 距离高速公路的便利指数
TAX: 每一万美元的不动产税率
PTRATIO: 城镇中的教师学生比例
B: 城镇中的黑人比例
LSTAT: 地区中有多少房东属于低收入人群
MEDV: 自住房屋房价中位数(也就是均价)

  • 原文:print (boston_data['DESCR'])

Boston House Prices dataset

===========================

Notes

------ Data Set Characteristics:

:Number of Instances: 506 

:Number of Attributes: 13 numeric/categorical predictive

:Median Value (attribute 14) is usually the target

:Attribute Information (in order):
    - CRIM     per capita crime rate by town
    - ZN       proportion of residential land zoned for lots over 25,000 sq.ft.
    - INDUS    proportion of non-retail business acres per town
    - CHAS     Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
    - NOX      nitric oxides concentration (parts per 10 million)
    - RM       average number of rooms per dwelling
    - AGE      proportion of owner-occupied units built prior to 1940
    - DIS      weighted distances to five Boston employment centres
    - RAD      index of accessibility to radial highways
    - TAX      full-value property-tax rate per $10,000
    - PTRATIO  pupil-teacher ratio by town
    - B        1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
    - LSTAT    % lower status of the population
    - MEDV     Median value of owner-occupied homes in $1000's

导入库

from sklearn.datasets import load_boston
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
from matplotlib import pyplot as plt

载入数据集

boston_data=load_boston()
x_data = boston_data.data
y_data = boston_data.target

names=boston_data.feature_names
FeaturesNums = 13
DataNums = len(x_data)

可视化分析

  • 将数据集各个特征可视化
  • 分析相关性后再进行数据处理
  • 处理后继续可视化
  • 可视化再反馈给数据处理
  • 若数据满意,则尝试建模

以下的数据图是经过筛选后的特征数据所得

特征与标签关系

  • 观察特征与标签关系
  • 分析特征对于标签的贡献程度
# 每个Feature和target二维关系图
plt.subplots(figsize=(20,12))
for i in range(FeaturesNums):
    plt.subplot(231+i)
    plt.scatter(x_train[:,i],y_train,s=20,color='blueviolet')
    plt.title(names[i])
plt.show()

特征数据分布

  • 数据分布能够估计数据价值
  • 也能发现异常数据
plt.subplots(figsize=(20,10))
for i in range(FeaturesNums):
    plt.subplot(231+i)
    plt.hist(x_data[:,i],color='lightseagreen',width=2)
    plt.xlabel(names[i])
    plt.title(names[i])
plt.show()

数据处理

  • 导入sklearn中的预处理库
  • 多种处理方式
from sklearn import preprocessing

清除异常值

DelList0=[]
for i in range(DataNums):
    if (y_data[i] >= 49 or y_data[i] <= 1):
        DelList0.append(i)
DataNums -= len(DelList0)
x_data = np.delete(x_data,DelList0,axis=0)
y_data = np.delete(y_data,DelList0,axis=0)

去除无用特征

DelList1=[]
for i in range(FeaturesNums):
    if (names[i] == 'ZN' or
        names[i] == 'INDUS' or
        names[i] == 'RAD' or
        names[i] == 'TAX' or
        names[i] == 'CHAS' or
        names[i] == 'NOX' or
        names[i] == 'B' or
        names[i] == 'PTRATIO'):
      DelList1.append(i)
x_data = np.delete(x_data, DelList1, axis=1)
names = np.delete(names, DelList1)
FeaturesNums -= len(DelList1)

归一化

from sklearn.preprocessing import MinMaxScaler, scale
nms = MinMaxScaler()
x_train = nms.fit_transform(x_train)
x_test  = nms.fit_transform(x_test)
y_train = nms.fit_transform(y_train.reshape(-1,1))
y_test  = nms.fit_transform(y_test.reshape(-1,1))

数据分割

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3)

训练模型

  • 尝试多种模型
  • 择优选取

线性回归LinearRegression

  • 用线性回归模型训练
  • 查看MSE和R2得分
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

model = LinearRegression()
model.fit(x_train, y_train)
y_pred = model.predict(x_test)
print ("MSE =", mean_squared_error(y_test, y_pred),end='\n\n')
print ("R2  =", r2_score(y_test, y_pred),end='\n\n')

MSE = 0.013304697805737791
R2 = 0.44625845284900767

  • 可视化结果
# 画图
fig, ax = plt.subplots()
ax.scatter(y_test, y_pred, c="blue", edgecolors="aqua",s=13)
ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'k', lw=2, color='navy')
ax.set_xlabel('Reality')
ax.set_ylabel('Prediction')
plt.show()

SVR模型linear核

  • 用SVR模型linear核模型训练
  • 查看得分
from sklearn.svm import SVR
from sklearn.model_selection import cross_val_predict, cross_val_score
linear_svr = SVR(kernel='linear')
# linear_svr.fit(x_train, y_train)
# linear_pred = linear_svr.predict(x_test)
linear_svr_pred = cross_val_predict(linear_svr, x_train, y_train, cv=5)
linear_svr_score = cross_val_score(linear_svr, x_train, y_train, cv=5)
linear_svr_meanscore = linear_svr_score.mean()
print ("Linear_SVR_Score =",linear_svr_meanscore,end='\n')

Linear_SVR_Score = 0.6497361775614359

SVR模型poly核

  • 用SVR模型poly核模型训练
  • 查看得分
from sklearn.svm import SVR
from sklearn.model_selection import cross_val_predict, cross_val_score
poly_svr = SVR(kernel='poly')
poly_svr.fit(x_train, y_train)
poly_pred = poly_svr.predict(x_test)
poly_svr_pred = cross_val_predict(poly_svr, x_train, y_train, cv=5)
poly_svr_score = cross_val_score(poly_svr, x_train, y_train, cv=5)
poly_svr_meanscore = poly_svr_score.mean()
print ('\n',"Poly_SVR_Score =",poly_svr_meanscore,end='\n')

Poly_SVR_Score = 0.5383303049258509

总结

  • 通过数据处理和可视化分析,能够相互反馈筛选有效特征
  • 采用多种模型进行尝试,选择得分最优的模型进行最终的训练
  • 最后,SVR模型linear核效果最佳
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python机器学习/数据挖掘项目实战 波士顿房价预测 回归分析 的相关文章

随机推荐

  • 刷脸支付服务商帮助微信支付宝拓展市场服务客户

    如今的刷脸支付市场 随着微信刷脸支付 青蛙 的内测完成 马上就会和支付宝的 蜻蜓 有一场争夺市场的大战了 两大巨头打架 肯定会有很多的政策 到时候刷脸支付下面的人就能分一点汤 一定要记住 申请服务商是免费公开透明的 想要好好了解的就去支付宝
  • 大小端与结构体释疑

    本人在做项目过程中需要在ARM对从FPGA读取到的数据进行处理 在实际过程中产生了一些问题 在思考了后记录在此 1 大小端模式 大小端指数据在内存中的存储方式 小端指数据的高字节保存在内存的高地址处 低字节保存在内存的低地址处 大端模式则正
  • 【os模块】os.walk 获取指定路径下文件名

    os walk函数原型 os walk是python中的一个函数 函数声明 os walk top topdown True nerr r None top 目标路径 topdown 默认值是 True 表示首先返回顶级目录下的文件 然后再
  • c++ Sigmoid/Softmax/Argmax

    Sigmoid float sigmoid float x return 1 1 exp x float sigmoid dy dz float x return x 1 0 x float tanh dy dz float x retur
  • ES按日期滚动索引

    按日期滚动索引 环境 ES 6 9 ES 7 Centos 7 配置过程 创建索引 PUT localhost 9200 index 20210915 设置索引别名 写入别名和读取别名 PUT localhost 9200 index 20
  • 网络 -- n/24 计算IP范围

    1 IP地址 共分为四类 A B C D类 A类 从1 0 0 0 到 126 255 255 255 B类 从128 0 0 0 到 191 255 255 255 C类 从192 0 0 0 到 223 255 255 255 其中12
  • 关于输入、输出电容在 LDO 应用中的重要性

    关于输入 输出电容在 LDO 应用中的重要性 如何让LDO 产品在应用中达到更佳的稳定性 则用户在设计电路时 最好根据芯片 datasheet 的说明文档而定 下面以LP2985 3 3这个LDO为例 LP2985 3 3是低功耗 低压差
  • Vue基础(二)——模板语法

    一 指令 1 v bind 绑定属性 2 v on 绑定事件 3 v if和v show 1 介绍
  • tcp/ip在物理层/数据链路层 实现简单抓包

    socket的精妙之处在于协议族的横向转换和地址族的纵向转换 我们也可在更底层实现对流经host的数据流的监督和修改 尤其是监察数据 十分简单 这里是混杂模式实现对ip数据流的监察与对tcp数据流的简单查看 需要root权限 这里忽略了tc
  • 整理一下go的ci工具

    代码格式化 go fmt fileName go goimports 自动格式化import goimports w fileName go mod 自动更新 删除包 go mod tidy 检查注释是否符合导出 1 安装revive go
  • 关于如何修复烧写镜像文件失败的SD卡

    前言 使用某些软件 比如 win32 Disk Imager 向SD卡烧写镜像文件时 很有可能出现烧写失败的情况 通常如果烧写失败 系统会弹出请求格式化SD卡的提示框 此时不要点格式化 点了可能会造成不可挽救的结果 也可能不会 而是进行以下
  • 【C库函数】memcpy函数详解

    目录 memcpy 函数原型 参数讲解 返回值讲解 函数讲解 三个注意点 memcpy 拷贝内存块到目标空间 函数原型 void memcpy void dest const void src size t count 参数讲解 参数 de
  • 百度AI──自然语言处理使用教程

    百度AI 自然语言处理使用教程 情感倾向分析 创建自己的应用 python方式调用 安装Python SDK 创建一个 Python SDK客户端 配置AipNlp 调用接口 情感倾向分析 需要注意的几个点 完整代码 参考 创建自己的应用
  • Linux 配置 PaddleOCR环境

    配置环境 1 准备好CUDA和cudnn 安培架构GPU需配置CUDA 11 2 CUDNN 8 1 1 以下文档以安培架构GPU的为例 找到对应的版本下载CUDA https developer nvidia com cuda downl
  • 一位数组返回id和pid通过这两个参数转换为树形结构数据,和树形结构的渲染

    废话不多说直接上代码 html代码我是引用了一个jq的插件作为样式插件名字为 jOrgChart 具体内容大家可以评论到下方 div class com div class TheEditor 编辑 div div div div js代码
  • Java 实体设置指定日期格式

    import com fasterxml jackson annotation JsonFormat JsonFormat pattern yyyy MM dd HH mm ss timezone GMT 8 private Date cr
  • nginx 代理图片服务器

    location gif jpg jpeg png expires 24h root home sk ftp 指定图片存放路径 proxy store on proxy store access user rw group rw all r
  • MATLAB BP神经网络 笔记整理

    1 如何更改输出层的激活函数 传递函数 对于有两层神经网络结构 可以通过调用以下函数 net layers 1 or 2 transferFcn for the hidden net layers 3 transferFcn for the
  • C#实现遍历文件夹获取指定后缀名文件

    问题描述 项目需要 要进行某文件夹下所有shp数据的读取 解决方法 using System using System Collections Generic using System ComponentModel using System
  • Python机器学习/数据挖掘项目实战 波士顿房价预测 回归分析

    Python机器学习 数据挖掘项目实战 波士顿房价预测 回归分析 此数据源于美国某经济学杂志上 分析研究波士顿房价 Boston HousePrice 的数据集 在这个项目中 你将利用马萨诸塞州波士顿郊区的房屋信息数据训练和测试一个模型 并