用户画像之线性回归逻辑回归综合实战

简介: 用户画像之线性回归逻辑回归综合实战

线性回归篇

导语:本次使用的数据是网上提供的脱敏消费数据,因变量全数值类型,数据本身符合线性回归标准,初始数据选择请确保数据符合马尔可夫五大假设,再进行线性回归拟合,
1 线性与参数
2 不存在多重共线性
3 残差的正态性
4 残差的均值为0
5 残差的同方差性

1 初期准备

raw<-read.csv("data_revenue_model.csv",stringsAsFactors = F)#read in your csv data
str(raw)      #check the varibale type
View(raw)     #take a quick look at the data
summary(raw)  #take a quick look at the summary of variable

Y值预览明显右偏

#dv_revenue  
hist(raw$dv_revenue) #Y histogram
quantile(raw$dv_revenue,(1:20)/20) #Y quantile

在这里插入图片描述
阈值处理

hist(raw[raw$dv_revenue<=2000,'dv_revenue'])

在这里插入图片描述

2 分割数据集

# modeling segments
View(table(raw$segment))
View(prop.table(table(raw$segment)))

在这里插入图片描述
将数据集分为训练集,验证集,测试集

#train validation 70/30 split
raw_2=raw[raw$segment!="outval",]
View(prop.table(table(raw_2$segment)))

#Separate Build Sample
train<-raw[raw$segment=='build',] #select build sample
View(table(train$segment))        #check segment
#Separate invalidation Sample
test<-raw[raw$segment=='inval',]  #select invalidation(OOS) sample
View(table(test$segment))         #check segment

#Separate out of validation Sample
validation<-raw[raw$segment=='outval',] #select out of validation(OOT) sample
View(table(validation$segment))         #check segment

3 lift制作

预览数据,查看分层情况,对数据进行计算,计算总的消费金额,记录总行数,平均用户消费金额

#overall performance
overall_cnt=nrow(train)                      #calculate the total count
overall_revenue=sum(train$dv_revenue)        #calculate the total revenue
Average_revenue=overall_revenue/overall_cnt  #calculate the average revenue
overall_perf<-c(overall_count=overall_cnt,overall_revenue=overall_revenue,Average_revenue=Average_revenue)  #combine
View(t(overall_perf))  #take a look at the summary

在这里插入图片描述
对变量进行lift系数计算,lift=对该变量分组后组内的平均消费额度/总数据平均消费额度

prof_exe<-ddply(train,.(ex_auto_used0005),summarise,cnt=length(rid),rev=sum(dv_revenue))
View(prof_exe)

prof1_exe<-within(prof_exe,
                  {AVG_REVENUE<-rev/cnt
                  index<-AVG_REVENUE/Average_revenue*100
                  percent<-cnt/overall_cnt
                  })
View(prof1_exe)

也可以用sql写

use sqldf if you are familiar with sql

install.packages('sqldf')

library(sqldf)

sqldf("select hh_gender_m_flag,count() as cnt,sum(dv_revenue)as rev,sum(dv_revenue)/count() as AVG_REVENUE from train group by 1 ")

4 缺失值处理


缺失值少于20%可直接删除,或者平均数,中位数填充,甚至可以knn填充

train$m3_pos_revenue_base_sp_6mo <- ifelse(is.na(train$pos_revenue_base_sp_6mo) == T, 294.16,     #when pos_revenue_base_sp_6mo is missing ,then assign 294.16
                                           ifelse(train$pos_revenue_base_sp_6mo <= 0, 0,                   #when pos_revenue_base_sp_6mo<=0 then assign 0
                                                  ifelse(train$pos_revenue_base_sp_6mo >=4397.31, 4397.31, #when pos_revenue_base_sp_6mo>=4397.31 then assign 4397.31
                                                         train$pos_revenue_base_sp_6mo)))                  #when 0<pos_revenue_base_sp_6mo<4397.31 and not missing then assign the raw value

summary(train$m3_pos_revenue_base_sp_6mo)  #do a summary
summary(train$m2_POS_REVENUE_BASE_SP_6MO)  #do a summary
summary(train$pos_revenue_base_sp_6mo)

train$mn_ex_auto_used0005_x1 <- ifelse(is.na(train$ex_auto_used0005), 0,   
                                       ifelse(train$ex_auto_used0005 == 1, 1, 0))
View(train)

5 变量确定与模型拟合

确定变量的第一步是根据业务确定,确定有可能的指标,再进行相关分析,模型拟合,AIC筛选

library(picante)  #call picante

