評估樣本外模型擬合度
你現在知道,比起看樣本內的擬合度,查看樣本外的模型擬合度更有意義。在這個練習中,你要建立一個樣本外的準確率指標。
在此之前,你需要先做一些準備步驟。再次使用 defaultData。logitModelNew 已經載入到你的環境中。
請注意,完整的分析中,你一定要比較不同的模型候選者,且(特別是)要使用樣本外的資料來比較。
樣本內準確率(使用最佳閾值 0.3)為 0.7922901。
請確認你是否理解是否發生了過度擬合(overfitting)。
本練習屬於課程
R 的行銷分析機器學習
練習說明
先將資料集隨機切分為訓練集與測試集。訓練集應包含整體資料的 2/3。
接著快速訓練模型,並將其命名為
logitTrainNew。使用提供的公式。針對測試集進行預測,然後利用混淆矩陣計算樣本外準確率。請注意,
SDMTools已無法從 CRAN 下載。若在你的個人電腦上安裝,請改用remotes::install_version("SDMTools", "1.1-221.2")。將樣本外準確率與上面給出的樣本內數值進行比較。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Split data in train and test set
set.seed(534381)
defaultData$isTrain <- rbinom(nrow(defaultData), 1, 0.66)
train <- subset(defaultData, ___ == 1)
test <- subset(defaultData, ___ == 0)
logitTrainNew <- glm(formulaLogit, family = binomial, data = ___) # Modeling
test$predNew <- predict(logitTrainNew, type = "response", newdata = ___) # Predictions
# Out-of-sample confusion matrix and accuracy
confMatrixModelNew <- confusion.matrix(___, ___, threshold = 0.3)
sum(diag(confMatrixModelNew)) / sum(confMatrixModelNew) # Compare this value to the in-sample accuracy