草庐IT

boston数据集预测房价

Yangmird 2023-07-17 原文

                 一:boston数据集

    Boston数据集各个特征的含义如下:

特征值

特征值含义

CRIM

城镇人均犯罪率

ZN

住宅用地所占比例

INDUS

城镇中非住宅用地所占比例

CHAS

虚拟变量,用于回归分析

NOX

环保指数

RM

每栋住宅的房间数

AGE

1940 年以前建成的自住单位的比例

DIS

距离 5 个波士顿的就业中心的加权距离

RAD

距离高速公路的便利指数

TAX

每一万美元的不动产税率

PTRATIO

城镇中的教师学生比例

B

城镇中的黑人比例

LSTAT

地区中有多少房东属于低收入人群

MEDV

自住房屋房价中位数(也就是均价)

   

波士顿房价数据集包括506个样本,每个样本包括12个特征变量和该地区的平均房价,房价显然和多个特征变量相关,先选择亿元线性回归与多个特征建立线性方程,观察模型预测的好坏,再选择多元线性回归进行房价预测。

建立线性模型

二:boston数据处理及模型建立

2.1加载boston数据集

import pandas as pd

import numpy as np

import matplotlib

matplotlib.rcParams['font.sans-serif'] = ['SimHei']

matplotlib.rcParams['font.family'] = 'sans-serif'

matplotlib.rcParams['axes.unicode_minus'] = False

import matplotlib.pyplot as plt

from sklearn import datasets

# 获取数据

boston = datasets.load_boston()

print(boston)

boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)

boston_df['MEDV'] = boston.target  # 房价-----y

    查看数据:

# 查看数据是否存在空值,从结果来看数据不存在空值。

boston_df.isnull().sum()

可以看出,boston数据集中有14个特征,并且没有缺失值,所以不用做缺失值处理,其中’MEDV’作为目标值。

# 查看数据大小

boston_df.shape

# 查看数据的描述信息,在描述信息里可以看到每个特征的均值,最大值,最小值等信息。

boston_df.describe()

# 看看各个特征中是否有相关性,判断一下用哪种模型比较合适

import seaborn as sns

plt.figure(figsize=(12,8))

sns.heatmap(boston_df.corr(), annot=True, fmt='.2f',cmap='PuBu')

从上图可以看出数据不存在相关性较小的属性,也不用担心共线性,所以可以用线性回归模型去预测。

2.2 画出各个特征与MEDV房价的散点图

   # 各个特征和MEDV房价的散点图

boston_df_xTitle=['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT']

for i in range(0,len(boston_df_xTitle)):

      plt.figure(facecolor='white')

          plt.scatter(boston_df[str(boston_df_xTitle[i])], boston_df['MEDV'], s=30, edgecolor='white')

    plt.title(str(boston_df_xTitle[i])+'--------MEDV')

    plt.xlabel(str(boston_df_xTitle[i]))

    plt.ylabel('MEDV房价')

    plt.show()

从上图可以看出’RM’,’LSTAT’,’CRIM’这三个特征值与房价存在一定的相关性,所以选择该三个特征作为特征值,移除其余不相关的特征值。

# 定义目标值和特征值

# 分析房屋的’RM’, ‘LSTAT’,'CRIM’ 特征与MEDV的相关性性,所以,将其余不相关特征移除

new_boston_df = boston_df[['LSTAT', 'CRIM', 'RM', 'MEDV']]

# print('describe:      ')

# new_boston_df.describe()

#  目标值

y = np.array(new_boston_df['MEDV'])

# drop函数默认删除行,列需要加axis=1

new_boston_df = new_boston_df.drop(['MEDV'], axis=1)

# 特征值

X = np.array(new_boston_df)

2.3划分训练集和测试集

由于数据没有null值,并且,都是连续型数据,所以暂时不用对数据进行过多的处理,不够既然要建立模型,首先就要进行对boston数据集分为训练集和测试集,取出了大概百分之30的数据作为测试集,剩下的百分之70为训练集

# 划分训练集和测试集

from sklearn.model_selection import train_test_split

# 70%用于训练,30%用于测试

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=10)

print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

2.4建立线性回归模型

 # 线性回归-------------------------------------------------

from sklearn.linear_model import LinearRegression

from sklearn.preprocessing import StandardScaler

lr = LinearRegression()

# ss=StandardScaler()

# 使用训练数据进行参数估计

lr.fit(X_train, y_train)

# 输出线性回归的系数

print('线性回归的系数为:\n w=%s\n b=%s ' % (lr.coef_, lr.intercept_))

