竞赛 大数据房价预测分析与可视

0 前言

🔥 优质竞赛项目系列,今天要分享的是

🚩 大数据房价预测分析与可视

🥇学长这里给一个题目综合评分(每项满分5分)

  • 难度系数:3分
  • 工作量:3分
  • 创新点:4分

该项目较为新颖,适合作为竞赛课题方向,学长非常推荐!

🧿 更多资料, 项目分享:

https://gitee.com/dancheng-senior/postgraduate

1 课题背景

Ames数据集包含来自Ames评估办公室的2930条记录。
该数据集具有23个定类变量,23个定序变量,14个离散变量和20个连续变量(以及2个额外的观察标识符) - 总共82个特征。
可以在包含的codebook.txt文件中找到每个变量的说明。
该信息用于计算2006年至2010年在爱荷华州艾姆斯出售的个别住宅物业的评估价值。实际销售价格中增加了一些噪音,因此价格与官方记录不符。

分别分为训练和测试集,分别为2000和930个观测值。 在测试集中保留实际销售价格。 此外,测试数据进一步分为公共和私有测试集。

本次练习需要围绕以下目的进行:

  • 理解问题 : 观察每个变量特征的意义以及对于问题的重要程度
  • 研究主要特征 : 也就是最终的目的变量----房价
  • 研究其他变量 : 研究其他多变量对“房价”的影响的他们之间的关系
  • 基础的数据清理 : 对一些缺失数据、异常点和分类数据进行处理
  • 拟合模型: 建立一个预测房屋价值的模型,并且准确预测房价

在这里插入图片描述

2 导入相关的数据

1.导入相关的python包

​    
​    import numpy as np
​    import pandas as pd
from pandas.api.types import CategoricalDtype%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as snsfrom sklearn import linear_model as lm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold# Plot settingsplt.rcParams['figure.figsize'] = (12, 9)
plt.rcParams['font.size'] = 12

2. 导入训练数据集和测试数据集

​    
​    training_data = pd.read_csv("ames_train.csv")
​    test_data = pd.read_csv("ames_test.csv")
​    pd.set_option('display.max_columns', None)#显示所有行
​    pd.set_option('display.max_rows', None)#设置value的显示长度为100,默认为50
​    pd.set_option('max_colwidth',100)
​    training_data.head(7)

在这里插入图片描述

3 观察各项主要特征与房屋售价的关系

该数据集具有46个类别型变量,34个数值型变量,整理到excel表格中,用于筛选与房价息息相关的变量。从中筛选出以下几个与房价相关的变量:

类别型变量:

  • Utilities : 可用设施(电、天然气、水)

  • Heating (Nominal): 暖气类型

  • Central Air (Nominal): 是否有中央空调

  • Garage Type (Nominal): 车库位置

  • Neighborhood (Nominal): Ames市区内的物理位置(地图地段)

  • Overall Qual (Ordinal): 评估房屋的整体材料和光洁度

数值型变量:

  • Lot Area(Continuous):地皮面积(平方英尺)

  • Gr Liv Area (Continuous): 地面以上居住面积平方英尺

  • Total Bsmt SF (Continuous): 地下面积的总面积

  • TotRmsAbvGrd (Discrete): 地面上全部房间数目

分析最重要的变量"SalePrice"

    training_data['SalePrice'].describe()

在这里插入图片描述

从上面的描述性统计可以看出房价的平均值、标准差、最小值、25%分位数、50%分位数、75%分位数、最大值等,并且SalePrice没有无效或者其他非数值的数据。

    #绘制"SalePrice"的直方图sns.distplot(training_data['SalePrice'])#计算峰度和偏度print("Skewness: %f" % training_data['SalePrice'].skew())print("Kurtosis: %f" % training_data['SalePrice'].kurt())

在这里插入图片描述

从直方图中可以看出"SalePrice"成正态分布,峰度为4.838055,偏度为1.721408,比正态分布的高峰更加陡峭,偏度为右偏,长尾拖在右边。

2.类别型变量

(1)Utilities与SalePrice

Utilities (Ordinal): Type of utilities available

AllPub All public Utilities (E,G,W,& S)

NoSewr Electricity, Gas, and Water (Septic Tank)

NoSeWa Electricity and Gas Only

ELO Electricity only

​    
​    #类别型变量#1.Utilities 
​    var = 'Utilities'
​    data = pd.concat([training_data['SalePrice'], training_data[var]], axis=1)
​    fig = sns.boxplot(x=var, y="SalePrice", data=data)
​    fig.axis(ymin=0, ymax=800000)

