資料切分
為了正確評估模型,你可以將資料切分為訓練集與測試集。訓練集用來建立模型,測試集用來評估模型。這個切分會隨機進行,但當目標變數的發生率很低時,可能需要進行分層抽樣(stratify),也就是確保訓練集與測試集中目標的比例相同。
在這個練習中,你會用分層抽樣來切分資料,並驗證訓練集與測試集的目標發生率是否相同。train_test_split 方法已匯入,X 與 y 兩個 DataFrame 也已在你的工作環境中可用。
本練習屬於課程
Python 預測分析入門
練習說明
- 使用
train_test_split方法對這些 DataFrame 進行分層抽樣切分。請確保訓練集與測試集大小相同,且目標發生率一致。 - 計算訓練集的目標發生率。也就是訓練集中目標筆數除以訓練集的觀測筆數。
- 計算測試集的目標發生率。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Load the partitioning module
from sklearn.model_selection import train_test_split
# Create DataFrames with variables and target
X = basetable.drop("target", 1)
y = basetable["target"]
# Carry out 50-50 partititioning with stratification
X_train, X_test, y_train, y_test = ____(X, y, test_size = ____, stratify = ____)
# Create the final train and test basetables
train = pd.concat([X_train, y_train], axis=1)
test = pd.concat([X_test, y_test], axis=1)
# Check whether train and test have same percentage targets
print(round(sum(train[____])/len(____), 2))
print(round(sum(test[____])/len(____), 2))