文章目錄
- 一、前言
- 二、數據劃分方法
- 1. 留出法(Hold-out)
- 2. K折交叉驗證(K-Fold)
- 3. 留一法(Leave-One-Out)
- 三、總結
一、前言
簡要介紹數據劃分在機器學習中的作用。
二、數據劃分方法
1. 留出法(Hold-out)
- 使用 train_test_split 將數據分為訓練集和測試集。
- 代碼片段:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
print('Train obs: ', len(X_train))
print('Test obs: ', len(X_test))
2. K折交叉驗證(K-Fold)
- 用 KFold 將數據分為多折,循環訓練和測試。
- 代碼片段:
from sklearn.model_selection import KFold
X = np.random.randn(20, 1)
# 創建一個KFold對象,將數據分為5份,shuffle=True表示在分割前會先打亂數據
# 設置一個random state保證每次打亂的結果一致
kf = KFold(n_splits=5, shuffle=True, random_state=10)
#kf.get_n_splits(X)
for train_index, test_index in kf.split(X):print(train_index, test_index)
# 創建一個KFold對象,將數據分為5份,不打亂數據
kf = KFold(n_splits=5, shuffle=False)
#kf.get_n_splits(X)
for train_index, test_index in kf.split(X):print(train_index, test_index)
Note:假設總共有N個樣本,K折交叉驗證會將數據平均分成K份。每一折中,test_index的數量大約是 N/K(如果N不能被K整除,有的折會多一個或少一個),其余的樣本作為訓練集,train_index的數量就是N- test_index 的數量。在本例中,test_index的數量是20/5=4。
3. 留一法(Leave-One-Out)
- 每次留一個樣本做測試,其余做訓練。
- 代碼片段:
from sklearn.model_selection import LeaveOneOut
loo = LeaveOneOut()
loo.get_n_splits(X)
for train_index, test_index in loo.split(X):print(train_index, test_index)
三、總結
方法名稱 | 主要思想 | sklearn實現 | 訓練集數量 | 測試集數量 | 適用場景與特點 |
---|---|---|---|---|---|
留出法 | 隨機劃分一部分做訓練,其余做測試 | train_test_split | 設定比例(如60%) | 設定比例(如40%) | 簡單高效,適合大數據集 |
K折交叉驗證 | 將數據均分為K份,輪流做測試 | KFold | N-N/K | N/K | 評估更穩定,適合中小數據集 |
留一法 | 每次留一個樣本做測試,其余訓練 | LeaveOneOut | N-1 | 1 | 適合樣本量較小的情況 |
說明:
- 訓練集數量和測試集數量均為占總樣本數的比例或數量。
- K折法和留一法屬于交叉驗證,能更全面評估模型性能。
- 留出法實現簡單,適合數據量較大時快速實驗。
參考:https://scikit-learn.org/stable/api/sklearn.model_selection.html
博客內容如有錯誤歡迎指正~