本系列主要采用Python-sklearn實作,環境搭建可參考 資料挖掘入門:Python開發環境搭建(eclipse-pydev模式).
相關答案和源代碼托管在我的Github上:PY131/Machine-Learning_ZhouZhihua.
3.4 比較k折交叉驗證法與留一法
![]()
周志華《機器學習》課後習題解答系列(四):Ch3.4 - 交叉驗證法練習
本題采用UCI中的 Iris Data Set 和 Blood Transfusion Service Center Data Set,基于sklearn完成練習(檢視完整代碼)。
關于資料集的介紹:
IRIS資料集簡介 - 百度百科;通過花朵的性狀資料(花萼大小、花瓣大小…)來推測花卉的類别。變量屬性X=4種,類别标簽y公有3種,這裡我們選取其中兩類資料來拟合對率回歸(邏輯斯蒂回歸)。
Blood Transfusion Service Center Data Set - UCI;通過捐血行為(上次捐血時間、總捐血cc量…)的曆史資料,來推測某人是否會在某一時段捐血。變量屬性X=4種,類别y={0,1}。該資料集相對iris要大一些。
具體過程如下:
1. 資料導入、可視化、預分析:
iris資料集十分常用,sklearn的資料包已包含該資料集,我們可以直接載入。對于transfusion資料集,我們從UCI官網上下載下傳導入即可。
采用seaborn庫可以實作基于matplotlib的非常漂亮的可視化呈現效果,下圖是采用seaborn.pairplot()繪制的iris資料集各變量關系組合圖,從圖中可以看出,類别區分十分明顯,分類器應該比較容易實作:
![]()
周志華《機器學習》課後習題解答系列(四):Ch3.4 - 交叉驗證法練習
相關樣例代碼:
import numpy as np
import seaborn as sns
sns.set(style="white", color_codes=True)
iris = sns.load_dataset("iris")
iris.plot(kind="scatter", x="sepal_length", y="sepal_width")
sns.pairplot(iris,hue='species')
sns.plt.show()
2. 基于sklearn進行拟合與交叉驗證:
這裡我們選擇iris中的兩類資料對應的樣本進行分析。k-折交叉驗證可直接根據sklearn.model_selection.cross_val_predict()得到精度、F1值等度量(該函數要求1<k<n-1)。留一法稍微複雜一點,這裡采用loop實作。
面向iris資料集的樣例代碼:
'''
2-nd logistic regression using sklearn
'''
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.model_selection import cross_val_predict
# log-regression lib model
log_model = LogisticRegression()
m = np.shape(X)[]
# 10-folds CV
y_pred = cross_val_predict(log_model, X, y, cv=)
print(metrics.accuracy_score(y, y_pred))
# LOOCV
from sklearn.model_selection import LeaveOneOut
loo = LeaveOneOut()
accuracy = ;
for train, test in loo.split(X):
log_model.fit(X[train], y[train]) # fitting
y_p = log_model.predict(X[test])
if y_p == y[test] : accuracy +=
print(accuracy / np.shape(X)[])
得出了精度(預測準确度)結果如下:
0.97
0.96
可以看到,兩種方法的模型精度都十分高,這也得益于iris資料集類間散度較大。
同樣的方法對blood-transfusion資料集得出的精度結果:
0.76
0.77
也可以看到,兩種交叉驗證的結果相近,但是由于此資料集的類分性不如iris明顯,所得結果也要差一些。同時由程式運作可以看出,LOOCV的運作時間相對較長,這一點随着資料量的增大而愈發明顯。
是以,一般情況下選擇K-折交叉驗證即可滿足精度要求,同時運算量相對小。
本文的一些重要索引如下:
- sklearn中自帶iris資料集的使用
- UCI機器學習資料集官方首頁
- 基于Python的資料可視化 matplotlib seaborn pandas
- seaborn可視化庫的官方首頁