在这里插入图片描述

从图中可以看出,配备全套设施(水、电、天然气)的房子价格普遍偏高

(2)Heating与SalePrice

Heating (Nominal): Type of heating

Floor Floor Furnace

GasA Gas forced warm air furnace

GasW Gas hot water or steam heat

Grav Gravity furnace

OthW Hot water or steam heat other than gas

Wall Wall furnace

​    
​    #2.Heating
​    var = 'Heating'
​    data = pd.concat([training_data['SalePrice'], training_data[var]], axis=1)
​    fig = sns.boxplot(x=var, y="SalePrice", data=data)
​    fig.axis(ymin=0, ymax=800000)

在这里插入图片描述

从图中可以看出拥有GasA、GasW的房子价格较高,并且有GasA的房子价格变动较大,房屋价格较高的房子一般都有GasA制暖装置。

(3)Central_Air与SalePrice

#3.Central_Air
​    var = 'Central_Air'
​    data = pd.concat([training_data['SalePrice'], training_data[var]], axis=1)
​    fig = sns.boxplot(x=var, y="SalePrice", data=data)
​    fig.axis(ymin=0, ymax=800000)

在这里插入图片描述

由中央空调的房子能给用户更好的体验,因此一般价格较高,房屋价格较高的房子一般都有中央空调。

(4)Gabage_type与SalePrice

Garage Type (Nominal): Garage location

2Types More than one type of garage

Attchd Attached to home

Basment Basement Garage

BuiltIn Built-In (Garage part of house - typically has room above garage)

CarPort Car Port

Detchd Detached from home

NA No Garage

    #4.Gabage_typevar = 'Garage_Type'data = pd.concat([training_data['SalePrice'], training_data[var]], axis=1)fig = sns.boxplot(x=var, y="SalePrice", data=data)fig.axis(ymin=0, ymax=800000)

在这里插入图片描述

车库越便捷,一般房屋价格越高,临近房屋以及房屋内置的车库这两种价格较高。

(5)Neighborhood与SalePrice

Neighborhood为房屋位于Ames市内的具体的地段,越临近繁华市区、旅游风景区、科技园区、学园区的房屋,房屋价格越贵

​    
​    #5.Neighborhood
​    fig, axs = plt.subplots(nrows=2)
​    sns.boxplot(x='Neighborhood',y='SalePrice',data=training_data.sort_values('Neighborhood'),ax=axs[0])sns.countplot(x='Neighborhood',data=training_data.sort_values('Neighborhood'),ax=axs[1])# Draw median priceaxs[0].axhline(y=training_data['SalePrice'].median(), color='red',linestyle='dotted')# Label the bars with countsfor patch in axs[1].patches:x = patch.get_bbox().get_points()[:, 0]y = patch.get_bbox().get_points()[1, 1]axs[1].annotate(f'{int(y)}', (x.mean(), y), ha='center', va='bottom')# Format x-axesaxs[1].set_xticklabels(axs[1].xaxis.get_majorticklabels(), rotation=90)axs[0].xaxis.set_visible(False)# Narrow the gap between the plotsplt.subplots_adjust(hspace=0.01)

在这里插入图片描述

从上图结果可以看出,我们训练数据集中Neighborhood这一列数据不均匀,NAmes有299条数据,而Blueste只有4条数据,Gilbert只有6条数据,GmHill只有2条数据,这样造成数据没那么准确。

(6)Overall Qual 与SalePrice

总体评价越高,应该房屋的价格越高

    #Overall Qual var = 'Overall_Qual'data = pd.concat([training_data['SalePrice'], training_data[var]], axis=1)fig = sns.boxplot(x=var, y="SalePrice", data=data)fig.axis(ymin=0, ymax=800000)

在这里插入图片描述

3.数值型变量

(1) Lot Area与SalePrice

    #数值型变量#1.Lot Areasns.jointplot(x='Lot_Area', y='SalePrice', data=training_data,stat_func=None,kind="reg",ratio=4,space=0,scatter_kws={'s': 3,'alpha': 0.25},line_kws={'color': 'black'})

在这里插入图片描述

看起来没有什么明显的趋势,散点图主要集中在前半部分,不够分散

(2)Gr_Liv_Area与SalePrice

Gr_Liv_Area代表建筑在土地上的房屋的面积

猜测两者应该成正相关,即房屋面积越大,房屋的价格越高

    sns.jointplot(x='Gr_Liv_Area', y='SalePrice', data=training_data,stat_func=None,kind="reg",ratio=4,space=0,scatter_kws={'s': 3,'alpha': 0.25},line_kws={'color': 'black'})

