温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

数据挖掘实战-客户价值分析

发布时间:2020-02-29 16:24:27 来源:网络 阅读:317 作者:专注地一哥 栏目:编程语言

数据简单分析

import pandas as pd

 

datafile= '../data/air_data.csv'  # 航空原始数据,第一行为属性标签

resultfile = '../tmp/explore.csv'  # 数据探索结果表

 

# 读取原始数据,指定UTF-8编码(需要用文本编辑器将数据装换为UTF-8编码)

data = pd.read_csv(datafile, encoding = 'utf-8')

 

# 包括对数据的基本描述,percentiles参数是指定计算多少的分位数表(如1/4分位数、中位数等)

explore = data.describe(percentiles = [], include = 'all').T  # T是转置,转置后更方便查阅

explore['null'] = len(data)-explore['count']  # describe()函数自动计算非空值数,需要手动计算空值数

 

explore = explore[['null', 'max', 'min']]

explore.columns = [u'空值数', u'最大值', u'最小值']  # 表头重命名

'''

这里只选取部分探索结果。

describe()函数自动计算的字段有count(非空值数)、unique(唯一值数)、top(频数最高者)、

freq(最高频数)、mean(平均值)、std(方差)、min(最小值)、50%(中位数)、max(最大值)

'''

简单可视化

import pandas as pd

import matplotlib.pyplot as plt

 

datafile= '../data/air_data.csv'  # 航空原始数据,第一行为属性标签

 

# 读取原始数据,指定UTF-8编码(需要用文本编辑器将数据装换为UTF-8编码)

data = pd.read_csv(datafile, encoding = 'utf-8')

 

# 客户信息类别

# 提取会员入会年份

from datetime import datetime

ffp = data['FFP_DATE'].apply(lambda x:datetime.strptime(x,'%Y/%m/%d'))

ffp_year = ffp.map(lambda x : x.year)

# 绘制各年份会员入会人数直方图

fig = plt.figure(figsize = (8 ,5))  # 设置画布大小

plt.rcParams['font.sans-serif'] = 'SimHei'  # 设置中文显示

plt.rcParams['axes.unicode_minus'] = False

plt.hist(ffp_year, bins='auto', color='#0504aa')

plt.xlabel('年份')

plt.ylabel('入会人数')

plt.title('各年份会员入会人数')

plt.show()

plt.close

 

# 提取会员不同性别人数

male = pd.value_counts(data['GENDER'])['']

female = pd.value_counts(data['GENDER'])['']

# 绘制会员性别比例饼图

fig = plt.figure(figsize = (7 ,4))  # 设置画布大小

plt.pie([ male, female], labels=['',''], colors=['lightskyblue', 'lightcoral'],

       autopct='%1.1f%%')

plt.title('会员性别比例')

plt.show()

plt.close

数据清洗

import numpy as np

import pandas as pd

 

datafile = '../data/air_data.csv'  # 航空原始数据路径

cleanedfile = '../tmp/data_cleaned.csv'  # 数据清洗后保存的文件路径

 

# 读取数据

airline_data = pd.read_csv(datafile,encoding = 'utf-8')

print('原始数据的形状为:',airline_data.shape)

 

# 去除票价为空的记录

airline_notnull = airline_data.loc[airline_data['SUM_YR_1'].notnull() &

                                   airline_data['SUM_YR_2'].notnull(),:]

print('删除缺失记录后数据的形状为:',airline_notnull.shape)

 

# 只保留票价非零的,或者平均折扣率不为0且总飞行公里数大于0的记录。

index1 = airline_notnull['SUM_YR_1'] != 0

index2 = airline_notnull['SUM_YR_2'] != 0

index3 = (airline_notnull['SEG_KM_SUM']> 0) & (airline_notnull['avg_discount'] != 0)

index4 = airline_notnull['AGE'] > 100  # 去除年龄大于100的记录

airline = airline_notnull[(index1 | index2) & index3 & ~index4]

print('数据清洗后数据的形状为:',airline.shape)

airline.to_csv(cleanedfile)  # 保存清洗后的数据

原始数据的形状为: (62988, 44)
删除缺失记录后数据的形状为: (62299, 44)
数据清洗后数据的形状为: (62043, 44)

属性选择、构造与数据标准化

# 属性选择、构造与数据标准化

 

import pandas as pd

import numpy as np

 

# 读取数据清洗后的数据

cleanedfile = '../tmp/data_cleaned.csv'  # 数据清洗后保存的文件路径

airline = pd.read_csv(cleanedfile, encoding = 'utf-8')

# 选取需求属性

airline_selection = airline[['FFP_DATE','LOAD_TIME','LAST_TO_END',

                                     'FLIGHT_COUNT','SEG_KM_SUM','avg_discount']]

print('筛选的属性前5行为:\n',airline_selection.head())

 

 

 

# 代码7-8

 

# 构造属性L

L = pd.to_datetime(airline_selection['LOAD_TIME']) - \

pd.to_datetime(airline_selection['FFP_DATE'])

L = L.astype('str').str.split().str[0]

L = L.astype('int')/30

 

# 合并属性

airline_features = pd.concat([L,airline_selection.iloc[:,2:]],axis = 1)

airline_features.columns = ['L','R','F','M','C']

print('构建的LRFMC属性前5行为:\n',airline_features.head())

 

# 数据标准化

from sklearn.preprocessing import StandardScaler