var_list1<-c(
  'm2_POS_REVENUE_BASE',
  'm2_POS_LAST_TOTAL_REVENUE',
  'm2_POS_REVENUE_TOTAL',
  'm2_POS_REVENUE_TOTAL_6MO',
  'm2_POS_MARGIN_TOTAL',
  'm2_POS_MARGIN_TOTAL_12MO',
  'm2_POS_SP_QTY_24MO',
  'm2_EM_COUNT_VALID',
  'm2_IID_COUNT',
  'm2_EM_NUM_OPEN_30',
  'm2_SH_INQUIRED_LAST12MO',
  'm2_WEB_CNT_IID_ACCESSED',
  'm2_SH_INQUIRED_LAST3MO',
  'm2_POS_MNTHS_LAST_ORDER',
  'm2_POS_NUM_ORDERS',
  'm2_POS_TOT_REVPERSYS',
  'm2_POS_NUM_ORDERS_24MO',
  'm2_HH_INCOME',
  'm2_EM_MONTHS_LAST_OPEN',
  'm2_HH_AGE',
  'm2_WEB_MNTHS_SINCE_LAST_SES',
  'm2_POS_REVENUE_BASE_SP_6MO',
  'm2_SH_MNTHS_LAST_INQUIRED') 

进行相关分析,做出相关性矩阵

####all variables correlation
corr_var<-train[, var_list1]  #select all the variables you want to do correlation analysis
str(corr_var)                #check the variable type
correlation<-data.frame(cor.table(corr_var,cor.method = 'pearson')) #do the correlation
View(correlation)

在这里插入图片描述

依据相关系数矩阵筛选相关系数高的变量,对于x之间相关性高的可以做标识变量或哑变量

初次模型拟合

mods<-train[,c('dv_revenue',var_list1)] #select Y and variables you want to try

model_lm<-lm(dv_revenue~.,data=mods)   #regression model
model_lm

summary(model_lm)

再使用逐步回归法

#Stepwise

library(MASS)
model_sel<-stepAIC(model_lm,direction ="both")  #using both backward and forward stepwise selection
summary<-summary(model_sel) #summary
summary

model_summary<-data.frame(var=rownames(summary$coefficients),summary$coefficients) #do the model summary
model_summary

在这里插入图片描述
模型预测,并对预测的结果进行分群排序,分别依照10分为数划分,1代表前10%

#lift Chart:train
pred<-predict(model_lm,train,type='response')  #Predict Y

decile<-cut(pred,unique(quantile(pred,(0:10)/10)),labels=10:1, include.lowest = T) #Separate into 10 groups

# decile
sum<-data.frame(actual=train$dv_revenue,pred=pred,decile=decile)  #put actual Y,predicted Y,Decile together
View(sum)

decile_sum<-ddply(sum,.(decile),summarise,cnt=length(actual),rev=sum(actual)) #group by decile
decile_sum2<-within(decile_sum,
                    {rev_avg<-rev/cnt
                    index<-100*rev_avg/(sum(rev)/sum(cnt))
                    })  #add Avg_Rev,index
View(decile_sum2)
decile_sum3<-decile_sum2[order(decile_sum2[,1],decreasing=T),]  #order decile
View(decile_sum3)

在这里插入图片描述
从中可以发现排序较前分组里面的平均花费比总体平均高,并成降序排序

#test data
pred_test<-predict(model_lm,test,type='response')
decile_test<-cut(pred_test,unique(quantile(pred_test,(0:10)/10)),labels = 10:1,include.lowest = T)
sum_test<-data.frame(actual=test$dv_revenue,pred=pred_test,decile=decile_test)
View(sum_test)

decile_sum_test<-ddply(sum_test,.(decile_test),summarise,cnt=length(actual),rev=sum(actual))
decile_sum_test2<-within(decile_sum_test,
                         {rev_avg<-rev/cnt
                         index<-100*rev_avg/(sum(rev)/sum(cnt))
                         })
View(decile_sum_test2)
decile_sum_test3<-decile_sum_test2[order(decile_sum_test2[,1],decreasing = T),] 
View(decile_sum_test3)

测试集数据同理

6 lift图制作

#plot
plot(1:10, decile_sum3$index, type="b",pch=16,lty=1,xlab="decile",ylab="index")
lines(1:10,decile_sum_test3$index,type='b',lty=2,pch=17)
legend('topright',inset=0.05,c('train','test'),lty=c(1,2),pch=c(16,17))

在这里插入图片描述

7 输出模型公式

#output model equoation
ss <- summary(model_lm)
names(ss)

ss[[4]]

