#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
inputfile='E:\\pycharm\\python数据分析与挖掘实战数据及源码\\chapter5\\demo\\data\\consumption_data.xls'
outputfile='E:\\pycharm\\python数据分析与挖掘实战数据及源码\\chapter5\\demo\\tmp\\data_type1.xls'
k=3
iteration=500
data=pd.read_excel(inputfile,index_col=u'Id')
data_zs=1.0*(data-data.mean())/data.std()#数据标准化
from sklearn.cluster import KMeans
model=KMeans(n_clusters=k,n_jobs=1,max_iter=iteration)#分为k类,并发数为4
model.fit(data_zs)
#简单打印结果
r1=pd.Series(model.labels_).value_counts()#统计各个类别的数目
r2=pd.DataFrame(model.cluster_centers_)#找出聚类中心
r=pd.concat([r2,r1],axis=1)#横向连接(0是纵向),得到聚类中心对应的类别下的数目
r.columns=list(data.columns)+[u'类别数目']
#详细输出原始数据及其类别
r=pd.concat([data,pd.Series(model.labels_,index=data.index)],axis=1)
r.columns=list(data.columns)+[u'聚类类别']
r.to_excel(outputfile)
def density_plot(data):#自定义作图函数
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
p=data.plot(kind='kde',linewidth=2,subplots=True,sharex=False)#kde表示密度图
[p[i].set_ylabel(u'密度') for i in range(k)]
plt.legend()
return plt
pic_output='E:\\pycharm\\python数据分析与挖掘实战数据及源码\\chapter5\\demo\\tmp\\new'
for i in range(k):
density_plot(data[r['聚类类别']==i]).savefig(u'%s%s.png' %(pic_output,i))
#用TSNE进行数据降维并展示聚类结果
from sklearn.manifold import TSNE
tsne=TSNE()
tsne.fit_transform(data_zs)
tsne=pd.DataFrame(tsne.embedding_,index=data_zs.index)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
d=tsne[r[u'聚类类别']==0]
plt.plot(d[0],d[1],'r.')
d=tsne[r[u'聚类类别']==1]
plt.plot(d[0],d[1],'go')
d=tsne[r[u'聚类类别']==2]
plt.plot(d[0],d[1],'b*')
plt.show()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#使用Apriori算法挖掘菜品订单关联规则
import pandas as pd
from apriori import *
inputfile='E:\\pycharm\\python数据分析与挖掘实战数据及源码\\chapter5\\demo\\data\\menu_orders.xls'
outputfile='E:\\pycharm\\python数据分析与挖掘实战数据及源码\\chapter5\\demo\\tmp\\apriori_rules.xls'
data=pd.read_excel(inputfile,header=None)
print(u'\n转换原始数据01矩阵...')
ct=lambda x:pd.Series(1,index=x[pd.notnull(x)])#转换01矩阵的过渡函数
b=map(ct,data.as_matrix())#用map方式执行,map(函数,对象),只是一个将对象进行函数化后的容器
data=pd.DataFrame(list(b)).fillna(0)#实现矩阵转化,空值用0填充
print(u'\n转换完毕')
del b#删除中间变量b,节省内存
support=0.2
confidence=0.5
ms='----'#连接符,用来区分不通过元素,如A---B,需要保证原始表格中不含有该字符
find_rule(data,support,confidence,ms).to_excel(outputfile)
将提前编译好的apriori.py放入sitepakges中
#-*- coding: utf-8 -*-
from __future__ import print_function
import pandas as pd
#自定义连接函数,用于实现L_{k-1}到C_k的连接
def connect_string(x, ms):
x = list(map(lambda i:sorted(i.split(ms)), x))
l = len(x[0])
r = []
for i in range(len(x)):
for j in range(i,len(x)):
if x[i][:l-1] == x[j][:l-1] and x[i][l-1] != x[j][l-1]:
r.append(x[i][:l-1]+sorted([x[j][l-1],x[i][l-1]]))
return r
#寻找关联规则的函数
def find_rule(d, support, confidence, ms = u'--'):
result = pd.DataFrame(index=['support', 'confidence']) #定义输出结果
support_series = 1.0*d.sum()/len(d) #支持度序列
column = list(support_series[support_series > support].index) #初步根据支持度筛选
k = 0
while len(column) > 1:
k = k+1
print(u'\n正在进行第%s次搜索...' %k)
column = connect_string(column, ms)
print(u'数目:%s...' %len(column))
sf = lambda i: d[i].prod(axis=1, numeric_only = True) #新一批支持度的计算函数
#创建连接数据,这一步耗时、耗内存最严重。当数据集较大时,可以考虑并行运算优化。
d_2 = pd.DataFrame(list(map(sf,column)), index = [ms.join(i) for i in column]).T
support_series_2 = 1.0*d_2[[ms.join(i) for i in column]].sum()/len(d) #计算连接后的支持度
column = list(support_series_2[support_series_2 > support].index) #新一轮支持度筛选
support_series = support_series.append(support_series_2)
column2 = []
for i in column: #遍历可能的推理,如{A,B,C}究竟是A+B-->C还是B+C-->A还是C+A-->B?
i = i.split(ms)
for j in range(len(i)):
column2.append(i[:j]+i[j+1:]+i[j:j+1])
cofidence_series = pd.Series(index=[ms.join(i) for i in column2]) #定义置信度序列
for i in column2: #计算置信度序列
cofidence_series[ms.join(i)] = support_series[ms.join(sorted(i))]/support_series[ms.join(i[:len(i)-1])]
for i in cofidence_series[cofidence_series > confidence].index: #置信度筛选
result[i] = 0.0
result[i]['confidence'] = cofidence_series[i]
result[i]['support'] = support_series[ms.join(sorted(i.split(ms)))]
result = result.T.sort_values(['confidence','support'], ascending = False) #结果整理,输出
print(u'\n结果为:')
print(result)
return result