k-均值聚类是非监督学习的一种,输入必须指定聚簇中心个数k。k均值是基于相似度的聚类,为没有标签的一簇实例分为一类。

  一 经典的k-均值聚类  

  思路:  

  1 随机创建k个质心(k必须指定,二维的很容易确定,可视化数据分布,直观确定即可);

  2 遍历数据集的每个实例,计算其到每个质心的相似度,这里也就是欧氏距离;把每个实例都分配到距离最近的质心的那一类,用一个二维数组数据结构保存,第一列是最近质心序号,第二列是距离;

  3 根据二维数组保存的数据,重新计算每个聚簇新的质心;

  4 迭代2 和 3,直到收敛,即质心不再变化;

from numpy import *

def loadDataSet(fileName):      #general function to parse tab -delimited floats
dataMat = [] #assume last column is target value
fr = open(fileName)
for line in fr.readlines():
curLine = line.strip().split('\t')
fltLine = map(float,curLine) #map all elements to float()
dataMat.append(fltLine)
return dataMat def distEclud(vecA, vecB):
return sqrt(sum(power(vecA - vecB, ))) #la.norm(vecA-vecB) def randCent(dataSet, k):
n = shape(dataSet)[]
centroids = mat(zeros((k,n)))#create centroid mat
for j in range(n):#create random cluster centers, within bounds of each dimension
minJ = min(dataSet[:,j])
rangeJ = float(max(dataSet[:,j]) - minJ)
centroids[:,j] = mat(minJ + rangeJ * random.rand(k,))
return centroids def kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):
m = shape(dataSet)[]
clusterAssment = mat(zeros((m,)))#create mat to assign data points
#to a centroid, also holds SE of each point
centroids = createCent(dataSet, k)
clusterChanged = True
while clusterChanged:
clusterChanged = False
for i in range(m):#for each data point assign it to the closest centroid
minDist = inf; minIndex = -
for j in range(k):
distJI = distMeas(centroids[j,:],dataSet[i,:])
if distJI < minDist:
minDist = distJI; minIndex = j
if clusterAssment[i,] != minIndex: clusterChanged = True
clusterAssment[i,:] = minIndex,minDist**
print centroids
for cent in range(k):#recalculate centroids
ptsInClust = dataSet[nonzero(clusterAssment[:,].A==cent)[]]#get all the point in this cluster
centroids[cent,:] = mean(ptsInClust, axis=) #assign centroid to mean
return centroids, clusterAssment

  经典的k均值聚类有很大的缺点就是很容易收敛到局部最优,为了避免这种局部最优,我们引入了二分k-均值算法。

  二 二分k-均值聚类算法

  二分k-均值聚类算法是基于经典k-均值算法实现的;里面调用经典k-均值(k=2),把一个聚簇分成两个,迭代到分成k个停止;

  具体思路:

  1 把整个数据集看成一个聚簇,计算质心;并用同样的数据结构二维数组保存每个实例到质心的距离;

  2 对每一个聚簇进行2-均值聚类划分;

  3 计算划分后的误差,选择所有被划分的聚簇中总误差最小的划分保存;

  4 迭代2 和 3 直到聚簇数目达到k停止;

def biKmeans(dataSet, k, distMeas=distEclud):
m = shape(dataSet)[]
clusterAssment = mat(zeros((m,)))
centroid0 = mean(dataSet, axis=).tolist()[]
centList =[centroid0] #create a list with one centroid
for j in range(m):#calc initial Error
clusterAssment[j,] = distMeas(mat(centroid0), dataSet[j,:])**
while (len(centList) < k):
lowestSSE = inf
for i in range(len(centList)):
ptsInCurrCluster = dataSet[nonzero(clusterAssment[:,].A==i)[],:]#get the data points currently in cluster i
centroidMat, splitClustAss = kMeans(ptsInCurrCluster, , distMeas)
sseSplit = sum(splitClustAss[:,])#compare the SSE to the currrent minimum
sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:,].A!=i)[],])
print "sseSplit, and notSplit: ",sseSplit,'--',sseNotSplit
if (sseSplit + sseNotSplit) < lowestSSE:
bestCentToSplit = i
bestNewCents = centroidMat
bestClustAss = splitClustAss.copy()
lowestSSE = sseSplit + sseNotSplit
bestClustAss[nonzero(bestClustAss[:,].A == )[],] = len(centList) #change to ,, or whatever
bestClustAss[nonzero(bestClustAss[:,].A == )[],] = bestCentToSplit
print 'the bestCentToSplit is: ',bestCentToSplit
print 'the len of bestClustAss is: ', len(bestClustAss)
centList[bestCentToSplit] = bestNewCents[,:].tolist()[]#replace a centroid with two best centroids
centList.append(bestNewCents[,:].tolist()[])
clusterAssment[nonzero(clusterAssment[:,].A == bestCentToSplit)[],:]= bestClustAss#reassign new clusters, and SSE
return mat(centList), clusterAssment

  三 地理位置聚簇实例

  地理位置的经纬度正好是二维的,可以可视化出来,所以很适合聚类算法确定质心个数k值;值得注意的是,球面计算距离,不能简单的用欧式距离,而需要用球面距离公式,见函数distSLC;

  代码的含义给定n个俱乐部地址名称,然后使用urllib包,调用yahoo地图的API返回经纬度,调用我们上面实现的k均值聚类算法,找到聚簇的中心,最后利用matplotlib工具可视化出来;

