#coding=utf-8 """ 2017.3.14 天气数据分析 """ import os import xlrd data = [] xls =xlrd.open_workbook("weather.xls") sheet = xls.sheets()[0] result1 = sheet.col_values(2) print result1 result2 = sheet.col_values(3) T = dict(zip(result1,result2)) type(T) print u'List' X = list(map(lambda x,y: (x,y), T.keys(),T.values())) print X print type(X) print len(X) """ KMeans聚类 clf = KMeans(n_clusters=3) 表示类簇数为3,聚成3类数据,clf即赋值为KMeans y_pred = clf.fit_predict(X) 载入数据集X,并且将聚类的结果赋值给y_pred """ from sklearn.cluster import Birch from sklearn.cluster import KMeans clf = KMeans(n_clusters=3) y_pred = clf.fit_predict(X) print(clf) print(y_pred) """ 可视化绘图 Python导入Matplotlib包,专门用于绘图 import matplotlib.pyplot as plt 此处as相当于重命名,plt用于显示图像 """ import numpy as np import matplotlib.pyplot as plt # 获取第一列和第二列数据 使用for循环获取 n[0]表示X第一列 x = [n[0] for n in X] print x y = [n[1] for n in X] print y # 绘制散点图 参数:x横轴 y纵轴 c=y_pred聚类预测结果 marker类型 o表示圆点 *表示星型 x表示点 # plt.scatter(x, y, c=y_pred, marker='x') # 坐标 x1 = [] y1 = [] x2 = [] y2 = [] x3 = [] y3 = [] # 分布获取类标为0、1、2的数据 赋值给(x1,y1) (x2,y2) (x3,y3) i = 0 while i < len(X): if y_pred[i] == 0: x1.append(X[i][0]) y1.append(X[i][1]) elif y_pred[i] == 1: x2.append(X[i][0]) y2.append(X[i][1]) elif y_pred[i] == 2: x3.append(X[i][0]) y3.append(X[i][1]) i = i + 1 # 四种颜色 红 绿 蓝 黑 plot1, = plt.plot(x1, y1, 'or', marker="x") plot2, = plt.plot(x2, y2, 'og', marker="o") plot3, = plt.plot(x3, y3, 'ob', marker="*") # 绘制标题 plt.title("Kmeans-HTemp-LTemp") # 绘制x轴和y轴坐标 plt.xlabel("Htemp") plt.ylabel("Ltemp") # 设置右上角图例 plt.legend((plot1, plot2, plot3), ('A', 'B', 'C'), fontsize=10) plt.show()
KMeans案例
最新推荐文章于 2023-09-25 14:32:05 发布