本文之编写程序涉及到API介绍,程序的完整实现,具体算法原理请查看之前所写的K-Means算法介绍
一、基础准备
1、python 基础
random.uniform
方法将随机生成下一个实数,它在[x,y]范围内。
print(random.uniform(2,6))
#uniform(5, 10) 的随机数为 : 6.98774810047
#uniform(7, 14) 的随机数为 : 12.2243345905
2、numpy 基础
mat
matrices,将数组转换成矩阵运算
data = [[2,6],[3,6]]
print(data)
#>>[[2, 6], [3, 6]]
print(np.mat(data))
#>>[[2 6]
[3 6]]
二、完整程序
# -*- coding: utf-8 -*-
from numpy import *
import time
import matplotlib.pyplot as plt
# 计算距离
def euclDistance(vector1, vector2):
return sqrt(sum(power(vector2 - vector1, 2)))
# 获取初始值
def initCentroids(dataSet, k):
numSamples, dim = dataSet.shape
centroids = zeros((k, dim))
for i in range(k):
index = int(random.uniform(0, numSamples))
centroids[i, :] = dataSet[index, :]
return centroids
# 聚类
def kmeans(dataSet, k):
numSamples = dataSet.shape[0]
clusterAssment = mat(zeros((numSamples, 2)))
clusterChanged = True
#获取初始聚类中心
centroids = initCentroids(dataSet, k)
# 不断迭代,指导聚类中点没有变化
while clusterChanged:
clusterChanged = False
for i in range(numSamples):
minDist = 100000.0
minIndex = 0
for j in range(k):
#计算出距离
distance = euclDistance(centroids[j, :], dataSet[i, :])
#求出最短的聚类点
if distance < minDist:
minDist = distance
minIndex = j
# 如果该点聚类有变化,则重新赋值
if clusterAssment[i, 0] != minIndex:
clusterChanged = True
clusterAssment[i, :] = minIndex, minDist ** 2
# 更新聚类中心点
for j in range(k):
pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]]
centroids[j, :] = mean(pointsInCluster, axis=0)
print('聚类完毕')
return centroids, clusterAssment
#展示数据
def showCluster(dataSet, k, centroids, clusterAssment):
numSamples, dim = dataSet.shape
if dim != 2:
print("Sorry! I can not draw because the dimension of your data is not 2!")
return 1
mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']
if k > len(mark):
print("Sorry! Your k is too large! please contact Zouxy")
return 1
# draw all samples
for i in range(numSamples):
markIndex = int(clusterAssment[i, 0])
plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex])
mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']
# draw the centroids
for i in range(k):
plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize=12)
plt.show()
if __name__ == '__main__':
print("加载数据")
dataSet = []
fileIn = open('data\\testData.txt')
for line in fileIn.readlines():
lineArr = line.strip().split(' ')
dataSet.append([float(lineArr[0]), float(lineArr[1])])
#转化为矩阵
dataSet = mat(dataSet)
k = 4
centroids, clusterAssment = kmeans(dataSet, k)
# 最后结果
print(centroids)
print("显示数据")
showCluster(dataSet, k, centroids, clusterAssment)