计算机毕设 大数据房价预测分析与可视

news2024/10/6 18:22:34

文章目录

  • 0 前言
  • 1 课题背景
    • 2 导入相关的数据
  • 3 观察各项主要特征与房屋售价的关系
  • 4 最后


0 前言

🔥 这两年开始毕业设计和毕业答辩的要求和难度不断提升,传统的毕设题目缺少创新和亮点,往往达不到毕业答辩的要求,这两年不断有学弟学妹告诉学长自己做的项目系统达不到老师的要求。

为了大家能够顺利以及最少的精力通过毕设,学长分享优质毕业设计项目,今天要分享的是

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

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

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

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 sns

from sklearn import linear_model as lm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold

# Plot settings
plt.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_type
var = '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 price
axs[0].axhline(
    y=training_data['SalePrice'].median(), 
    color='red',
    linestyle='dotted'
)

# Label the bars with counts
for 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-axes
axs[1].set_xticklabels(axs[1].xaxis.get_majorticklabels(), rotation=90)
axs[0].xaxis.set_visible(False)

# Narrow the gap between the plots
plt.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 Area
sns.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.TotRmsAbvGrd
sns.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 最后

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

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

相关文章

战火使命攻略,高级回响怎么出现

《战火使命》中,高级回响材料是每个玩家追求的梦想,因为它们不仅能够提升角色的实力,还能让你在战场上独具风采。本战火使命攻略将详细介绍三种获取高级回响的方法,助你在游戏中更加强大! 关注【娱乐天梯】&#xff0c…

数据结构-图-基础知识

图 图的基本概念图的概念顶点和边有向图和无向图完全图有向完全图无向完全图 邻接顶点顶点的度路径和路径长度简单路径和回路子图生成树 连通图强连通图 图的存储结构邻接矩阵邻接表 图的遍历BFSDFS 图的基本概念 图的概念 🚀图是由顶点集合及顶点间关系组成的一种…

O(根号n/ln(根号n))时间复杂度内求n的所有因子

O()复杂度内求n的所有因子,在2e9数量级比O()快10倍左右 先用范围内的质数除n,求出n的分解质因数形式,然后爆搜求出n的所有因子, n范围内的质数大约有个,所以是这个时间…

Spring Framework 黑马程序员-学习笔记

5.spring-核心概念 IoC :控制反转 使用对象时(如在service类中调用Dao层的对象,以便使用Dao类中的方法),本来是依靠new一个Dao层的对象来实现,而实现了Ioc思想的Spring为了解耦,将此过程改为&…

Play Beyond:Sui让优秀的游戏变得更好

自问世以来,视频游戏就紧随着文化产业发展。从Pong和Space Invaders的时代到Animal Crossing和Among Us,伟大的游戏总有能力吸引玩家,并推动娱乐产业发展。根据Grand View Research的数据,全球视频游戏市场在2022年估计为2170.6亿…

fastadmin插件 shopro 商城支付配置

1、 2、 注意上图中有添加支付方式链接,可以点击添加,这里添加后立即生效

zkVM设计性能分析

1. 引言 本文主要参考: 2023年9月ZKSummit10 Wei Dai 1k(x) & Terry Chung 1k(x)分享视频 ZK10: Analysis of zkVM Designs - Wei Dai & Terry Chung 当前有各种zkVM,其设计思想各有不同,且各有取舍,本文重点对现有各z…