gsub("\\+-","-",gsub('\\*\\(Intercept\\)','',paste(ss[[4]][,1],rownames(ss[[4]]),collapse = "+",sep = "*")

在这里插入图片描述
将客户分群与客户信息相结合

目录
相关文章
|
存储 API
uniapp登录拦截器
uniapp登录拦截器
uniapp登录拦截器
|
9月前
|
人工智能 安全 API
深入理解OpenClaw技术架构与实现原理(上)
本文深度剖析OpenClaw——当前最热门的个人AI助手系统,涵盖其本地优先、多端联动的总体架构,以及Gateway网关、Agentic Loop、定时任务、工具系统、Channels连接生态、上下文管理、SubAgent子智能体等16大核心模块。全文以AI-Coding实现为特色,强调安全沙箱、协议化设计与自进化能力,展现新一代软件构建范式的开山之作。
深入理解OpenClaw技术架构与实现原理(上)
|
2月前
|
存储 弹性计算 人工智能
阿里云超低价云服务器怎么选?38元到1252元四款档位解析,99元与199元续费同价更划算
本文从配置、带宽、存储、算力与成本等维度,拆解阿里云四款入门云服务器。38元轻量应用服务器2核2G、200M峰值带宽,适合短期验证;99元经济型e实例2核2G、3M固定带宽,为共享型标准ECS且支持续费同价;199元u1实例2核4G、5M固定带宽、独享算力,适合中小企业;1252.63元u2i实例4核8G,算力更强但1M带宽或成瓶颈。选型需综合续费政策、计算模式、带宽存储余量与整体TCO,而非只看首年价格。
|
12月前
|
SQL 人工智能 Apache
Apache Doris 4.0.2 版本正式发布
亲爱的社区小伙伴们,Apache Doris 4.0.2 版本已正式发布。此版本新增了在 AI & Search、函数、物化视图、Lakehouse 等方面的功能,并同步进行了多项优化改进及问题修复,欢迎下载体验!
716 9
|
11月前
|
数据采集 编解码 自动驾驶
世界模型 LingBot-World,正式开源!
蚂蚁灵波团队开源世界模型LingBot-World,专为交互式仿真设计。其核心LingBot-World-Base具备高保真、强动态、长时序一致性(支持近10分钟稳定生成)和实时交互能力(≈16FPS,延迟<1秒),依托可扩展数据引擎,从游戏环境学习物理与因果规律,打造具身智能、自动驾驶等领域的“数字演练场”。
2834 1
|
7月前
|
人工智能 自然语言处理 安全
OpenClaw v2.6.6 部署教程 小龙虾本地 AI 智能体 Windows 完整安装
OpenClaw(小龙虾AI)是开源本地AI智能体,支持Windows一键部署:零代码、全自动、内置全部依赖,开箱即用;提供28万Tokens额度,兼容多模型,可离线执行文件整理、浏览器操作等任务,隐私安全、无广告干扰。(239字)
|
12月前
|
存储 人工智能 机器人
【2026必看 AI智能体】零基础Coze平台使用教程
本文介绍了Coze智能体的实战入门与进阶应用,涵盖智能体创建、配置大语言模型(LLM)、使用插件扩展功能、构建知识库(RAG)实现高考志愿填报助手、利用记忆功能开发记账本,以及通过API调用和工作流实现中草药识别与菜谱生成等复杂任务,全面展示其在多场景下的智能化能力。
9405 11
|
人工智能 数据可视化 API
智能体框架大比拼:全面解析Dify、Coze、n8n、AutoGen、LangChain、CrewAI
智能体(AIAgent)正推动AI应用开发革新,从单模型调用转向具备自主决策与协作能力的智能系统。本文系统解析六大框架——Dify(企业级开源)、Coze(零代码)、n8n(自动化)、AutoGen(多Agent协作)、LangChain(模块化开发)和CrewAI(角色分工),对比其核心能力、适用场景及优劣势,助开发者高效选型。低代码平台适合快速原型,编程框架满足深度定制,多Agent系统适配复杂任务,选择需权衡开发门槛、协作能力与生态支持。
|
机器学习/深度学习 人工智能 自然语言处理
深度学习模型、算法与应用的全方位解析
深度学习,作为人工智能(AI)的一个重要分支,已经在多个领域产生了革命性的影响。从图像识别到自然语言处理,从语音识别到自动驾驶,深度学习无处不在。本篇博客将深入探讨深度学习的模型、算法及其在各个领域的应用。
2310 3
|
机器人 容器 Docker
100%由Qwen3-Coder独立编程!工业级RAGFlow聊天机器人实战,故障诊断提速300%
RAGFlow Chatbot 是一个集成了 RAGFlow 技术的智能问答系统,专注于 LCD 彩膜制造领域的专业知识。该系统能够回答关于工艺诊断、缺陷分析、材料验证和设备优化等方面的问题,为工程师和技术人员提供快速准确的知识支持。 功能特性 🤖 基于 RAGFlow 的智能问答系统 💬 实时流式响应,支持思考过程展示 📚 对话历史记录与管理 🔍 搜索历史对话 📤 导出对话记录 🧠 深度思考模式 🌐 响应式设计,支持移动端 🌙 深色主题支持
1174 0