data = StandardScaler().fit_transform(airline_features)

np.savez('../tmp/airline_scale.npz',data)

print('标准化后LRFMC五个属性为:\n',data[:5,:])

筛选的属性前5行为:

FFP_DATE LOAD_TIME LAST_TO_END FLIGHT_COUNT SEG_KM_SUM avg_discount

0 2006/11/2 2014/3/31 1 210 580717 0.961639

1 2007/2/19 2014/3/31 7 140 293678 1.252314

2 2007/2/1 2014/3/31 11 135 283712 1.254676

3 2008/8/22 2014/3/31 97 23 281336 1.090870

4 2009/4/10 2014/3/31 5 152 309928 0.970658

构建的LRFMC属性前5行为:

L R F M C

0 90.200000 1 210 580717 0.961639

1 86.566667 7 140 293678 1.252314

2 87.166667 11 135 283712 1.254676

3 68.233333 97 23 281336 1.090870

4 60.533333 5 152 309928 0.970658

标准化后LRFMC五个属性为:

[[ 1.43579256 -0.94493902 14.03402401 26.76115699 1.29554188]

[ 1.30723219 -0.91188564 9.07321595 13.12686436 2.86817777]

[ 1.32846234 -0.88985006 8.71887252 12.65348144 2.88095186]

[ 0.65853304 -0.41608504 0.78157962 12.54062193 1.99471546]

[ 0.3860794 -0.92290343 9.92364019 13.89873597 1.34433641]]

import pandas as pd

import numpy as np

from sklearn.cluster import KMeans  # 导入kmeans算法

 

# 读取标准化后的数据

airline_scale = np.load('../tmp/airline_scale.npz')['arr_0']

k = 5  # 确定聚类中心数

 

# 构建模型,随机种子设为123

kmeans_model = KMeans(n_clusters = k,n_jobs=4,random_state=123)

fit_kmeans = kmeans_model.fit(airline_scale)  # 模型训练

 

# 查看聚类结果

kmeans_cc = kmeans_model.cluster_centers_  # 聚类中心

print('各类聚类中心为:\n',kmeans_cc)

kmeans_labels = kmeans_model.labels_  # 样本的类别标签

print('各样本的类别标签为:\n',kmeans_labels)

r1 = pd.Series(kmeans_model.labels_).value_counts()  # 统计不同类别样本的数目

print('最终每个类别的数目为:\n',r1)

# 输出聚类分群的结果

cluster_center = pd.DataFrame(kmeans_model.cluster_centers_,\

             columns = ['ZL','ZR','ZF','ZM','ZC'])   # 将聚类中心放在数据框中

cluster_center.index = pd.DataFrame(kmeans_model.labels_ ).\

                  drop_duplicates().iloc[:,0]  # 将样本类别作为数据框索引

print(cluster_center)

 

 

# 代码7-10

 

 

import matplotlib.pyplot as plt

# 客户分群雷达图

labels = ['ZL','ZR','ZF','ZM','ZC']

legen = ['客户群' + str(i + 1) for i in cluster_center.index]  # 客户群命名,作为雷达图的图例

lstype = ['-','--',(0, (3, 5, 1, 5, 1, 5)),':','-.']

kinds = list(cluster_center.iloc[:, 0])

# 由于雷达图要保证数据闭合,因此再添加L列,并转换为 np.ndarray

function(){ //亨达 http://www.hantecglobal.org.cn/

cluster_center = pd.concat([cluster_center, cluster_center[['ZL']]], axis=1)

centers = np.array(cluster_center.iloc[:, 0:])

 

# 分割圆周长,并让其闭合

n = len(labels)

angle = np.linspace(0, 2 * np.pi, n, endpoint=False)

angle = np.concatenate((angle, [angle[0]]))

 

# 绘图

fig = plt.figure(figsize = (8,6))

ax = fig.add_subplot(111, polar=True)  # 以极坐标的形式绘制图形

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签

plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 画线

for i in range(len(kinds)):

    ax.plot(angle, centers[i], linestyle=lstype[i], linewidth=2, label=kinds[i])

# 添加属性标签

ax.set_thetagrids(angle * 180 / np.pi, labels)

plt.title('客户特征分析雷达图')

plt.legend(legen)

plt.show()

plt.close

各类聚类中心为:

[[ 1.1606821 -0.37729768 -0.08690742 -0.09484273 -0.15591932]

[-0.31365557 1.68628985 -0.57402225 -0.53682279 -0.17332449]

[ 0.05219076 -0.00264741 -0.22674532 -0.23116846 2.19158505]

[-0.70022016 -0.4148591 -0.16116192 -0.1609779 -0.2550709 ]

[ 0.48337963 -0.79937347 2.48319841 2.42472188 0.30863168]]

各样本的类别标签为:

[4 4 4 3 1 1]

最终每个类别的数目为:

3 24661

0 15739

1 12125

4 5336

2 4182

dtype: int64

ZL ZR ZF ZM ZC

0

4 1.160682 -0.377298 -0.086907 -0.094843 -0.155919

2 -0.313656 1.686290 -0.574022 -0.536823 -0.173324

0 0.052191 -0.002647 -0.226745 -0.231168 2.191585

3 -0.700220 -0.414859 -0.161162 -0.160978 -0.255071

1 0.483380 -0.799373 2.483198 2.424722 0.308632

 


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI