K-Means
import pandas as pd
import os
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
path=os.getcwd()+'\\'+'8c859681-527c-4d9b-a98a-f00e6169931f_.xls'
path1=os.getcwd()+'\\'+'test124.xls'
data=pd.read_excel(path)
k=3
iteration=1902
model=KMeans(n_clusters=k,n_jobs=4,max_iter=iteration)
model.fit(data)
r1=pd.Series(model.labels_).value_counts()#统计各个类别的数目
r2=pd.DataFrame(model.cluster_centers_)#找出聚类中心
r=pd.concat([r2,r1],axis=1)
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(path1)
def density_plot(data):
plt.figure(figsize=(20,10))
p=plt.plot(data,linewidth=2)
plt.ylabel(u'密度')
plt.xlabel(u'分群')
plt.legend()
return plt
pic_output=os.getcwd()+'\\'+'pd_'
for i in range(k):
density_plot(data[r[u'聚类类别']==i]).savefig(u'%s%s.png'%(pic_output,i))