K 折交叉驗證
你將先動手實作最常用的 K 折交叉驗證。
你要使用的資料來自 Kaggle 競賽「Two sigma connect: rental listing inquiries」。這個競賽的任務是將出租物件分成 3 個類別的多類別分類問題:低關注度、中關注度與高關注度。為了更快的效能,你將使用含 1,000 筆觀測值的子樣本。
你需要實作 K 折驗證策略,並查看每個得到的折(fold)的大小。train DataFrame 已經在你的工作環境中可用。
本練習屬於課程
用 Python 拿下 Kaggle 競賽
練習說明
- 建立一個具有 3 折的
KFold物件。 - 使用
kf物件迴圈走訪每個分割。 - 在每個分割中,使用
train_index與test_index選取訓練與測試的折。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import KFold
from sklearn.model_selection import KFold
# Create a KFold object
kf = ____(n_splits=____, shuffle=True, random_state=123)
# Loop through each split
fold = 0
for train_index, test_index in ____.____(train):
# Obtain training and testing folds
cv_train, cv_test = train.iloc[____], train.iloc[____]
print('Fold: {}'.format(fold))
print('CV train shape: {}'.format(cv_train.shape))
print('Medium interest listings in CV train: {}\n'.format(sum(cv_train.interest_level == 'medium')))
fold += 1