无监督学习之聚类1——Kmeans
Kmeans算法分析31省市消费水平
#coding=utf-8 import numpy as np from sklearn.cluster import KMeans def loadData(filepath): fr = open(filepath, 'r+') lines = fr.readlines() retData = [] retCityName = [] for line in lines: items = line.strip().split(",")#以逗号为分割符读取数据 retCityName.append(items[0]) #将城市名加到城市名数据列表中 retData.append([float(items[i]) for i in range(1,len(items))]) #将数据中的其他data转化为float后加到retData中 return retData,retCityName if __name__ == '__main__': data,cityName = loadData('F:\data\city.txt') km = KMeans(n_clusters=4) #分成的簇的数目 label = km.fit_predict(data)#计算簇中心及为簇分配序号 expenses = np.sum(km.cluster_centers_, axis=1) #axis按行求和 CityCluster = [[],[],[],[]]#设置与簇数目对应的列表数来存储数据 #将每个城市分成设定的簇 for i in range(len(cityName)): CityCluster[label[i]].append(cityName[i]) #将每个簇的城市名输出 #输出每个簇的平均消费 for i in range(len(CityCluster)): print("Expenses: %.2f"%expenses[i]) print(CityCluster[i])
运算后;
Expenses: 4512.27
['江苏', '安徽', '湖南', '湖北', '广西', '海南', '四川', '云南']
Expenses: 7754.66
['北京', '上海', '广东']
Expenses: 5678.62
['天津', '浙江', '福建', '重庆', '西藏']
Expenses: 3788.76
['河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '江西', '山东', '河南', '贵州', '陕西', '甘肃', '青海', '宁夏', '新疆']