R 的行銷分析機器學習
Verena Pflieger
Data Scientist at INWT Statistics
1) 將資料集分成訓練與測試資料
# Generating random index for training and test set
# set.seed ensures reproducibility of random components
set.seed(534381)
churnData$isTrain <- rbinom(nrow(churnData), 1, 0.66)
train <- subset(churnData, churnData$isTrain == 1)
test <- subset(churnData, churnData$isTrain == 0)
2) 以訓練資料建立模型
# Modeling logitTrainNew
logitTrainNew <- glm( returnCustomer ~ title + newsletter +
websiteDesign + paymentMethod + couponDiscount +
purchaseValue + throughAffiliate +
shippingFees + dvd + blueray + vinyl +
videogameDownload + prodOthers + prodRemitted,
family = binomial, data = train)
# Out-of-sample prediction for logitTrainNew
test$predNew <- predict(logitTrainNew, type = "response",
newdata = test)
# Calculating the confusion matrix
confMatrixNew <- confusion.matrix(test$returnCustomer, test$predNew,
threshold = 0.3)
confMatrixNew
# Calculating the accuracy
accuracyNew <- sum(diag(confMatrixNew)) / sum(confMatrixNew)
accuracyNew
obs
pred 0 1
0 11939 2449
1 716 350
0.7951987

計算交叉驗證的準確率
library(boot)
# Accuracy function with threshold = 0.3
Acc03 <- function(r, pi = 0) {
cm <- confusion.matrix(r, pi, threshold = 0.3)
acc <- sum(diag(cm)) / sum(cm)
return(acc)}
# Accuracy
set.seed(534381)
cv.glm(churnData, logitModelNew, cost = Acc03, K = 6)$delta
0.7943894
| 學習重點:Logistic 迴歸 | |
|---|---|
| 你學到… | 如何預測可能流失的網路商店顧客 |
| 使用二元 Logistic 迴歸計算機率 | |
| 閾值(threshold)的選擇至關重要 |
| 模型啟示 | |
|---|---|
| 你學到… | 訂閱電子報的顧客較可能回購 |
| 使用優惠券的顧客較不可能回購 | |
| 免運費的顧客較可能回購 | |
| 等等… |
R 的行銷分析機器學習