样本外验证与交叉验证

用 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)
用 R 进行市场营销分析的机器学习

样本外拟合:建模

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)
用 R 进行市场营销分析的机器学习

样本外准确率

# 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
用 R 进行市场营销分析的机器学习

交叉验证:设置

用 R 进行市场营销分析的机器学习

交叉验证:准确率

交叉验证准确率的计算

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
用 R 进行市场营销分析的机器学习
逻辑回归要点
你已学会… 预测可能流失的网店客户
用二元逻辑回归计算概率
阈值选择至关重要
模型洞见
你已学会… 订阅新闻简报的客户更可能回访
使用优惠券的客户回访可能性更低
免运费的客户更可能回访
等等…
用 R 进行市场营销分析的机器学习

最后一道练习!

用 R 进行市场营销分析的机器学习

Preparing Video For Download...