偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

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

開發(fā) 后端 數(shù)據(jù)分析
關于房價,一直都是全民熱議的話題,畢竟不少人終其一生都在為之奮斗。房地產(chǎn)的泡沫究竟有多大不得而知?今天我們拋開泡沫,回歸房屋最本質(zhì)的內(nèi)容,來分析一下房價的影響因素究竟是什么?

[[217972]]

關于房價,一直都是全民熱議的話題,畢竟不少人終其一生都在為之奮斗。

房地產(chǎn)的泡沫究竟有多大不得而知?今天我們拋開泡沫,回歸房屋最本質(zhì)的內(nèi)容,來分析一下房價的影響因素究竟是什么?

1、導入數(shù)據(jù)

 

  1. import numpy as np 
  2.  
  3. import pandas as pd 
  4.  
  5. import matplotlib.pyplot as plt 
  6.  
  7. import seaborn as sn 
  8.  
  9. import missingno as msno 
  10.  
  11. %matplotlib inline 
  12.  
  13. train = pd.read_csv('train.csv',index_col=0)  
  14.  
  15. #導入訓練集 
  16.  
  17. test = pd.read_csv('test.csv',index_col=0)  
  18.  
  19. #導入測試集 
  20.  
  21. train.head(3) 
  22.  
  23. print('train訓練集缺失數(shù)據(jù)分布圖'
  24.  
  25. msno.matrix(train) 
  26.  
  27. print('test測試集缺失數(shù)據(jù)分布圖'
  28.  
  29. msno.matrix(test) 

從上面的數(shù)據(jù)缺失可視化圖中可以看出,部分特征的數(shù)據(jù)缺失十分嚴重,下面我們來對特征的缺失數(shù)量進行統(tǒng)計。

2、目標Y值分析 

  1. ##分割Y和X數(shù)據(jù) 
  2.  
  3. y=train['SalePrice'
  4.  
  5. #看一下y的值分布 
  6.  
  7. prices = pd.DataFrame({'price':y,'log(price+1)':np.log1p(y)}) 
  8.  
  9. prices.hist() 

觀察目標變量y的分布和取對數(shù)后的分布看,取完對數(shù)后更傾向于符合正太分布,故我們對y進行對數(shù)轉化。 

  1. y = np.log1p(y) #+1的目的是防止對數(shù)轉化后的值無意義 

3、合并數(shù)據(jù) 缺失處理 

  1. #合并訓練特征和測試集 
  2.  
  3. all_df = pd.concat((X,test),axis=0) 
  4.  
  5. print('all_df缺失數(shù)據(jù)圖'
  6.  
  7. msno.matrix(all_df) 
  8.  
  9. #定義缺失統(tǒng)計函數(shù) 
  10.  
  11. def show_missing(feature): 
  12.  
  13.     missing = feature.columns[feature.isnull().any()].tolist()     
  14.  
  15. return  missing 
  16.  
  17. print('缺失特征的數(shù)據(jù)缺失量統(tǒng)計:'
  18.  
  19. all_df[show_missing(all_df)].isnull().sum() 
  20.  
  21. #先處理numeric數(shù)值型數(shù)據(jù) 
  22.  
  23. #挨個兒看一下分布 
  24.  
  25. fig,axs = plt.subplots(3,2,figsize=(16,9)) 
  26.  
  27. all_df['BsmtFinSF1'].hist(ax = axs[0,0])#眾數(shù)填充 
  28.  
  29. all_df['BsmtFinSF2'].hist(ax = axs[0,1])#眾數(shù) 
  30.  
  31. all_df['BsmtUnfSF'].hist(ax =  axs[1,0])#中位數(shù) 
  32.  
  33. all_df['TotalBsmtSF'].hist(ax = axs[1,1])#均值填充 
  34.  
  35. all_df['BsmtFullBath'].hist(ax = axs[2,0])#眾數(shù) 
  36.  
  37. all_df['BsmtHalfBath'].hist(ax = axs[2,1])#眾數(shù) 
  38.  
  39. #lotfrontage用均值填充 
  40.  
  41. mean_lotfrontage = all_df.LotFrontage.mean() 
  42.  
  43. all_df.LotFrontage.hist() 
  44.  
  45. print('用均值填充:'
  46.  
  47. cat_input(all_df,'LotFrontage',mean_lotfrontage) 
  48.  
  49. cat_input(all_df,'BsmtFinSF1',0.0) 
  50.  
  51. cat_input(all_df,'BsmtFinSF2',0.0) 
  52.  
  53. cat_input(all_df,'BsmtFullBath',0.0) 
  54.  
  55. cat_input(all_df,'BsmtHalfBath',0.0) 
  56.  
  57. cat_input(all_df,'BsmtUnfSF',467.00) 
  58.  
  59. cat_input(all_df,'TotalBsmtSF',1051.78) 
  60.  
  61. #在處理字符型,同樣,挨個看下分布 
  62.  
  63. fig,axs = plt.subplots(4,2,figsize=(16,9)) 
  64.  
  65. all_df['MSZoning'].hist(ax = axs[0,0])#眾數(shù)填充 
  66.  
  67. all_df['Utilities'].hist(ax = axs[0,1])#眾數(shù) 
  68.  
  69. all_df['Exterior1st'].hist(ax =  axs[1,0])#眾數(shù) 
  70.  
  71. all_df['Exterior2nd'].hist(ax = axs[1,1])#眾數(shù)填充 
  72.  
  73. all_df['KitchenQual'].hist(ax = axs[2,0])#眾數(shù) 
  74.  
  75. all_df['Functional'].hist(ax = axs[2,1])#眾數(shù) 
  76.  
  77. all_df['SaleType'].hist(ax = axs[3,0])#眾數(shù) 
  78.  
  79. cat_input(all_df,'MSZoning','RL'
  80.  
  81. cat_input(all_df,'Utilities','AllPub'
  82.  
  83. cat_input(all_df,'Exterior1st','VinylSd'
  84.  
  85. cat_input(all_df,'Exterior2nd','VinylSd'
  86.  
  87. cat_input(all_df,'KitchenQual','TA'
  88.  
  89. cat_input(all_df,'Functional','Typ'
  90.  
  91. cat_input(all_df,'SaleType','WD'
  92.  
  93. #再看一下缺失分布 
  94.  
  95. msno.matrix(all_df) 

binggo,數(shù)據(jù)干凈啦!下面開始處理特征,經(jīng)過上述略微復雜的處理,數(shù)據(jù)集中所有的缺失數(shù)據(jù)都已處理完畢,可以開始接下來的工作啦!

缺失處理總結:在本篇文章所使用的數(shù)據(jù)集中存在比較多的缺失,缺失數(shù)據(jù)包括數(shù)值型和字符型,處理原則主要有兩個:

一、根據(jù)繪制數(shù)據(jù)分布直方圖,觀察數(shù)據(jù)分布的狀態(tài),采取合適的方式填充缺失數(shù)據(jù);

二、非常重要的特征描述,認真閱讀,按照特征描述填充可以解決大部分問題。

4、特征處理

讓我們在重新仔細審視一下數(shù)據(jù)有沒有問題?仔細觀察發(fā)現(xiàn)MSSubClass特征實際上是分類特征,但是數(shù)據(jù)顯示是int類型,這個需要改成str。 

  1. #觀察特征屬性發(fā)現(xiàn),MSSubClass是分類特征,但是數(shù)據(jù)給的是數(shù)值型,需要對其做轉換 
  2.  
  3. all_df['MSSubClass']=all_df['MSSubClass'].astype(str) 
  4.  
  5. #將分類變量轉變成數(shù)值變量 
  6.  
  7. all_df = pd.get_dummies(all_df) 
  8.  
  9. print('分類變量轉換完成后有{}行{}列'.format(*all_df.shape))  

分類變量轉換完成后有2919行316列 

  1. #標準化處理 
  2.  
  3. numeric_cols = all_df.columns[all_df.dtypes !='uint8'
  4.  
  5. #x-mean(x)/std(x) 
  6.  
  7. numeric_mean = all_df.loc[:,numeric_cols].mean() 
  8.  
  9. numeric_std = all_df.loc[:,numeric_cols].std() 
  10.  
  11. all_df.loc[:,numeric_cols] = (all_df.loc[:,numeric_cols]-numeric_mean)/numeric_std  

再把數(shù)據(jù)拆分到訓練集和測試集 

  1. train_df = all_df.ix[0:1460]#訓練集 
  2.  
  3. test_df = all_df.ix[1461:]#測試集  

5、構建基準模型 

  1. from sklearn import cross_validation 
  2.  
  3. from sklearn import linear_model 
  4.  
  5. from sklearn.learning_curve import learning_curve 
  6.  
  7. from sklearn.metrics import explained_variance_score 
  8.  
  9. from sklearn.grid_search import GridSearchCV 
  10.  
  11. from sklearn.model_selection import cross_val_score 
  12.  
  13. from sklearn.ensemble import RandomForestRegressor 
  14.  
  15. y = y.values #轉換成array數(shù)組 
  16.  
  17. X = train_df.values #轉換成array數(shù)組 
  18.  
  19. cv = cross_validation.ShuffleSplit(len(X),n_iter=3,test_size=0.2) 
  20.  
  21. print('嶺回歸交叉驗證結果:'
  22.  
  23. for train_index,test_index in cv: 
  24.  
  25.     ridge = linear_model.Ridge(alpha=1).fit(X,y)     
  26.  
  27.    print('train_score:{0:.3f},test_score:{1:.3f}\n'.format(ridge.score(X[train_index],y[train_index]), ridge.score(X[test_index],y[test_index]))) 
  28.  
  29. print('隨機森林交叉驗證結果:'
  30.  
  31. for train_index,test_index in cv: 
  32.  
  33.     rf = RandomForestRegressor().fit(X,y)     
  34.  
  35.     print('train_score:{0:.3f},test_score:{1:.3f}\n'.format(rf.score(X[train_index],y[train_index]), rf.score(X[test_index],y[test_index]))) 

哇!好意外啊,這兩個模型的結果表現(xiàn)都不錯,但是隨機森林的結果似乎更好,下面來看看學習曲線情況。

我們采用的是默認的參數(shù),沒有調(diào)優(yōu)處理,得到的兩個基準模型都存在過擬合現(xiàn)象。下面,我們開始著手參數(shù)的調(diào)整,希望能夠改善模型的過擬合現(xiàn)象。

6、參數(shù)調(diào)優(yōu)

嶺回歸正則項縮放系數(shù)alpha調(diào)整 

  1. alphas =[0.01,0.1,1,10,20,50,100,300] 
  2.  
  3. test_scores = [] 
  4.  
  5. for alp in alphas: 
  6.  
  7.     clf = linear_model.Ridge(alp) 
  8.  
  9.     test_score = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error'
  10.  
  11.     test_scores.append(np.mean(test_score)) 
  12.  
  13. import matplotlib.pyplot as plt 
  14.  
  15. %matplotlib inline 
  16.  
  17. plt.plot(alphas,test_scores) 
  18.  
  19. plt.title('alpha vs test_score'

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

隨機森林參數(shù)調(diào)優(yōu)

隨機森林算法,本篇中主要調(diào)整三個參數(shù):maxfeatures,maxdepth,n_estimators 

  1. #隨機森林的深度參數(shù) 
  2.  
  3. max_depth=[2,4,6,8,10] 
  4.  
  5. test_scores_depth = [] 
  6.  
  7. for depth in max_depth: 
  8.  
  9.     clf = RandomForestRegressor(max_depth=depth) 
  10.  
  11.     test_score_depth = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error'
  12.  
  13.     test_scores_depth.append(np.mean(test_score_depth)) 
  14.  
  15. #隨機森林的特征個數(shù)參數(shù) 
  16.  
  17. max_features =[.1, .3, .5, .7, .9, .99] 
  18.  
  19. test_scores_feature = [] 
  20.  
  21. for feature in max_features: 
  22.  
  23.     clf = RandomForestRegressor(max_features=feature) 
  24.  
  25.     test_score_feature = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error'
  26.  
  27.     test_scores_feature.append(np.mean(test_score_feature)) 
  28.  
  29. #隨機森林的估計器個位數(shù)參數(shù) 
  30.  
  31. n_estimators =[10,50,100,200,500] 
  32.  
  33. test_scores_n = [] 
  34.  
  35. for n in n_estimators: 
  36.  
  37.     clf = RandomForestRegressor(n_estimators=n) 
  38.  
  39.     test_score_n = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error'
  40.  
  41.     test_scores_n.append(np.mean(test_score_n)) 

隨機森林的各項參數(shù)來看,深度位于8,選擇特征個數(shù)比例為0.5,估計器個數(shù)為500時,效果***。下面分別利用上述得到的***參數(shù)分別重新訓練,看一下學習曲線,過擬合現(xiàn)象是否得到緩解?

再回想一下,我們最初的基線模型學習曲線的形狀,是不是得到了一定程度的緩解?OK,下面我們采用模型融合技術,對數(shù)據(jù)進行預測。 

  1. #預測 
  2.  
  3. ridge = linear_model.Ridge(alpha=10).fit(X,y) 
  4.  
  5. rf = RandomForestRegressor(n_estimators=500,max_depth=8,max_features=.5).fit(X,y) 
  6.  
  7. y_ridge = np.expm1(ridge.predict(test_df.values)) 
  8.  
  9. y_rf = np.expm1(rf.predict(test_df.values)) 
  10.  
  11. y_final = (y_ridge + y_rf)/2 

本篇房價預測的模型搭建已經(jīng)完成。同樣,再梳理一邊思路:

一、本篇用到的房價數(shù)據(jù)集存在比較多的數(shù)據(jù)缺失,且分類變量十分多。在預處理階段需要將訓練集和測試集合并,進行缺失填充和one-hot獨熱變量處理,保證數(shù)據(jù)處理過程的一致性,在數(shù)據(jù)缺失填充過程中,需要綜合考慮特征的實際描述和數(shù)據(jù)的分布,選擇合適的填充方式填充;

二、為防止數(shù)據(jù)變量不統(tǒng)一帶來的模型準確率下降,將數(shù)值型特征進行標準化處理,數(shù)據(jù)處理完成后,按照數(shù)據(jù)合并的方式,再還原到訓練集和測試集;

三、先構建嶺回歸和隨機森林基準模型,進行三折交叉驗證,繪制學習曲線,存在明顯的過擬合現(xiàn)象;

四、接下來分別對兩個基準模型進行參數(shù)調(diào)優(yōu),獲得使得均方誤差最小的參數(shù),返回到訓練集進行訓練; 

五、采用并行模型融合的方式,計算兩個模型預測結果的均值作為測試集的預測結果。 

責任編輯:龐桂玉 來源: Python中文社區(qū)
相關推薦

2019-07-24 11:21:18

Node.jsHTMLCSS

2015-06-09 14:49:38

2011-02-16 16:13:40

Debian

2021-03-08 21:44:33

以太坊區(qū)塊鏈比特幣

2018-03-29 10:19:45

2019-05-27 15:30:44

Node.jsJavaScript前端

2015-09-29 09:47:14

2018-09-10 13:47:21

數(shù)據(jù)科學統(tǒng)計學決策

2023-10-07 00:18:05

2011-08-04 13:24:28

IT運維

2014-07-28 08:28:38

Windows

2014-08-07 10:32:02

Windows微軟

2012-05-28 22:49:50

PureView

2009-07-30 14:43:30

認識BSM

2022-06-13 09:51:35

UWB超寬帶無線載波通信技術

2015-08-26 09:54:19

物聯(lián)網(wǎng)

2014-06-27 09:35:16

機器學習

2021-08-09 05:19:08

Provider 前端前端代碼

2022-02-07 15:20:53

去中心化加密經(jīng)濟學加密貨幣

2020-07-08 08:09:08

邊緣計算邊緣云云平臺
點贊
收藏

51CTO技術棧公眾號