用Python研究了三千套房子,告诉你究竟是什么抬高了房价?

关于房价,一直都是全民热议的话题,毕竟不少人终其一生都在为之奋斗。

房地产的泡沫究竟有多大不得而知?今天我们抛开泡沫,回归房屋最本质的内容,来分析一下房价的影响因素究竟是什么?

1、导入数据

  
  
  1. import numpy as np

  2. import pandas as pd

  3. import matplotlib.pyplot as plt

  4. import seaborn as sn

  5. import missingno as msno

  6. %matplotlib inline

  7. train = pd.read_csv('train.csv',index_col=0) #导入训练集

  8. test = pd.read_csv('test.csv',index_col=0) #导入测试集

  9. train.head(3)

  
  
  1. print('train训练集缺失数据分布图')

  2. msno.matrix(train)

  
  

  1. print('test测试集缺失数据分布图')

  2. msno.matrix(test)

从上面的数据缺失可视化图中可以看出,部分特征的数据缺失十分严重,下面我们来对特征的缺失数量进行统计。

2、目标Y值分析

  
  
  1. ##分割Y和X数据

  2. y=train['SalePrice']

  3. #看一下y的值分布

  4. prices = pd.DataFrame({'price':y,'log(price+1)':np.log1p(y)})

  5. prices.hist()

观察目标变量y的分布和取对数后的分布看,取完对数后更倾向于符合正太分布,故我们对y进行对数转化。

  
  
  1. y = np.log1p(y)#+1的目的是防止对数转化后的值无意义

3、合并数据 缺失处理

  
  
  1. #合并训练特征和测试集

  2. all_df = pd.concat((X,test),axis=0)

  3. print('all_df缺失数据图')

  4. msno.matrix(all_df)

  
  
  1. #定义缺失统计函数

  2. def show_missing(feature):

  3.    missing = feature.columns[feature.isnull().any()].tolist()

  4.    return missing

  5. print('缺失特征的数据缺失量统计:')

  6. all_df[show_missing(all_df)].isnull().sum()

  
  
  1. #先处理numeric数值型数据

  2. #挨个儿看一下分布

  3. fig,axs = plt.subplots(3,2,figsize=(16,9))

  4. all_df['BsmtFinSF1'].hist(ax = axs[0,0])#众数填充

  5. all_df['BsmtFinSF2'].hist(ax = axs[0,1])#众数

  6. all_df['BsmtUnfSF'].hist(ax =  axs[1,0])#中位数

  7. all_df['TotalBsmtSF'].hist(ax = axs[1,1])#均值填充

  8. all_df['BsmtFullBath'].hist(ax = axs[2,0])#众数

  9. all_df['BsmtHalfBath'].hist(ax = axs[2,1])#众数

  10. #lotfrontage用均值填充

  11. mean_lotfrontage = all_df.LotFrontage.mean()

  12. all_df.LotFrontage.hist()

  13. print('用均值填充:')

  14. cat_input(all_df,'LotFrontage',mean_lotfrontage)

  
  
  1. cat_input(all_df,'BsmtFinSF1',0.0)

  2. cat_input(all_df,'BsmtFinSF2',0.0)

  3. cat_input(all_df,'BsmtFullBath',0.0)

  4. cat_input(all_df,'BsmtHalfBath',0.0)

  5. cat_input(all_df,'BsmtUnfSF',467.00)

  6. cat_input(all_df,'TotalBsmtSF',1051.78)

  
  
  1. #在处理字符型,同样,挨个看下分布

  2. fig,axs = plt.subplots(4,2,figsize=(16,9))

  3. all_df['MSZoning'].hist(ax = axs[0,0])#众数填充

  4. all_df['Utilities'].hist(ax = axs[0,1])#众数

  5. all_df['Exterior1st'].hist(ax =  axs[1,0])#众数

  6. all_df['Exterior2nd'].hist(ax = axs[1,1])#众数填充

  7. all_df['KitchenQual'].hist(ax = axs[2,0])#众数

  8. all_df['Functional'].hist(ax = axs[2,1])#众数

  9. all_df['SaleType'].hist(ax = axs[3,0])#众数

  
  
  1. cat_input(all_df,'MSZoning','RL')

  2. cat_input(all_df,'Utilities','AllPub')

  3. cat_input(all_df,'Exterior1st','VinylSd')

  4. cat_input(all_df,'Exterior2nd','VinylSd')

  5. cat_input(all_df,'KitchenQual','TA')

  6. cat_input(all_df,'Functional','Typ')

  7. cat_input(all_df,'SaleType','WD')

  8. #再看一下缺失分布

  9. msno.matrix(all_df)