[C语言】(指针解决)输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组

代码 下面是使用指针解决的代码示例&#xff1a; #include <stdio.h>void swap(int *a, int *b) {int temp *a;*a *b;*b temp; }int main() {int arr[100], n, max_index 0, min_index 0;printf("Enter the size of the array: ");scanf("%d"…

Maven(项目构建管理工具)

为什么要使用Maven&#xff1f; 传统项目管理状态分析&#xff1a; ①jar包不统一&#xff0c;jar包不兼容&#xff1b; ②工程升级维护过程操作繁琐&#xff1b; ........... Maven(JAVA书写)&#xff1a;管理jar包以及jar之间的依赖关系&#xff0c;完成项目编译&#xff0c;…

【算法】排序——归并排序和计数排序

主页点击直达&#xff1a;个人主页 我的小仓库&#xff1a;代码仓库 C语言偷着笑&#xff1a;C语言专栏 数据结构挨打小记&#xff1a;初阶数据结构专栏 Linux被操作记&#xff1a;Linux专栏 LeetCode刷题掉发记&#xff1a;LeetCode刷题 算法头疼记&#xff1a;算法专栏…

回归预测|GWO-BPNN-Adaboost算法原理及其实现(Matlab)

在上一篇文章中介绍了BPNN-Adaboost算法的原理及其实现&#xff0c;Adaboost算法可以将多个BPNN作为弱分类器进行训练&#xff0c;使其相互补充&#xff0c;集成为具有较强鲁棒性的强分类器。但由于BPNN对于初始权值和阈值的选取具有随机性&#xff0c;这将导致模型精度的不定性…

【易语言】m3u8下载器源码

前阵子接了个下载视频的小单子&#xff0c;部分视频是m3u8链接的&#xff0c;临时弄了个批量下载器&#xff0c;如图&#xff1a; 这东西网上虽然很多&#xff0c;但还是喜欢自己折腾一下&#xff0c;就直接开源了。代码好不好&#xff0c;只看能不能跑。 原理就是调用ffmpeg&a…

Polygon Mide状态模型:解决状态膨胀,而不牺牲隐私和去中心化

1. 引言 前序博客有&#xff1a; Polygon Miden&#xff1a;扩展以太坊功能集的ZK-optimized rollupPolygon Miden zkRollup中的UTXO账户混合状态模型Polygon Miden交易模型&#xff1a;Actor模式 ZKP &#xff1e; 并行 隐私 在Polygon Miden交易模型&#xff1a;Actor模…

国庆day5

客户端 #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);socket new QTcpSocket(this);//此时&#xff0c;已经向服务器发送连接请求了&#xff0c;如果成功连…

安全防御—密码学

1. 什么是APT&#xff1f; APT&#xff08;Advanced Persistent Threat&#xff09;是指高级持续性威胁&#xff0c;本质是针对性攻击。 利用先进的攻击手段对特定目标进行长期持续性网络攻击的攻击形式&#xff0c;APT攻击的原理相对于其他攻击形式更为高级和先进&#xff0c;…

一文教你搞懂Redis集群

一、Redis主从 1.1、搭建主从架构 单节点的Redis的并发能力是有上限的&#xff0c;要进一步的提高Redis的并发能力&#xff0c;据需要大家主从集群&#xff0c;实现读写分离。 共包含三个实例&#xff0c;由于资源有限&#xff0c;所以在一台虚拟机上&#xff0c;开启多个red…

第八章 排序 一、排序的基本概念

目录 一、定义 二、排序算法的评价指标 1、算法的稳定性 2、时间复杂度和空间复杂度 三、排序算法的分类 &#xff08;1&#xff09;内部排序 &#xff08;2&#xff09;外部排序 一、定义 排序是将一组数据按照一定的规则或条件进行重新排列的过程&#xff0c;使得数据…

代码随想录第35天 | ● 01背包问题,你该了解这些! ● 01背包问题—— 滚动数组 ● 416. 分割等和子集

01背包 题目 有n件物品和一个最多能背重量为w 的背包。第i件物品的重量是weight[i]&#xff0c;得到的价值是value[i] 。每件物品只能用一次&#xff0c;求解将哪些物品装入背包里物品价值总和最大。 代码 function testWeightBagProblem (weight, value, size) {// 定义 d…

【已解决】spring-boot项目使用maven打包时出现BOOT-INF文件夹的问题

jar中多了这个BOOT-INF文件夹的原因&#xff0c;主要是因为我们在maven的pom文件中加入了spring-boot-maven-plugin这个插件&#xff0c;如下所示&#xff1a; 只需要将加个configuration标签&#xff0c;并在里面嵌套加入一个skip子标签&#xff0c;并将skip的值设为true&…

实现文档AI搜索,提高问题解决效率

在当今的数字时代&#xff0c;以AI为动力的文档搜索变得越来越重要。随着在线提供信息的指数增长&#xff0c;传统的搜索方法通常效率低下且耗时。实施文档AI搜索可以显著提高搜索相关文档的效率和有效性。 | 在网站中实施文档AI搜索的好处很多 首先&#xff0c;它通过提供无缝…