lr_reg_pre=lr.predict(X_test)

# -----------------------------------------------------------

2.5计算MAE和MSE

# 进行预测

# 使用测试数据进行回归预测

y_test_pred = lr.predict(X_test)

print('y_test_pred:\n', y_test_pred)

# 训练数据的预测值

y_train_pred = lr.predict(X_train)

print('y_train_pred : \n ', y_train_pred)

# 计算平均绝对误差MAE

train_MAE=mean_absolute_error(y_train,y_train_pred)

print('MAE为:',train_MAE)

#  计算均方误差MSE

train_MSE=mean_squared_error(y_train,y_train_pred) # 训练值与训练预测值之间的对比

print('MSE为:',train_MSE)

# 绘制MAE和MSE图

2.6画出学习曲线

    from sklearn.model_selection import  learning_curve,ShuffleSplit

def plot_learning_curve(plt,estimator,title,X,y,

ylim=None,cv=None,n_jobs=1,train_sizes=np.linspace(.1,1.0,5)):

      plt.title(title)

      if ylim is not None:

         plt.ylim(ylim)

      plt.xlabel("Training examples")

      plt.ylabel("Score")

train_sizes,train_scores,test_scores=learning_curve(estimator,X,y,cv=cv,n_jobs=n_jobs,train_sizes=train_sizes)

     train_scores_mean=np.mean(train_scores,axis=1)

     train_scores_std=np.std(train_scores,axis=1)

     test_scores_mean=np.mean(test_scores,axis=1)

     test_scores_std=np.std(test_scores,axis=1)

     plt.grid()

     plt.fill_between(train_sizes,train_scores_mean-train_scores_std,train_scores_mean+train_scores_std,alpha=0.1,color="r")

     plt.fill_between(train_sizes,test_scores_mean-test_scores_std,test_scores_mean+test_scores_std,alpha=0.1,color="g")

     plt.plot(train_sizes,train_scores_mean,'o--',color="r",label="Training scores")

     plt.plot(train_sizes,test_scores_mean,'o-',color="g",label="Cross-validation score")

     plt.legend(loc="best")

     return plt

cv=ShuffleSplit(n_splits=10,test_size=0.2,random_state=0)

plt.figure(figsize=(10,6))

plot_learning_curve(plt,lr,"Learn Curve for LinearRegression",new_boston_df,y,ylim=None,cv=cv)

plt.show()

    可以看出,模型有些欠拟合,需要优化,考虑使用二项式、三项式进行优化。

三:模型优化及结果分析

3.1模型优化

    # 定义划分数据集函数

def split_data():

    X=boston.data

    y=boston.target

    print(boston.feature_names)

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)

    return (X, y, X_train, X_test, y_train, y_test)

# 定义MAE函数

def mae_value(y_train,y_train_pred):

    n=len(y_train)

    mae=mean_absolute_error(y_train,y_train_pred)

    return  mae

# 定义MSE函数

def mse_value(y_train,y_train_pred):

    n=len(y_train)

    mse=mean_squared_error(y_train,y_train_pred)

    return  mse

# 定义多项式模型函数

from sklearn.preprocessing import PolynomialFeatures

from sklearn.pipeline import Pipeline

def polynomial_regression(degree=1):

    polynomial_features=PolynomialFeatures(degree=degree,include_bias=False)

    # 模型开启数据归一化

    linear_regression_model=LinearRegression(normalize=True)

    model=Pipeline([("polynomial_features", polynomial_features),

                    ("linear_regression", linear_regression_model)])

    return  model

# 训练模型

def train_model(X_train, X_test, y_train, y_test,degrees):

    res=[]

    for degree in degrees:

        model=polynomial_regression(degree)

        model.fit(X_train,y_train)

        train_score=model.score(X_train,y_train)*100

        test_score = model.score(X_test, y_test)*100

        res.append({'model':model,'degree':degree,'train_score':train_score,'test_score':test_score})

        y_test_predict=model.predict(X_test)

        mae=mae_value(y_test,y_test_predict)

        mse=mse_value(y_test,y_test_predict)

        print("degree:",degree, "MAE:",mae,"MSE",mse)

    for r in res:

        print("degree:{};train_score:{}".format(r["degree"],r["train_score"],r["test_score"]))

    return res

# 定义画出学习曲线的函数

from sklearn.model_selection import learning_curve

