【用户价值分析 RFM模型】用户价值分析

RFM模型是衡量客户价值和客户创利能力的重要工具和手段。RFM分析模型主要由三个指标组成,下面对这三个指标的定义和作用做下简单解释:

1、最近一次消费(Recency)
最近一次消费意指用户上一次购买的时间,理论上,上一次消费时间越近的顾客应该是比较好的顾客,对提供即时的商品或是服务也最有可能会有反应。因为最近一次消费指标定义的是一个时间段,并且与当前时间相关,因此是一直在变动的。最近一次消费对营销来说是一个重要指标,涉及吸引客户,保持客户,并赢得客户的忠诚度。
2、消费频率(Frequency)
消费频率是顾客在一定时间段内的消费次数。最常购买的消费者,忠诚度也就最高,增加顾客购买的次数意味着从竞争对手处偷取市场占有率,由别人的手中赚取营业额。
根据这个指标,我们又把客户分成五等分,这个五等分分析相当于是一个“忠诚度的阶梯”(loyalty ladder),其诀窍在于让消费者一直顺着阶梯往上爬,把销售想像成是要将两次购买的顾客往上推成三次购买的顾客,把一次购买者变成两次的。
3、消费金额(Monetary)
消费金额是对购彩产能的最直接的衡量指标,也可以验证“帕雷托法则”(Pareto’s Law)——公司80%的收入来自20%的顾客。

FRM就是根据客户活跃度和交易金额贡献,进行客户价值细分的一种方法。

RFM算法步骤:
1.计算RFM各项分值
R_S,距离当前日期越近,得分越高,最高7分,最低1分,按实际数据分布情况切割依次从高到低取分数。
F_S,交易频率越高,得分越高,最高7分,最低1分,按实际数据分布情况切割依次从高到低取分数。
M_S,交易金额越高,得分越高,最高7分,最低1分,按实际数据分布情况切割依次从高到低取分数。

2.归总RFM分值
RFM赋予权重(目前权重采用R:F:M = 1:1:1),权重乘以分数归总RFM分值。这个总RFM分值作为衡量用户价值的关键指标。公式如下:

3.根据RFM分值对客户分类

# encoding: utf-8


"""
function:RFM用户价值分析分成5类
author:dongli
update_date:2018-06-07
"""

# 导入包
import pandas as pd
######################################################写入excel设置问题#########################################
import xlsxwriter
# 定义RFM函数
def RFM(aggData):

    """

    :param aggData: 输入数据集,数据集字段要包含recency,frequency,monetary等三个字段
    :return:返回数据集结果
    """
    # 计算R_S
    bins = aggData.recency.quantile(q=[0, 0.28, 0.38, 0.46, 0.53, 0.57, 0.77, 1], interpolation='nearest')
    bins[0] = 0
    labels = [7, 6, 5, 4, 3, 2, 1]
    R_S = pd.cut(aggData.recency, bins, labels=labels)

    # 计算F_S
    bins = aggData.frequency.quantile(q=[0, 0.29, 0.45, 0.60, 0.71, 0.76, 0.90, 1], interpolation='nearest')
    bins[0] = 0
    labels = [1, 2, 3, 4, 5, 6, 7]
    F_S = pd.cut(aggData.frequency, bins, labels=labels)

    # 计算M_S
    bins = aggData.monetary.quantile(q=[0, 0.20, 0.26, 0.45, 0.55, 0.76, 0.85, 1], interpolation='nearest')
    bins[0] = 0
    labels = [1, 2, 3, 4, 5, 6, 7]
    M_S = pd.cut(aggData.monetary, bins, labels=labels)

    # 赋值
    aggData['R_S'] = R_S
    aggData['F_S'] = F_S
    aggData['M_S'] = M_S

    # 计算FRM值
    aggData['RFM'] = R_S.astype(int)*1 + F_S.astype(int)*1 + M_S.astype(int)*1


    # 根据RFM分值对客户分类


    #分五类
    bins = aggData.RFM.quantile(q=[0, 0.2, 0.4, 0.6, 0.8, 1],interpolation='nearest')
    bins[0] = 0
    labels = [1, 2, 3, 4, 5]
    aggData['level'] = pd.cut(aggData.RFM,bins, labels=labels)

    # 分八类
    # bins = aggData.RFM.quantile(q=[0, 0.125, 0.25, 0.375, 0.5,0.625, 0.75, 0.875, 1],interpolation='nearest')
    # bins[0] = 0
    # labels = [1, 2, 3, 4, 5, 6, 7, 8]
    # aggData['level'] = pd.cut(aggData.RFM,bins, labels=labels )




    return aggData


