1. #-*- coding: utf-8 -*-
    2. #使用K-Means算法聚类消费行为特征数据
    3. import numpy as np
    4. import pandas as pd
    5. #参数初始化
    6. inputfile = '../data/consumption_data.xls' #销量及其他属性数据
    7. k = 3 #聚类的类别
    8. threshold = 2 #离散点阈值
    9. iteration = 500 #聚类最大循环次数
    10. data = pd.read_excel(inputfile, index_col = 'Id') #读取数据
    11. data_zs = 1.0*(data - data.mean())/data.std() #数据标准化
    12. from sklearn.cluster import KMeans
    13. model = KMeans(n_clusters = k, n_jobs = 4, max_iter = iteration) #分为k类,并发数4
    14. model.fit(data_zs) #开始聚类
    15. #标准化数据及其类别
    16. r = pd.concat([data_zs, pd.Series(model.labels_, index = data.index)], axis = 1) #每个样本对应的类别
    17. r.columns = list(data.columns) + [u'聚类类别'] #重命名表头
    18. norm = []
    19. for i in range(k): #逐一处理
    20. norm_tmp = r[['R', 'F', 'M']][r[u'聚类类别'] == i]-model.cluster_centers_[i]
    21. norm_tmp = norm_tmp.apply(np.linalg.norm, axis = 1) #求出绝对距离
    22. norm.append(norm_tmp/norm_tmp.median()) #求相对距离并添加
    23. norm = pd.concat(norm) #合并
    24. import matplotlib.pyplot as plt
    25. plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
    26. plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
    27. norm[norm <= threshold].plot(style = 'go') #正常点
    28. discrete_points = norm[norm > threshold] #离群点
    29. discrete_points.plot(style = 'ro')
    30. for i in range(len(discrete_points)): #离群点做标记
    31. id = discrete_points.index[i]
    32. n = discrete_points.iloc[i]
    33. plt.annotate('(%s, %0.2f)'%(id, n), xy = (id, n), xytext = (id, n))
    34. plt.xlabel(u'编号')
    35. plt.ylabel(u'相对距离')
    36. plt.show()