binggo,数据干净啦!下面开始处理特征,经过上述略微复杂的处理,数据集中所有的缺失数据都已处理完毕,可以开始接下来的工作啦!

缺失处理总结:在本篇文章所使用的数据集中存在比较多的缺失,缺失数据包括数值型和字符型,处理原则主要有两个:

一、根据绘制数据分布直方图,观察数据分布的状态,采取合适的方式填充缺失数据;

二、非常重要的特征描述,认真阅读,按照特征描述填充可以解决大部分问题。

4、特征处理

让我们在重新仔细审视一下数据有没有问题?仔细观察发现MSSubClass特征实际上是分类特征,但是数据显示是int类型,这个需要改成str。

  
  
  1. #观察特征属性发现,MSSubClass是分类特征,但是数据给的是数值型,需要对其做转换

  2. all_df['MSSubClass']=all_df['MSSubClass'].astype(str)

  3. #将分类变量转变成数值变量

  4. all_df = pd.get_dummies(all_df)

  5. print('分类变量转换完成后有{}行{}列'.format(*all_df.shape))

分类变量转换完成后有2919行316列

  
  
  1. #标准化处理

  2. numeric_cols = all_df.columns[all_df.dtypes !='uint8']

  3. #x-mean(x)/std(x)

  4. numeric_mean = all_df.loc[:,numeric_cols].mean()

  5. numeric_std = all_df.loc[:,numeric_cols].std()

  6. all_df.loc[:,numeric_cols] = (all_df.loc[:,numeric_cols]-numeric_mean)/numeric_std

再把数据拆分到训练集和测试集

  
  
  1. train_df = all_df.ix[0:1460]#训练集

  2. test_df = all_df.ix[1461:] #测试集

5、构建基准模型

  
  
  1. from sklearn import cross_validation

  2. from sklearn import linear_model

  3. from sklearn.learning_curve import learning_curve

  4. from sklearn.metrics import explained_variance_score

  5. from sklearn.grid_search import GridSearchCV

  6. from sklearn.model_selection import cross_val_score

  7. from sklearn.ensemble import RandomForestRegressor

  8. y = y.values #转换成array数组

  9. X = train_df.values #转换成array数组

  
  
  1. cv = cross_validation.ShuffleSplit(len(X),n_iter=3,test_size=0.2)

  2. print('岭回归交叉验证结果:')

  3. for train_index,test_index in cv:

  4.    ridge = linear_model.Ridge(alpha=1).fit(X,y)

  5.    print('train_score:{0:.3f},test_score:{1:.3f}\n'.format(ridge.score(X[train_index],y[train_index]),

  6.                                                            ridge.score(X[test_index],y[test_index])))

  7. print('随机森林交叉验证结果:')

  8. for train_index,test_index in cv:

  9.    rf = RandomForestRegressor().fit(X,y)

  10.    print('train_score:{0:.3f},test_score:{1:.3f}\n'.format(rf.score(X[train_index],y[train_index]),

  11.                                                            rf.score(X[test_index],y[test_index])))

哇!好意外啊,这两个模型的结果表现都不错,但是随机森林的结果似乎更好,下面来看看学习曲线情况。