# 主函数
if __name__ == '__main__':

    # 读取数据
    aggData = pd.read_csv('C:\\Users\\xiaohu\\Desktop\\月刊数据\\4月份用户价值数据.csv')


    # 调用模型函数
    result=RFM(aggData)

    # 打印结果
    print(result)


    # 计算每个类别的数据量

    c1=list(result["level"].value_counts())


    # 计算每个类别所占的百分比

    c2 = list(result["level"].value_counts()/len(result)*100)

    c3=(list(map(lambda x:str(round(x,3))+"%",c2)))

    c=pd.DataFrame({"level":range(1,len(c1)+1),"数量":c1,"百分比":c3})


    print(c)

    # 写出csv

    result.to_csv('C:\\Users\\xiaohu\\Desktop\\月刊数据\\result5_50_四月份.csv',index=False)


    # ## 先写出excel
    # workbook = xlsxwriter.Workbook("C:\\Users\\xiaohu\\Desktop\\月刊数据\\result_RFM.xlsx",options={'strings_to_urls': False})
    #
    # format = workbook.add_format()
    # format = workbook.add_format()
    # format.set_border(1)
    # format_title = workbook.add_format()
    # format_title.set_border(1)
    # format_title.set_bg_color('#cccccc')
    # format_title.set_align('center')
    # format_title.set_bold()
    # format_ave = workbook.add_format()
    # format_ave.set_border(1)
    # format_ave.set_num_format('0')
    #
    # data_format = workbook.add_format()
    # data_format.set_num_format('yyyy-mm-dd HH:MM:SS')
    # data_format.set_border(1)
    #
    # worksheet2 = workbook.add_worksheet('用户价值')
    # title2 = [u'user_id', u'recency', u'frequency', u'monetary',u'R_S',u'F_S',u'M_S',u'RFM', u'level']
    #
    # worksheet2.write_row('A1', title2, format_title)
    # worksheet2.write_column('A2:', result.iloc[:, 0], format_ave)
    # worksheet2.write_column('B2:', result.iloc[:, 1], format)
    # worksheet2.write_column('C2', result.iloc[:, 2], format)
    # worksheet2.write_column('D2', result.iloc[:, 3], format)
    # worksheet2.write_column('E2', result.iloc[:, 4], format)
    # worksheet2.write_column('F2', result.iloc[:, 5], format)
    # worksheet2.write_column('G2', result.iloc[:, 6], format)
    # worksheet2.write_column('H2', result.iloc[:, 7], format)
    # worksheet2.write_column('I2', result.iloc[:, 8], format)
    #
    # workbook.close()
    #

RFM+kmeans算法

# encoding: utf-8
"""
function:RFM用户价值分析+kmeans算法自动划分
author:dongli
update_date:2018-05-09
"""

# 导入包
from __future__ import  division
import pandas as pd
from sklearn.cluster import KMeans


######################################python画图显示中文参数设置####################################
##########设置中文显示#################
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
font_size =11 # 字体大小
fig_size = (8, 6) # 图表大小
# 更新字体大小
mpl.rcParams['font.size'] = font_size
# 更新图表大小
mpl.rcParams['figure.figsize'] = fig_size
###################################################################################################

# 定义RFM函数
def RFM(aggData):
    """
    :param aggData: 输入数据集,数据集字段要包含recency,frequency,monetary等三个字段
    :return:返回数据集结果
    """
    # 计算R_S
    bins = aggData.recency.quantile(q=[0, 0.31, 0.38, 0.46, 0.53, 0.57, 0.77, 1], interpolation='nearest')
    bins[0] = 0
    labels = [7, 6, 5, 4, 3, 2, 1]
    R_S = pd.cut(aggData.recency, bins, labels=labels)

    # 计算F_S
    bins = aggData.frequency.quantile(q=[0, 0.29, 0.45, 0.60, 0.71, 0.76, 0.90, 1], interpolation='nearest')
    bins[0] = 0
    labels = [1, 2, 3, 4, 5, 6, 7]
    F_S = pd.cut(aggData.frequency, bins, labels=labels)

    # 计算M_S
    bins = aggData.monetary.quantile(q=[0, 0.20, 0.26, 0.45, 0.55, 0.76, 0.85, 1], interpolation='nearest')
    bins[0] = 0
    labels = [1, 2, 3, 4, 5, 6, 7]
    M_S = pd.cut(aggData.monetary, bins, labels=labels)

    # 赋值
    aggData['R_S'] = R_S
    aggData['F_S'] = F_S
    aggData['M_S'] = M_S

    # 计算FRM值
    aggData['RFM'] = R_S.astype(int) + F_S.astype(int) + M_S.astype(int)

    #分五类
    bins = aggData.RFM.quantile(q=[0, 0.2, 0.4, 0.6, 0.8, 1],interpolation='nearest')
    bins[0] = 0
    labels = [1, 2, 3, 4, 5]
    aggData['level'] = pd.cut(aggData.RFM,bins, labels=labels)

    return aggData




# 读取数据
aggData = pd.read_csv('C:\\Users\\xiaohu\\Desktop\\用户价值分析\\用户价值分析RFM模型\\source\\RFM_Data_50.csv')
# print(aggData)

aggData2=RFM(aggData)
print(aggData2)





# 选择recency,frequency,monetary这三列
data=aggData2.loc[:,['recency','frequency','monetary']]

print(data)

