python 中任務 6.4 構建並評價迴歸模型 學習筆記4
阿新 • • 發佈:2020-12-24
文章目錄
任務 6.4 構建並評價迴歸模型
任務描述
迴歸演算法的實現過程與分類演算法相似,原理相差不大.分類和迴歸的主要區別在於,分類演算法的標籤是離散的,但是迴歸演算法的標籤是連續的.迴歸演算法在交通,物流,社交,網路和金融領域都能發揮巨大作用.
任務描述
(1) 使用sklearn 估計器構建線性迴歸(Linear Regression)模型
(2) 根據迴歸模型評價指標評價線性迴歸模型
6.4.1 使用sklearn估計器構建線性迴歸模型
從19世紀初高斯提出最小二乘估計算起,迴歸分析的歷史已有200多年。從經典的迴歸分析方法到近代的迴歸分析方法。按照研究方法劃分,迴歸分析研究的範圍大致下圖所示
程式碼6-24 使用sklearn 估計器構建線性迴歸模型
%%html
<img style="float: left;" src="./image/6-24.png" width=300 height= 400>
%%html
<img style="float: left;" src="./image/6-24-2.png" width=700 height=400>
%%html
<img style="float: left;" src="./image/6-24-3.png" width=700 height=400>
# 載入所需函式
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
# 載入boston資料
boston = load_boston()
X = boston['data']
y = boston['target']
names = boston['feature_names']
# 將資料劃分為訓練集測試集
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2,random_state=125)
# 建立線性迴歸模型
clf = LinearRegression().fit(X_train,y_train)
print('建立的LinearRegression模型為:','\n',clf)
# 預測訓練集結果
y_pred = clf.predict(X_test)
print('預測前20個結果為:','\n',y_pred[:20])
建立的LinearRegression模型為:
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
預測前20個結果為:
[21.16289134 19.67630366 22.02458756 24.61877465 14.44016461 23.32107187
16.64386997 14.97085403 33.58043891 17.49079058 25.50429987 36.60653092
25.95062329 28.49744469 19.35133847 20.17145783 25.97572083 18.26842082
16.52840639 17.08939063]
利用預測結果和真實結果劃出折線圖,能較為直觀地觀看出線性迴歸模型效果,如程式碼6-25 所示
程式碼6-25 迴歸結果視覺化
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.sans-serif'] = 'SimHei' #設定字型
fig = plt.figure(figsize=(10,6)) ##設定空白畫布,並制定大小
##用不同的顏色表示不同資料
plt.plot(range(y_test.shape[0]),y_test,color="blue", linewidth=1.5, linestyle="-")
plt.plot(range(y_test.shape[0]),y_pred,color="red", linewidth=1.5, linestyle="-.")
plt.legend(['真實值','預測值'])
plt.savefig('../tmp/聚類結果.png')
plt.show()
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-bJ2oWTkF-1608712508956)(output_11_0.png)]
6.4.2 評價迴歸模型
迴歸模型的效能評估不同於分類模型,雖然都是對照真實值進行評估,但由於迴歸模型的預測結果和真實值都是連續的,所以不能夠求取Precision、Recall和F1值等評價指標。迴歸模型擁有一套獨立的評價指標。
平均絕對誤差、均方誤差和中值絕對誤差的值越靠近0,模型效能越好。可解釋方差值和R方值則越靠近1,模型效能越好。
%%html
<img style="float: left;" src="./image/6-26-2.png" width=700 height=400>
程式碼6-26 迴歸模型的評價
from sklearn.metrics import explained_variance_score,\
mean_absolute_error,\
mean_squared_error,\
median_absolute_error,r2_score
print('Boston資料線性迴歸模型的平均絕對誤差為:',
mean_absolute_error(y_test,y_pred))
print('Boston資料線性迴歸模型的均方誤差為:',
mean_squared_error(y_test,y_pred))
print('Boston資料線性迴歸模型的中值絕對誤差為:',
median_absolute_error(y_test,y_pred))
print('Boston資料線性迴歸模型的可解釋方差值為:',
explained_variance_score(y_test,y_pred))
print('Boston資料線性迴歸模型的R方值為:',
r2_score(y_test,y_pred))
Boston資料線性迴歸模型的平均絕對誤差為: 3.3775517360082032
Boston資料線性迴歸模型的均方誤差為: 31.150517390315635
Boston資料線性迴歸模型的中值絕對誤差為: 1.7788996425420756
Boston資料線性迴歸模型的可解釋方差值為: 0.7105475650096659
Boston資料線性迴歸模型的R方值為: 0.7068961686076838
6.4.3 任務實現
房子的估值是一件相對煩瑣的事情,使用加利福尼亞住房資料集,可以通過房子的8個外在條件來評估房子的平均價值
1. 構建線性迴歸模型
程式碼6-27 使用sklearn估計器構建線性迴歸模型
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
house = pd.read_csv('../data/cal_housing.data',sep=',')
house_data = house.iloc[:,:-1]
house_target = house.iloc[:,-1]
house_names = ['longitude','latitude',
'housingMedianAge', 'totalRooms',
'totalBedrooms','population',
'households', 'medianIncome']
house_train,house_test,house_target_train,house_target_test = \
train_test_split(house_data,house_target,
test_size = 0.2,random_state = 42)
GBR_house = GradientBoostingRegressor().fit(house_train,house_target_train)
print('建立的梯度提升迴歸模型為:','\n',GBR_house)
建立的梯度提升迴歸模型為:
GradientBoostingRegressor(alpha=0.9, ccp_alpha=0.0, criterion='friedman_mse',
init=None, learning_rate=0.1, loss='ls', max_depth=3,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=100,
n_iter_no_change=None, presort='deprecated',
random_state=None, subsample=1.0, tol=0.0001,
validation_fraction=0.1, verbose=0, warm_start=False)
2. 評價構建的線性迴歸模型
程式碼6-28 評價構建線性迴歸模型
house_target_pred = GBR_house.predict(house_test)
from sklearn.metrics import explained_variance_score,\
mean_absolute_error,\
mean_squared_error,\
median_absolute_error,r2_score
print('california_housing資料梯度提升迴歸樹模型的平均絕對誤差為:',
mean_absolute_error(house_target_test,house_target_pred))
print('california_housing資料梯度提升迴歸樹模型的均方誤差為:',
mean_squared_error(house_target_test,house_target_pred))
print('california_housing資料梯度提升迴歸樹模型的中值絕對誤差為:',
median_absolute_error(house_target_test,house_target_pred))
print('california_housing資料梯度提升迴歸樹模型的可解釋方差值為:',
explained_variance_score(house_target_test,
house_target_pred))
print('california_housing資料梯度提升迴歸樹模型的R方值為:',
r2_score(house_target_test,house_target_pred))
california_housing資料梯度提升迴歸樹模型的平均絕對誤差為: 38055.93823652784
california_housing資料梯度提升迴歸樹模型的均方誤差為: 3103219873.747233
california_housing資料梯度提升迴歸樹模型的中值絕對誤差為: 26179.478445698245
california_housing資料梯度提升迴歸樹模型的可解釋方差值為: 0.7618957368088867
california_housing資料梯度提升迴歸樹模型的R方值為: 0.7618483669912332
小結
本章主要根據資料分析的應用分類,重點介紹了對應的資料分析建模方法及實現過程。
sklearn資料分析技術的基本任務主要體現在聚類、分類和迴歸三類。
每一類又有對應的多種評估方法,能夠評價所構建模型的效能優劣。
通過這一章的學習,讀者基本能夠掌握常用的模型構建與評估方法,可在以後的資料分析過程中採用適當的演算法並按所介紹的步驟實現綜合應用。
%%html
<img style="float: left;" src="./image/666.png" width=300 height=400>