import urllib
import json
def geoGrab(stAddress, city):
apiStem = 'http://where.yahooapis.com/geocode?' #create a dict and constants for the goecoder
params = {}
params['flags'] = 'J'#JSON return type
params['appid'] = 'aaa0VN6k'
params['location'] = '%s %s' % (stAddress, city)
url_params = urllib.urlencode(params)
yahooApi = apiStem + url_params #print url_params
print yahooApi
c=urllib.urlopen(yahooApi)
return json.loads(c.read()) from time import sleep
def massPlaceFind(fileName):
fw = open('places.txt', 'w')
for line in open(fileName).readlines():
line = line.strip()
lineArr = line.split('\t')
retDict = geoGrab(lineArr[], lineArr[])
if retDict['ResultSet']['Error'] == :
lat = float(retDict['ResultSet']['Results'][]['latitude'])
lng = float(retDict['ResultSet']['Results'][]['longitude'])
print "%s\t%f\t%f" % (lineArr[], lat, lng)
fw.write('%s\t%f\t%f\n' % (line, lat, lng))
else: print "error fetching"
sleep()
fw.close() def distSLC(vecA, vecB):#Spherical Law of Cosines
a = sin(vecA[,]*pi/) * sin(vecB[,]*pi/)
b = cos(vecA[,]*pi/) * cos(vecB[,]*pi/) * \
cos(pi * (vecB[,]-vecA[,]) /)
return arccos(a + b)*6371.0 #pi is imported with numpy import matplotlib
import matplotlib.pyplot as plt
def clusterClubs(numClust=):
datList = []
for line in open('places.txt').readlines():
lineArr = line.split('\t')
datList.append([float(lineArr[]), float(lineArr[])])
datMat = mat(datList)
myCentroids, clustAssing = biKmeans(datMat, numClust, distMeas=distSLC)
fig = plt.figure()
rect=[0.1,0.1,0.8,0.8]
scatterMarkers=['s', 'o', '^', '', 'p', \
'd', 'v', 'h', '>', '<']
axprops = dict(xticks=[], yticks=[])
ax0=fig.add_axes(rect, label='ax0', **axprops)
imgP = plt.imread('Portland.png')
ax0.imshow(imgP)
ax1=fig.add_axes(rect, label='ax1', frameon=False)
for i in range(numClust):
ptsInCurrCluster = datMat[nonzero(clustAssing[:,].A==i)[],:]
markerStyle = scatterMarkers[i % len(scatterMarkers)]
ax1.scatter(ptsInCurrCluster[:,].flatten().A[], ptsInCurrCluster[:,].flatten().A[], marker=markerStyle, s=)
ax1.scatter(myCentroids[:,].flatten().A[], myCentroids[:,].flatten().A[], marker='+', s=)
plt.show()

  四 总结

  优点:易实现;

  缺点:可能收敛到局部最小值,在大数据集上收敛较慢;

  适用数据类型:数值型;