# 定义数据标准化函数 Min-max 标准化
def Normalization(df):
    return df.apply(lambda x: (x - np.min(x)) / (np.max(x) - np.min(x)))

# 调用函数进行数据标准化(0-1)之间
zsredfile=Normalization(data)



# 对列进行重命名
names = ['ZR','ZF','ZM']
zsredfile.columns = names

print(zsredfile)


##########################################选择最佳的K值########################################################

"""
一般我们可以 通过迭代的方式选出合适的聚类个数 ,即让k值从1到K依次执行一遍,
再查看每一次k值对应的簇内离差平方和之和的变化,
如果变化幅度突然由大转小时,那个k值就是我们选择的合理个数
"""
K = range(1,15)
GSSE = []
for k in K:

    print(K)

    SSE = []

    kmeans = KMeans(n_clusters=k, random_state=10)

    kmeans.fit(zsredfile)

    labels = kmeans.labels_

    centers = kmeans.cluster_centers_
    for label in set(labels):
        SSE.append(np.sum(np.sum((zsredfile[['ZR', 'ZF','ZM']].loc[labels == label,] - centers[label, :]) ** 2)))

    GSSE.append(np.sum(SSE))

# 绘制K的个数与GSSE的关系
plt.plot(K, GSSE, 'b*-')

plt.xlabel('聚类个数')

plt.ylabel('簇内离差平方和')

plt.title('选择最优的聚类个数')

plt.show()


###########################################################################################################################

#########选择最优的聚类个数为5
seed(123)
#调用sklearn的库函数
num_clusters = 5
kmeans = KMeans(n_clusters=num_clusters, random_state=1)
kmeans.fit(zsredfile)


# 聚类结果标签
data['cluster'] = kmeans.labels_
# 聚类中心
centers = kmeans.cluster_centers_

cluster_center = pd.DataFrame(kmeans.cluster_centers_)
# 绘制散点图
plt.scatter(x = zsredfile.iloc[:,0], y = zsredfile.iloc[:,1], c = data['cluster'], s=50, cmap='rainbow')
plt.scatter(centers[:,0], centers[:,1], c='k', marker = '*', s = 180)
plt.xlabel('ZR')
plt.ylabel('ZF')
plt.title('聚类效果图')
# 图形显示
plt.show()



# # 查看RFM模型8个类别中的用户数量以及占比多少

result=data

aggData2['cluster']=result["cluster"]
# 计算每个类别的数据量

c1 = list(result["cluster"].value_counts())

# 计算每个类别所占的百分比

c2 = list(result["cluster"].value_counts() / len(result) * 100)

c3 = (list(map(lambda x: str(round(x, 3)) + "%", c2)))

c = pd.DataFrame({"level": range(1, len(c1) + 1), "数量": c1, "百分比": c3})

print(c)


# 写出csv

aggData2.to_csv('C:\\Users\\xiaohu\\Desktop\\用户价值分析\\东篱最终项目\\【修改版】用户价值分析项目--东篱\\RFM+K-Means算法对公司客户价值自动划分--东篱\\resource\\python_result_kmeans_50.csv', index=False)

cluster_center.to_csv('C:\\Users\\xiaohu\\Desktop\\用户价值分析\\东篱最终项目\\【修改版】用户价值分析项目--东篱\\RFM+K-Means算法对公司客户价值自动划分--东篱\\resource\\cluster_center.csv')

RFM+层次聚类

# -*- coding:utf-8 -*-

#######################################
#加载相关库
#######################################
import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN
from sklearn.cluster import Birch
from sklearn import metrics
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.externals import joblib
import time
import datetime

#######################################
#加载数据集及提取数列
#######################################

customdata = pd.read_csv(r'C:\\Users\\xiaohu\\Desktop\\RFM\\out_custom_label.csv')

new_custom_data = customdata[["R_S","F_S","M_S"]]

new_custom_data = new_custom_data.astype(np.float32)
new_custom_data = new_custom_data.values

#######################################
#数据标准化
#######################################

new_custom_data = StandardScaler().fit_transform(new_custom_data)

#######################################
#模型训练
#######################################

Birch_model = Birch(threshold=0.85, branching_factor=500,
                    n_clusters=None,compute_labels=True, copy=True).fit(new_custom_data)

#######################################
#提取分类结果
#######################################

label = Birch_model.labels_

#print ("Calinski-Harabasz Score", metrics.calinski_harabaz_score(new_custom_data, Birch_model))

label = pd.DataFrame(label)

label.columns = ['cluster.label']

outresult = pd.concat([customdata, label], axis = 1)

cluster_center = pd.DataFrame(Birch_model.subcluster_centers_)
n_clusters = np.unique(label).size
print("n_clusters : %d" % n_clusters)


#######################################
#结果输出
#######################################

outresult.to_csv('C:\\Users\\xiaohu\\Desktop\\RFM\\birch_outresult.csv')
cluster_center.to_csv('C:\\Users\\xiaohu\\Desktop\\RFM\\cluster_center.csv')

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页