def plot_learning_curve(plt,estimator,title,X,y,ylim=None,cv=None,n_jobs=1,train_sizes=np.linspace(.1,1.0,5)):

   plt.title(title)

   if ylim is not None:

     plt.ylim(ylim)

   plt.xlabel("Training examples")

   plt.ylabel("Score")

   train_sizes,train_scores,test_scores=learning_curve(estimator,X,y,cv=cv,n_jobs=n_jobs,train_sizes=train_sizes)

    train_scores_mean=np.mean(train_scores,axis=1)

    train_scores_std=np.std(train_scores,axis=1)

    test_scores_mean=np.mean(test_scores,axis=1)

    test_scores_std=np.std(test_scores,axis=1)

    plt.grid()

  plt.fill_between(train_sizes,train_scores_mean-train_scores_std,train_scores_mean+train_scores_std,alpha=0.1,color="r")

   plt.fill_between(train_sizes,test_scores_mean-test_scores_std,test_scores_mean+test_scores_std,alpha=0.1,color="g")

   plt.plot(train_sizes,train_scores_mean,'o--',color="r",label="Training scores")

   plt.plot(train_sizes,test_scores_mean,'o-',color="g",label="Cross-validation score")

   plt.legend(loc="best")

   return plt

# 定义1、2、3次多项式

degrees=[1,2,3,4]

# 划分数据集

X, y, X_train, X_test, y_train, y_test = split_data()

#训练模型,并打印train score

res = train_model(X_train, X_test, y_train, y_test, degrees)

# 画出学习曲线

from sklearn.model_selection import ShuffleSplit

cv=ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)

plt.figure(figsize=(10,6))

for index,data in enumerate(res):

 plot_learning_curve(plt,data["model"],"degree%d"%data["degree"],X,y,cv=cv)

   plt.show()

3.2结果分析

    模型优化结果如下:

    Degree=1时学习曲线如下:

Degree=2时学习曲线如下:

Degree=3时学习曲线如下:

Degree=4时学习曲线如下:

    根据上述模型优化结果分析可知,二次多项式效果较好,训练准确度达到了92.9%,MAE=2.36,MSE=8.67,比一次多项式的训练准确度72.8%要更准确。

有关boston数据集预测房价的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  3. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  4. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  5. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

  6. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

  7. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

  8. STM32读取串口传感器数据(颗粒物传感器,主动上传) - 2

    文章目录1.开发板选择*用到的资源2.串口通信(个人理解)3.代码分析(注释比较详细)1.主函数2.串口1配置3.串口2配置以及中断函数4.注意问题5.源码链接1.开发板选择我用的是STM32F103RCT6的板子,不过代码大概在F103系列的板子上都可以运行,我试过在野火103的霸道板上也可以,主要看一下串口对应的引脚一不一样就行了,不一样的就更改一下。*用到的资源keil5软件这里用到了两个串口资源,采集数据一个,串口通信一个,板子对应引脚如下:串口1,TX:PA9,RX:PA10串口2,TX:PA2,RX:PA32.串口通信(个人理解)我就从串口采集传感器数据这个过程说一下我自己的理解,

  9. SPI接收数据异常问题总结 - 2

    SPI接收数据左移一位问题目录SPI接收数据左移一位问题一、问题描述二、问题分析三、探究原理四、经验总结最近在工作在学习调试SPI的过程中遇到一个问题——接收数据整体向左移了一位(1bit)。SPI数据收发是数据交换,因此接收数据时从第二个字节开始才是有效数据,也就是数据整体向右移一个字节(1byte)。请教前辈之后也没有得到解决,通过在网上查阅前人经验终于解决问题,所以写一个避坑经验总结。实际背景:MCU与一款芯片使用spi通信,MCU作为主机,芯片作为从机。这款芯片采用的是它规定的六线SPI,多了两根线:RDY和INT,这样从机就可以主动请求主机给主机发送数据了。一、问题描述根据从机芯片手

  10. 微信小程序通过字典表匹配对应数据 - 2

    前言一般来说,前端根据后台返回code码展示对应内容只需要在前台判断code值展示对应的内容即可,但要是匹配的code码比较多或者多个页面用到时,为了便于后期维护,后台就会使用字典表让前端匹配,下面我将在微信小程序中通过wxs的方法实现这个操作。为什么要使用wxs?{{method(a,b)}}可以看到,上述代码是一个调用方法传值的操作,在vue中很常见,多用于数据之间的转换,但由于微信小程序诸多限制的原因,你并不能优雅的这样操作,可能有人会说,为什么不用if判断实现呢?但是if判断的局限性在于如果存在数据量过大时,大量重复性操作和if判断会让你的代码显得异常冗余。wxswxs相当于是一个独立

随机推荐