我们采用的是默认的参数,没有调优处理,得到的两个基准模型都存在过拟合现象。下面,我们开始着手参数的调整,希望能够改善模型的过拟合现象。

6、参数调优

岭回归正则项缩放系数alpha调整

  
  
  1. alphas =[0.01,0.1,1,10,20,50,100,300]

  2. test_scores = []

  3. for alp in alphas:

  4.    clf = linear_model.Ridge(alp)

  5.    test_score = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

  6.    test_scores.append(np.mean(test_score))

  7. import matplotlib.pyplot as plt

  8. %matplotlib inline

  9. plt.plot(alphas,test_scores)

  10. plt.title('alpha vs test_score')

alpha在10-20附近均方误差最小

随机森林参数调优

随机森林算法,本篇中主要调整三个参数:maxfeatures,maxdepth,n_estimators

  
  
  1. #随机森林的深度参数

  2. max_depth=[2,4,6,8,10]

  3. test_scores_depth = []

  4. for depth in max_depth:

  5.    clf = RandomForestRegressor(max_depth=depth)

  6.    test_score_depth = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

  7.    test_scores_depth.append(np.mean(test_score_depth))

  8. #随机森林的特征个数参数

  9. max_features =[.1, .3, .5, .7, .9, .99]

  10. test_scores_feature = []

  11. for feature in max_features:

  12.    clf = RandomForestRegressor(max_features=feature)

  13.    test_score_feature = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

  14.    test_scores_feature.append(np.mean(test_score_feature))

  15. #随机森林的估计器个位数参数

  16. n_estimators =[10,50,100,200,500]

  17. test_scores_n = []

  18. for n in n_estimators:

  19.    clf = RandomForestRegressor(n_estimators=n)

  20.    test_score_n = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

  21.    test_scores_n.append(np.mean(test_score_n))

随机森林的各项参数来看,深度位于8,选择特征个数比例为0.5,估计器个数为500时,效果最好。下面分别利用上述得到的最优参数分别重新训练,看一下学习曲线,过拟合现象是否得到缓解?

再回想一下,我们最初的基线模型学习曲线的形状,是不是得到了一定程度的缓解?OK,下面我们采用模型融合技术,对数据进行预测。

  
  
  1. #预测

  2. ridge = linear_model.Ridge(alpha=10).fit(X,y)

  3. rf = RandomForestRegressor(n_estimators=500,max_depth=8,max_features=.5).fit(X,y)

  4. y_ridge = np.expm1(ridge.predict(test_df.values))

  5. y_rf = np.expm1(rf.predict(test_df.values))

  6. y_final = (y_ridge + y_rf)/2

本篇房价预测的模型搭建已经完成。同样,再梳理一边思路:

一、本篇用到的房价数据集存在比较多的数据缺失,且分类变量十分多。在预处理阶段需要将训练集和测试集合并,进行缺失填充和one-hot独热变量处理,保证数据处理过程的一致性,在数据缺失填充过程中,需要综合考虑特征的实际描述和数据的分布,选择合适的填充方式填充;

二、为防止数据变量不统一带来的模型准确率下降,将数值型特征进行标准化处理,数据处理完成后,按照数据合并的方式,再还原到训练集和测试集;

三、先构建岭回归和随机森林基准模型,进行三折交叉验证,绘制学习曲线,存在明显的过拟合现象;

四、接下来分别对两个基准模型进行参数调优,获得使得均方误差最小的参数,返回到训练集进行训练;

五、采用并行模型融合的方式,计算两个模型预测结果的均值作为测试集的预测结果。

赞赏作者


本文作者

熊小莉

Python中文社区专栏作者。985硕士,本科统计专业,迷途知返的统计人,热爱数学,喜欢数据,狂爱钻研,目前转型做数据挖掘工程师,期待与更多同业人交流。

现在能赶上房价涨幅的,恐怕只有比特币了!

点击阅读原文加入币圈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值