一:前言
利用上次爬取的朝陽區(qū)房價數(shù)據(jù)诱告,通過簡單線性回歸模型、決策樹回歸模型吠架、xgboost回歸模型來進行房價預(yù)測效果對比芙贫,期間遇到一些問題和解決方法也記錄下來。
目的:練習(xí)相關(guān)sklearn傍药,xgboost模塊和學(xué)習(xí)驗證結(jié)果的方法磺平。
二:運行環(huán)境
- Anaconda Python 3.6
- xgboost 0.7
- scikit-learn 0.19.1
- pandas 0.20.3
安裝anaconda 后科學(xué)計算相關(guān)庫就有了,但是xgboost安裝沒有拐辽,需要下載軟件編譯xgboost的文件拣挪。這里我推薦一個更直接的方法:到這里下載對應(yīng)版本的xgboost
https://www.lfd.uci.edu/~gohlke/pythonlibs/
然后pip安裝即可,幾秒后你將擁有xgboost模塊俱诸。
pip install xgboost-0.7-cp36-cp36m-win_amd64.whl
三:引入模塊和數(shù)據(jù)
- 首先來導(dǎo)入相關(guān)模塊菠劝,這里的 learning_curve 用來查看訓(xùn)練的擬合過程,也可以利用validation_curve來確定相關(guān)模型里面的最佳參數(shù)乙埃,比如DecisionTreeRegressord闸英、XGBRegressor中的max_depth需要多次訓(xùn)練找出最佳值。
import pandas as pd
import numpy as np
from sklearn.learning_curve import learning_curve
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from xgboost import XGBRegressor
import matplotlib.pyplot as plt
- 下面是導(dǎo)入之前的數(shù)據(jù)介袜,取出合適的數(shù)據(jù)做為訓(xùn)練使用甫何。房屋一些大小,房價數(shù)目遇伞,每平米價格是自變量而價格是因變量辙喂,也就是需要預(yù)測的對象。
row_df = pd.read_csv('house_price.csv')
df = row_df[row_df.iloc[:,1] !='多']
data_X = df[['rooms','halls','size','unit_price']]
data_y = df.price
四:簡單線性回歸模型
引入模塊和數(shù)據(jù)后開始構(gòu)建回歸模型,LinearRegression() 是本次用的線性回歸巍耗,train_sizes=np.linspace(0.0, 1.0, num=30)[1:]
這個在可視化訓(xùn)練過程中對應(yīng)曲線多少個位置秋麸。0不取所以使用切片[1:]。cv=10
采用K折交叉驗證 scoring='r2'
表示采用R2的預(yù)測得分計算方法 也可以采用均方誤差炬太。
train_sizes, train_score, test_score = learning_curve(
LinearRegression(), data_X, data_y, cv=10, scoring='r2',
train_sizes=np.linspace(0.0, 1.0, num=30)[1:])
下面就是求取訓(xùn)練和測試過程中的預(yù)測得分情況灸蟆,然后show出來。
train_score_mean = np.mean(train_score, axis=1)
test_score_mean = np.mean(test_score, axis=1)
plt.plot(train_sizes, train_score_mean, 'o-', color="r",
label="Training")
plt.plot(train_sizes, test_score_mean, 'o-', color="g",
label="Validation")
print(train_score_mean.mean())
print(test_score_mean.mean())
plt.xlabel("Training examples")
plt.ylabel("Score")
plt.legend(loc="best")
plt.show()
通過圖示可以看到線性回歸的訓(xùn)練過程中亲族。訓(xùn)練和測試的得分趨于一個較為穩(wěn)定的值
0.925
五:決策樹回歸模型
決策樹的最大深度炒考,經(jīng)過測試發(fā)現(xiàn)16 的時候效果最好,然后采用R2標準來預(yù)測得分情況霎迫。
train_sizes, train_score, test_score = learning_curve(
DecisionTreeRegressor(max_depth=16), data_X, data_y, cv=10, scoring='r2',
train_sizes=np.linspace(0.0, 1.0, num=30)[1:])
train_score_mean = np.mean(train_score, axis=1)
test_score_mean = np.mean(test_score, axis=1)
plt.plot(train_sizes, train_score_mean, 'o-', color="r",
label="Training")
plt.plot(train_sizes, test_score_mean, 'o-', color="g",
label="Validation")
plt.xlabel("Training examples")
plt.ylabel("Score")
plt.legend(loc="best")
plt.show()
通過圖示可以看到?jīng)Q策樹回歸模型的測試的得分趨于 0.97 附近斋枢,效果要比簡單的線性回歸模型好很多了。
六:xgboost回歸模型回歸模型
XGBRegressor 經(jīng)測試每棵樹的最大深度在4效果最好知给,然后采用R2標準來預(yù)測得分情況瓤帚。
這里使用xgboost的過程中遇到一個問題:
AttributeError: 'DMatrix' object has no attribute 'handle'
查看前面報錯的信息后確定是:
ValueError: DataFrame.dtypes for data must be int, float or bool.
應(yīng)該是pandas數(shù)據(jù)類型錯誤所所以在使用xgboost訓(xùn)練的時候修改了數(shù)據(jù)
data_X = df[['rooms','halls','size','unit_price']].astype('int')
train_sizes, train_score, test_score = learning_curve(
XGBRegressor(max_depth=4), data_X, data_y, cv=10, scoring='r2',
train_sizes=np.linspace(0.0, 1.0, num=30)[1:])
train_score_mean = np.mean(train_score, axis=1)
test_score_mean = np.mean(test_score, axis=1)
plt.plot(train_sizes, train_score_mean, 'o-', color="r",
label="Training")
plt.plot(train_sizes, test_score_mean, 'o-', color="g",
label="Validation")
plt.xlabel("Training examples")
plt.ylabel("Score")
plt.legend(loc="best")
plt.show()
通過圖示可以看到xgboost回歸模型的測試的得分趨于 0.99 附近,效果要比簡單的線性回歸模型和決策樹回歸模型好很多涩赢。
七:總結(jié)
該項目代碼以及數(shù)據(jù)源全部存放于 github.com/rieuse/Machine_Learning
通過三個回歸模型的建立戈次,本地調(diào)試出最佳參數(shù)(決策樹和xgboost 的max_depth)然后進行預(yù)測,發(fā)現(xiàn)決策樹的效果比一遍的線性回歸模型好一些谒主,但是xgboost的預(yù)測效果更好朝扼。還有很多未知的知識等著學(xué)習(xí),加油霎肯。