[关闭]
@knight 2015-06-17T20:53:05.000000Z 字数 4725 阅读 2063

K-均值聚类

python 机器学习


  1. from numpy import *
  2. def loadDataSet(fileName): #general function to parse tab -delimited floats
  3. dataMat = [] #assume last column is target value
  4. fr = open(fileName)
  5. for line in fr.readlines():
  6. curLine = line.strip().split('\t')
  7. fltLine = map(float,curLine) #map all elements to float()
  8. dataMat.append(fltLine)
  9. return dataMat
  10. def distEclud(vecA, vecB):
  11. return sqrt(sum(power(vecA - vecB, 2))) #la.norm(vecA-vecB)
  12. def randCent(dataSet, k):
  13. n = shape(dataSet)[1]
  14. centroids = mat(zeros((k,n)))#create centroid mat
  15. for j in range(n):#create random cluster centers, within bounds of each dimension
  16. minJ = min(dataSet[:,j])
  17. rangeJ = float(max(dataSet[:,j]) - minJ)
  18. centroids[:,j] = mat(minJ + rangeJ * random.rand(k,1))
  19. return centroids
  20. def kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):
  21. m = shape(dataSet)[0]
  22. clusterAssment = mat(zeros((m,2)))#create mat to assign data points
  23. #to a centroid, also holds SE of each point
  24. centroids = createCent(dataSet, k)
  25. clusterChanged = True
  26. while clusterChanged:
  27. clusterChanged = False
  28. for i in range(m):#for each data point assign it to the closest centroid
  29. minDist = inf; minIndex = -1
  30. for j in range(k):
  31. distJI = distMeas(centroids[j,:],dataSet[i,:])
  32. if distJI < minDist:
  33. minDist = distJI; minIndex = j
  34. if clusterAssment[i,0] != minIndex: clusterChanged = True
  35. clusterAssment[i,:] = minIndex,minDist**2
  36. print centroids
  37. for cent in range(k):#recalculate centroids
  38. ptsInClust = dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]#get all the point in this cluster
  39. centroids[cent,:] = mean(ptsInClust, axis=0) #assign centroid to mean
  40. return centroids, clusterAssment
  41. def biKmeans(dataSet, k, distMeas=distEclud):
  42. m = shape(dataSet)[0]
  43. clusterAssment = mat(zeros((m,2)))
  44. centroid0 = mean(dataSet, axis=0).tolist()[0]
  45. centList =[centroid0] #create a list with one centroid
  46. for j in range(m):#calc initial Error
  47. clusterAssment[j,1] = distMeas(mat(centroid0), dataSet[j,:])**2
  48. while (len(centList) < k):
  49. lowestSSE = inf
  50. for i in range(len(centList)):
  51. ptsInCurrCluster = dataSet[nonzero(clusterAssment[:,0].A==i)[0],:]#get the data points currently in cluster i
  52. centroidMat, splitClustAss = kMeans(ptsInCurrCluster, 2, distMeas)
  53. sseSplit = sum(splitClustAss[:,1])#compare the SSE to the currrent minimum
  54. sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:,0].A!=i)[0],1])
  55. print "sseSplit, and notSplit: ",sseSplit,sseNotSplit
  56. if (sseSplit + sseNotSplit) < lowestSSE:
  57. bestCentToSplit = i
  58. bestNewCents = centroidMat
  59. bestClustAss = splitClustAss.copy()
  60. lowestSSE = sseSplit + sseNotSplit
  61. bestClustAss[nonzero(bestClustAss[:,0].A == 1)[0],0] = len(centList) #change 1 to 3,4, or whatever
  62. bestClustAss[nonzero(bestClustAss[:,0].A == 0)[0],0] = bestCentToSplit
  63. print 'the bestCentToSplit is: ',bestCentToSplit
  64. print 'the len of bestClustAss is: ', len(bestClustAss)
  65. centList[bestCentToSplit] = bestNewCents[0,:].tolist()[0]#replace a centroid with two best centroids
  66. centList.append(bestNewCents[1,:].tolist()[0])
  67. clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],:]= bestClustAss#reassign new clusters, and SSE
  68. return mat(centList), clusterAssment
  69. import urllib
  70. import json
  71. def geoGrab(stAddress, city):
  72. apiStem = 'http://where.yahooapis.com/geocode?' #create a dict and constants for the goecoder
  73. params = {}
  74. params['flags'] = 'J'#JSON return type
  75. params['appid'] = 'aaa0VN6k'
  76. params['location'] = '%s %s' % (stAddress, city)
  77. url_params = urllib.urlencode(params)
  78. yahooApi = apiStem + url_params #print url_params
  79. print yahooApi
  80. c=urllib.urlopen(yahooApi)
  81. return json.loads(c.read())
  82. from time import sleep
  83. def massPlaceFind(fileName):
  84. fw = open('places.txt', 'w')
  85. for line in open(fileName).readlines():
  86. line = line.strip()
  87. lineArr = line.split('\t')
  88. retDict = geoGrab(lineArr[1], lineArr[2])
  89. if retDict['ResultSet']['Error'] == 0:
  90. lat = float(retDict['ResultSet']['Results'][0]['latitude'])
  91. lng = float(retDict['ResultSet']['Results'][0]['longitude'])
  92. print "%s\t%f\t%f" % (lineArr[0], lat, lng)
  93. fw.write('%s\t%f\t%f\n' % (line, lat, lng))
  94. else: print "error fetching"
  95. sleep(1)
  96. fw.close()
  97. def distSLC(vecA, vecB):#Spherical Law of Cosines
  98. a = sin(vecA[0,1]*pi/180) * sin(vecB[0,1]*pi/180)
  99. b = cos(vecA[0,1]*pi/180) * cos(vecB[0,1]*pi/180) * \
  100. cos(pi * (vecB[0,0]-vecA[0,0]) /180)
  101. return arccos(a + b)*6371.0 #pi is imported with numpy
  102. import matplotlib
  103. import matplotlib.pyplot as plt
  104. def clusterClubs(numClust=5):
  105. datList = []
  106. for line in open('places.txt').readlines():
  107. lineArr = line.split('\t')
  108. datList.append([float(lineArr[4]), float(lineArr[3])])
  109. datMat = mat(datList)
  110. myCentroids, clustAssing = biKmeans(datMat, numClust, distMeas=distSLC)
  111. fig = plt.figure()
  112. rect=[0.1,0.1,0.8,0.8]
  113. scatterMarkers=['s', 'o', '^', '8', 'p', \
  114. 'd', 'v', 'h', '>', '<']
  115. axprops = dict(xticks=[], yticks=[])
  116. ax0=fig.add_axes(rect, label='ax0', **axprops)
  117. imgP = plt.imread('Portland.png')
  118. ax0.imshow(imgP)
  119. ax1=fig.add_axes(rect, label='ax1', frameon=False)
  120. for i in range(numClust):
  121. ptsInCurrCluster = datMat[nonzero(clustAssing[:,0].A==i)[0],:]
  122. markerStyle = scatterMarkers[i % len(scatterMarkers)]
  123. ax1.scatter(ptsInCurrCluster[:,0].flatten().A[0], ptsInCurrCluster[:,1].flatten().A[0], marker=markerStyle, s=90)
  124. ax1.scatter(myCentroids[:,0].flatten().A[0], myCentroids[:,1].flatten().A[0], marker='+', s=300)
  125. plt.show()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注