机器学习实战5:k-means聚类:二分k均值聚类+地理位置聚簇实例的更多相关文章

  1. 机器学习算法与Python实践之(六)二分k均值聚类

    http://blog.csdn.net/zouxy09/article/details/17590137 机器学习算法与Python实践之(六)二分k均值聚类 zouxy09@qq.com http ...

  2. 机器学习理论与实战(十)K均值聚类和二分K均值聚类

    接下来就要说下无监督机器学习方法,所谓无监督机器学习前面也说过,就是没有标签的情况,对样本数据进行聚类分析.关联性分析等.主要包括K均值聚类(K-means clustering)和关联分析,这两大类 ...

  3. 机器学习实战---K均值聚类算法

    一:一般K均值聚类算法实现 (一)导入数据 import numpy as np import matplotlib.pyplot as plt def loadDataSet(filename): ...

  4. 机器学习算法与Python实践之(五)k均值聚类(k-means)

    机器学习算法与Python实践这个系列主要是参考<机器学习实战>这本书.因为自己想学习Python,然后也想对一些机器学习算法加深下了解,所以就想通过Python来实现几个比较常用的机器学 ...

  5. K近邻 Python实现 机器学习实战(Machine Learning in Action)

    算法原理 K近邻是机器学习中常见的分类方法之间,也是相对最简单的一种分类方法,属于监督学习范畴.其实K近邻并没有显式的学习过程,它的学习过程就是测试过程.K近邻思想很简单:先给你一个训练数据集D,包括 ...

  6. 【机器学习笔记五】聚类 - k均值聚类

    参考资料: [1]Spark Mlib 机器学习实践 [2]机器学习 [3]深入浅出K-means算法  http://www.csdn.net/article/2012-07-03/2807073- ...

  7. 机器学习实战python3 K近邻(KNN)算法实现

    台大机器技法跟基石都看完了,但是没有编程一直,现在打算结合周志华的<机器学习>,撸一遍机器学习实战, 原书是python2 的,但是本人感觉python3更好用一些,所以打算用python ...

  8. k近邻算法python实现 -- 《机器学习实战》

    ''' Created on Nov 06, 2017 kNN: k Nearest Neighbors Input: inX: vector to compare to existing datas ...

  9. 机器学习实战-k近邻算法

    写在开头,打算耐心啃完机器学习实战这本书,所用版本为2013年6月第1版 在P19页的实施kNN算法时,有很多地方不懂,遂仔细研究,记录如下: 字典按值进行排序 首先仔细读完kNN算法之后,了解其是用 ...

随机推荐

  1. [RVM is not a function] Interating RVM with gnome-terminal

    Ubuntu 12.04 64bit LTS, running the 'rvm use 1.9.3' brings the 'RVM is not a function' warning. Here ...

  2. NSOperationQueue 多线程

    staticNSOperationQueue * queue; - (void)viewDidLoad { [superviewDidLoad]; queue = [[NSOperationQueue ...

  3. iptables conntrack有什么用

    iptables conntrack有什么用 http://zhidao.baidu.com/link?url=Eh5SRuplbsY_WkxxGkH4bpEyfMnHAe1RwJYSVlRYGKFU ...

  4. tomcat 禁用不安全的http请求模式 .

    HTTP服务器至少应该实现GET和HEAD方法,其他方法都是可选的.当然,所有的方法支持的实现都应当符合下述的方法各自的语义定义.此外,除了上述方法,特定的HTTP服务器还能够扩展自定义的方法. ht ...

  5. iptables 基础知识

    [root@tp ~]#iptables -L -n 查看防火墙规则 [root@tp ~]# iptables -D INPUT 1  根据命令iptables -L -n --line-numbe ...

  6. iOS-self.layer.shouldRasterize属性

    当shouldRasterize设成true时,layer被渲染成一个bitmap,并缓存起来,等下次使用时不会再重新去渲染了.实现圆角本身就是在做颜色混合(blending),如果每次页面出来时都b ...

  7. SQL Server中使用正则表达式

    SQL Server 2005及以上版本支持用CLR语言(C# .NET.VB.NET)编写过程.触发器和函数,因此使得正则匹配,数据提取能够在SQL中灵活运用,大大提高了SQL处理字符串,文本等内容 ...

  8. Swift游戏实战-跑酷熊猫 14 熊猫打滚

    这节内容我们来实现熊猫打滚.思路是这样的,当熊猫起跳时记录他的Y坐标,落到平台上的时候再记录它的Y坐标.两个坐标之间的差要是大于一定数值就判断它从高处落下要进行打滚缓冲.至此跑酷熊猫已经像一个游戏的样 ...

  9. Leetcode: Palindrome Numbers

    Determine whether an integer is a palindrome. Do this without extra space. 尝试用两头分别比较的方法,结果发现无法解决1000 ...

  10. SQLserver查看数据库端口 脚本

    exec sys.sp_readerrorlog 0, 1, 'listening'