在这里插入图片描述

结果:两者的确呈现正相关的线性关系,发现Gr_ Liv _ Area中有处于5000以上的异常值

编写函数,将5000以上的Gr_ Liv _ Area异常值移除

​    
​    def remove_outliers(data, variable, lower=-np.inf, upper=np.inf):"""
​        Input:
​          data (data frame): the table to be filtered
​          variable (string): the column with numerical outliers
​          lower (numeric): observations with values lower than this will be removed
​          upper (numeric): observations with values higher than this will be removed
​        Output:a winsorized data frame with outliers removed"""data=data[(data[variable]>lower)&(data[variable]

再次绘图

在这里插入图片描述

两者的确呈现正相关的线性关系

(3)Total_Bsmt_SF与SalePrice

#3.Total Bsmt SF
​    sns.jointplot(
​        x='Total_Bsmt_SF', 
​        y='SalePrice', 
​        data=training_data,
​        stat_func=None,
​        kind="reg",
​        ratio=4,
​        space=0,
​        scatter_kws={'s': 3,'alpha': 0.25},
​        line_kws={'color': 'black'})

在这里插入图片描述

(4)TotRms_AbvGrd与SalePrice

   #4.TotRmsAbvGrdsns.jointplot(x='TotRms_AbvGrd', y='SalePrice', data=training_data,stat_func=None,kind="reg",ratio=4,space=0,scatter_kws={'s': 3,'alpha': 0.25},line_kws={'color': 'black'})

在这里插入图片描述

4. 绘制相关性矩阵

    #绘制相关性矩阵corrmat = training_data.corr()f, ax = plt.subplots(figsize=(40, 20))sns.heatmap(corrmat, vmax=0.8,square=True,cmap="PiYG",center=0.0)

在这里插入图片描述

其中数值型变量中,Overall_Qual(房屋的整体评价) 、Year_Built(房屋建造年份)、Year_Remod/Add(房屋整修年份)、Mas
Vnr Area(房屋表层砌体模型)、Total_ Bsmt _ SF(地下总面积)、1stFlr_SF(一楼总面积) Gr_ L
iv_Area(地上居住面积)、Garage_Cars (车库数量)、Garage_Area(车库面积)都与呈正相关

最后从Year_Built(房屋建造年份)、Year_Remod/Add(房屋整修年份)中选取Year_Built,从1stFlr_SF(一楼总面积)
Gr_ L iv_Area(地上居住面积)中选取Gr_ L iv_Area,从Garage_Cars
(车库数量)、Garage_Area(车库面积)中选取Garage_Cars (车库数量)。

6. 拟合模型

sklearn中的回归有多种方法,广义线性回归集中在linear_model库下,例如普通线性回归、Lasso、岭回归等;另外还有其他非线性回归方法,例如核svm、集成方法、贝叶斯回归、K近邻回归、决策树回归、随机森林回归方法等,通过测试各个算法的

(1)加载相应包

​    
​    #拟合数据from sklearn import preprocessing
​    from sklearn import linear_model, svm, gaussian_process
​    from sklearn.ensemble import RandomForestRegressor
​    from sklearn.cross_validation import train_test_split
​    import numpy as np

(2)查看各列缺失值

    #查看各列缺失值print(training_data.Overall_Qual.isnull().any())print(training_data.Gr_Liv_Area.isnull().any())print(training_data.Garage_Cars.isnull().any())print(training_data.Total_Bsmt_SF.isnull().any())print(training_data.Year_Built.isnull().any())print(training_data.Mas_Vnr_Area.isnull().any())

发现Total_Bsmt_SF和Mas_Vnr_Area两列有缺失值

​    
​       #用均值填补缺失值
​        training_data.Total_Bsmt_SF=training_data.Total_Bsmt_SF.fillna(training_data.Total_Bsmt_SF.mean())
​        training_data.Mas_Vnr_Area=training_data.Mas_Vnr_Area.fillna(training_data.Mas_Vnr_Area.mean())print(training_data.Total_Bsmt_SF.isnull().any())print(training_data.Mas_Vnr_Area.isnull().any())

(3)拟合模型

# 获取数据from sklearn import metrics
​        cols = ['Overall_Qual','Gr_Liv_Area', 'Garage_Cars','Total_Bsmt_SF', 'Year_Built','Mas_Vnr_Area']
​        x = training_data[cols].values
​        y = training_data['SalePrice'].values
​        X_train,X_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
​        clf = RandomForestRegressor(n_estimators=400)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)计算MSE:print(metrics.mean_squared_error(y_test,y_pred))

(4)绘制预测结果的散点图

​    
​    import numpy as np
​    x = np.random.rand(660)
​    plt.scatter(x,y_test, alpha=0.5)
​    plt.scatter(x,y_pred, alpha=0.5,color="G")

在这里插入图片描述

(5)加载测试集数据

    test_data=pd.read_csv("ames_test.csv")test_data.head(5)

在这里插入图片描述

查看缺失值

    #查看各列缺失值print(test_data.Overall_Qual.isnull().any())print(test_data.Gr_Liv_Area.isnull().any())print(test_data.Garage_Cars.isnull().any())print(test_data.Total_Bsmt_SF.isnull().any())print(test_data.Year_Built.isnull().any())print(test_data.Mas_Vnr_Area.isnull().any())

    #用均值填补缺失值test_data.Garage_Cars=training_data.Garage_Cars.fillna(training_data.Garage_Cars.mean())print(test_data.Garage_Cars.isnull().any())

(6)预测测试集的房价

#预测
​        cols = ['Overall_Qual','Gr_Liv_Area', 'Garage_Cars','Total_Bsmt_SF', 'Year_Built','Mas_Vnr_Area']
​        x_test_value= test_data[cols].values
​        test_pre=clf.predict(x_test_value)#写入文件
​        prediction = pd.DataFrame(test_pre, columns=['SalePrice'])
​        result = pd.concat([test_data['Id'], prediction], axis=1)
​        result.to_csv('./Predictions.csv', index=False)
​    test_data.Garage_Cars=training_data.Garage_Cars.fillna(training_data.Garage_Cars.mean())print(test_data.Garage_Cars.isnull().any())

(6)预测测试集的房价

​    
​    #预测
​    cols = ['Overall_Qual','Gr_Liv_Area', 'Garage_Cars','Total_Bsmt_SF', 'Year_Built','Mas_Vnr_Area']
​    x_test_value= test_data[cols].values
​    test_pre=clf.predict(x_test_value)#写入文件
​    prediction = pd.DataFrame(test_pre, columns=['SalePrice'])
​    result = pd.concat([test_data['Id'], prediction], axis=1)
​    result.to_csv('./Predictions.csv', index=False)

4 最后

该项目较为新颖,适合作为竞赛课题方向,学长非常推荐!

🧿 更多资料, 项目分享:

[https://gitee.com/dancheng-senior/postgraduate](

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/146511.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

JavaScript中如何确定this的值?如何指定this的值?

🎀JavaScript中的this 在绝大多数情况下,函数的调用方法决定了this的值(运行时绑定)。this不能在执行期间被赋值,并且在每次函数呗调用时this的值也可能会不同。 🍿如何确定this的值: 在非严格…

百度交易中台之内容分润结算系统架构浅析

作者 | 交易中台团队 导读 随着公司内容生态的蓬勃发展,内容产出方和流量提供方最关注的“收益结算”的工作,也就成为重中之重。本文基于内容分润结算业务为入口,介绍了实现过程中的重难点,比如千万级和百万级数据量下的技术选型和…

C++八股

1、简述一下C中的多态 在面向对象中,多态是指通过基类的指针或引用,在运行时动态调用实际绑定对象函数的行为,与之相对应的编译时绑定函数称为静态绑定。 静态多态 静态多态是编译器在编译期间完成的,编译器会根据实参类型来选择…

UART相关参数和Modbus协议

温湿度数据和风速风向数据的读取和计算方法 文章目录 温湿度数据和风速风向数据的读取和计算方法1 串行通信数据格式1.1 协议介绍1.2 UART相关参数1.3 UART通信过程 2 USB转串口模块的使用3 串口调试助手的使用3.1 串口控制区3.2 发送控制区3.3 接收控制区 4 GY-39气象信息模块…

在2023年使用Unity2021从Built-in升级到Urp可行么

因为最近在做WEbgl平台,所以某些不可抗力原因,需要使用Unity2021开发,又由于不可明说原因,想用Urp,怎么办? 目录 创建RenderAsset 关联Asset 暴力转换(Menu->Edit) 单个文件…

Object.defineProperty()方法详解,了解vue2的数据代理

假期第一篇,对于基础的知识点,我感觉自己还是很薄弱的。 趁着假期,再去复习一遍 Object.defineProperty(),对于这个方法,更多的还是停留在面试的时候,面试官问你vue2和vue3区别的时候,不免要提一提这个方法…

SLAM从入门到精通(tf的使用)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing 163.com】 在ros的机器人学习过程中,有一件事情是肯定少不了的。那就是坐标系的转换。其实这也很容易理解。假设有一个机器人,它有一个…

Linux文件查找,别名,用户组综合练习

1.文件查看: 查看/etc/passwd文件的第5行 [rootserver ~]# head -5 /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologi…

性能压力测试的定义及步骤是什么

在今天的数字化时代,软件系统的性能和稳定性对于企业的成功至关重要。为了确保软件在高负载和压力情况下的正常运行,性能压力测试成为了不可或缺的环节。本文将介绍性能压力测试的定义、步骤。 一、性能压力测试的定义和目标 性能压力测试是通过模拟实际…

openGauss学习笔记-86 openGauss 数据库管理-内存优化表MOT管理-内存表特性-MOT部署配置

文章目录 openGauss学习笔记-86 openGauss 数据库管理-内存优化表MOT管理-内存表特性-MOT部署配置86.1 总体原则86.2 重做日志(MOT)86.3 检查点(MOT)86.4 恢复(MOT)86.5 统计(MOT)86…

USART串口协议

通信接口 •通信的目的:将一个设备的数据传送到另一个设备,扩展硬件系统 • 通信协议:制定通信的规则,通信双方按照协议规则进行数据收发 全双工:指通信双方能够同时进行双向通信,一般来说,全双…

阿里云ACP知识点(三)

1、弹性伸缩不仅提供了在业务需求高峰或低谷时自动调节ECS实例数量的能力,而且提供了ECS实例上自动部署应用的能力。弹性伸缩的伸缩配置支持多种特性,例如______,帮助您高效、灵活地自定义ECS实例配置,满足业务需求。 标签、密钥对、 实例RAM…

[docker]笔记-网络故障处理

1、同事在虚拟机上部署docker,发现电脑无法登录虚拟机了。首先ping测是通的,从我电脑继续进行登录测试发现没问题,初步判断是她电脑网络和虚拟机网络之间连接出错。 2、进行虚拟机登录查看,首先使用route -n命令查看路由&#xf…

SpringBoot整合数据库连接

JDBC 1、数据库驱动 JDBC(Java DataBase Connectivity),即Java数据库连接。简而言之,就是通过Java语言来操作数据库。 JDBC是sun公司提供一套用于数据库操作的接口. java程序员只需要面向这套接口编程即可。不同的数据库厂商&…

WPF中的控件

内容控件:label、border Window控件 Label控件 Border控件 内容控件 Button控件 点击取消按钮关闭程序;点击登录按钮打开BorderWindow窗口。 TextBox控件 PasswordBox控件 TextBlock控件 加载窗口时显示TextBlock中的内容 RadioButton控件 CheckBox控件…

Vim学习笔记

博客主页:https://tomcat.blog.csdn.net 博主昵称:农民工老王 主要领域:Java、Linux、K8S 期待大家的关注💖点赞👍收藏⭐留言💬 目录 模式介绍指令概览启动退出移动光标插入删除复制替换撤销搜索信息设置外…

Emmabuntüs Debian Edition 5 正式发布

导读来自 Emmabunts Collective 的 Patrick d’Emmabunts 近日向 9to5Linux.com 通报了 Emmabunts Debian Edition 5 1.00 的发布和全面可用性,该版本是用于翻新旧电脑的 GNU/Linux 发行版的最新稳定版本。 Emmabunts Debian Edition 5是在Emmabunts Debian Edition…

安全渗透测试基础之漏洞扫描工具之Nessus使用介绍

前置条件:Nessus工具使用前要确保工具是服务状态 systemctl start nessusd.service 启动nessus服务 systemctl status nessusd.service 查看nessus服务状态 1.配置扫描模板 2.新增高级扫描 2.1 设置日程表: 2.2设置邮件收件人(可选): 2.3主机发现: 2.

vue3简易文字验证码

大神勿喷,简易版本,demo中可以用一下。 需要几个文字自己codelen 赋值 灵活点直接父组件传过去,可以自己改造 首先创建一个生成数字的js **mathcode.js**function MathCode(num){let str "寻寻觅觅冷冷清清凄凄惨惨戚戚乍暖还寒时候…

字符串函数与内存函数讲解

文章目录 前言一、字符串函数1.求字符串长度strlen 2.长度不受限制的字符串函数(1)strcpy(2)strcat(3)strcmp 3.长度受限制的字符串函数(1)strncpy(2)strncat(3)strncmp 4.字符串查找(1)strstr(2)strtok 5.错误信息报告(1)strerror(2)perror 二、内存函数1.memcpy2.memmove3.me…