R语言LASSO特征选择、决策树CART和CHAID算法电商网站购物行为预测分析

本文通过分析电子商务平台的用户购物行为,帮助客户构建了一个基于决策树模型的用户购物行为预测分析模型。

由Kaizong Ye,Colin Ge撰写

该模型可以帮助企业预测用户的购物意愿、购物频率及购买金额等重要指标,为企业制定更有针对性的营销策略提供参考。


数据来源和处理

本研究所使用的数据来自某电子商务平台的用户购物历史记录。

image.png

读取数据

head(data)
image.png

视频

Lasso回归、岭回归等正则化回归数学原理及R语言实例

探索见解

去bilibili观看

探索更多视频


视频

从决策树到随机森林:R语言信用卡违约分析信贷数据实例

探索见解

去bilibili观看

探索更多视频

模型构建

在本文中,我们选择了决策树和LASSO模型作为分析工具。决策树是一种常见的机器学习算法,它能够根据数据的特征变量将数据分成不同的类别,并找到最佳的划分方式。LASSO模型通过构造一个惩罚函数得到一个较为精炼的模型,使得它压缩一些回归系数,即强制系数绝对值之和小于某个固定值;同时设定一些回归系数为零。因此保留了子集收缩的优点,是一种处理具有复共线性数据的有偏估计。

决策树

df2$Is_Buy_30
image.png

变量类型设置

df2$Is_Buy_30 =as.factor(df2$Is_Buy_30 )  
df2$T_weekday =as.factor(df2$T_weekday)  
df2$T_hour=as.numeric(df2$T_hour)  
df2$city_tier=as.numeric(df2$city_tier)
image.png

设置权重

df2$weight[df2$Is_Buy_30==1]=7
df2$weight[df2$Is_Buy_30==0]=4

建立决策树:是否购买

result=list(0)  
CARTmodelfunc=function(model){  
  CARTmodel = rpart(model, data=df2 , method="class",weights = df2$weig



## 绘制决策树  
## 输出决策树cp值
  
  
  prune(CARTmodel, cp= CARTmodel$cptable[which.min(CARTmodel$cptable[,"xerror"]),"CP"])  #剪枝  
   
  CARTmodel2 <- prune(CARTmodel, cp=cp); #对树进行剪枝
  
  #对数据进行预测  
   
   
  set.seed(1)  
  #获得训练集  
  df2.train <- df2[train, ]  
  #测试集  
  df2.test <- df2[-train, ]  
  #预测数据  
  tree.pred= (predict(CARTmodel2,df2.test ,type = "class"))
  
  
  confusionmatrix=table(tree.pred,df2.test$Is_Buy_30),#得到训练集混淆矩阵
  
  
  MSE=mean((as.numeric(tree.pred) - as.numeric(df2.test$Is_Buy_30))^
  

使用lasso算法进行筛选变量

#获得训练集

train <- sample(1:nrow(df2), nrow(df2)*0.8)

t)]), alpha = 1)  
plot(cv.lasso)

Calm-securities-services-1536x1536-1280.jpg

R语言气象模型集成预报技术:神经网络、回归、SVM、决策树用环流因子预测降雨水数据

阅读文章


image.png


随时关注您喜欢的主题


coef(cv.lasso,s="lambda.1se")
image.png

根据lasso筛选出最优的变量

image.png

chaid 树

ctreemodelfucntion=function(modelformula){  
  index=sample(1:nrow(df2),nrow(df2)*0.6)  
  df2.train=df2[index,]  
  df2.test=df2[index,]
  
  
  confusionmatrix=table(tree.pred2,df2.test$Is_Buy_30)#得到训练集混淆矩阵
  
  
  #预测为1类的正确率  
    presicion=tab[2,2]/sum(tab[,2]),  
    # [1] 0.3993589  
    #预测为1类的召回率  
    recall=tab[2,2]/sum(tab[2,]),  
    # [1] 0.6826484  
     
    #mse  
    MSE=mean((as.numeric(tree.pred2) - as.numeric(df2.test$Is_Buy_30))^2),

chaid tree LASSO 算法

可视化树状图:

image.png
image.png

模型结果:

image.png

image.png

将x表写进数据库里

sqlSave(channel,result2_loss22,rownames = "result2_loss22",addPK = TRUE)

CART tree LASSO 算法

resultlasso2=CARTmodelfunc(modelformulalasso)
image.png
image.png
image.png
image.png
202003281439369701.png
resultlasso2

image.png
image.png
# 将x表写进数据库里  
sqlSave(channel,result_rfm,rownames = "result_rfm",addPK = TRUE)


可下载资源

关于作者

Kaizong Ye拓端研究室(TRL)的研究员。

本文借鉴了作者最近为《R语言数据分析挖掘必知必会 》课堂做的准备。

​非常感谢您阅读本文,如需帮助请联系我们!

 
QQ在线咨询
售前咨询热线
15121130882
售后咨询热线
0571-63341498

关注有关新文章的微信公众号


永远不要错过任何见解。当新文章发表时,我们会通过微信公众号向您推送。

技术干货

最新洞察

This will close in 0 seconds