訓練集與測試集

Python 的 Machine Learning 前處理

James Chapman

Curriculum Manager, DataCamp

為什麼要切分?

 

  1. 降低「過度擬合」
  2. 在保留資料上評估效能
Python 的 Machine Learning 前處理

切分你的資料集

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
   X_train y_train            
0      1.0       n
1      4.0       n
       ...
5      5.0       n
6      6.0       n

   X_test y_test
0     9.0      y
1     1.0      n
2     4.0      n
Python 的 Machine Learning 前處理

分層抽樣

 

  • $100$ 筆樣本的資料集:$80$ 個 class 1、$20$ 個 class 2
  • $75$ 筆樣本的訓練集:$60$ 個 class 1、$15$ 個 class 2
  • $25$ 筆樣本的測試集:$20$ 個 class 1、$5$ 個 class 2
Python 的 Machine Learning 前處理

分層抽樣

X_train,X_test,y_train,y_test = train_test_split(X, y, stratify=y, random_state=42)
y["labels"].value_counts()
class1    80
class2    20
Name: labels, dtype: int64
Python 的 Machine Learning 前處理

分層抽樣

y_train["labels"].value_counts()
class1    60
class2    15
Name: labels, dtype: int64
y_test["labels"].value_counts()
class1    20
class2    5
Name: labels, dtype: int64
Python 的 Machine Learning 前處理

一起來練習吧!

Python 的 Machine Learning 前處理

Preparing Video For Download...