當前位置:首頁 » 編程語言 » kmeanspython

kmeanspython

發布時間: 2025-10-02 14:06:22

1. 減法聚類如何用python實現

下面是一個k-means聚類演算法在python2.7.5上面的具體實現,你需要先安裝Numpy和Matplotlib:
from numpy import *
import time
import matplotlib.pyplot as plt

# calculate Euclidean distance
def euclDistance(vector1, vector2):
return sqrt(sum(power(vector2 - vector1, 2)))
# init centroids with random samples
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
# k-means cluster
def kmeans(dataSet, k):
numSamples = dataSet.shape[0]
# first column stores which cluster this sample belongs to,
# second column stores the error between this sample and its centroid
clusterAssment = mat(zeros((numSamples, 2)))
clusterChanged = True
## step 1: init centroids
centroids = initCentroids(dataSet, k)
while clusterChanged:
clusterChanged = False
## for each sample
for i in xrange(numSamples):
minDist = 100000.0
minIndex = 0
## for each centroid
## step 2: find the centroid who is closest
for j in range(k):
distance = euclDistance(centroids[j, :], dataSet[i, :])
if distance < minDist:
minDist = distance
minIndex = j

## step 3: update its cluster
if clusterAssment[i, 0] != minIndex:
clusterChanged = True
clusterAssment[i, :] = minIndex, minDist**2
## step 4: update centroids
for j in range(k):
pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]]
centroids[j, :] = mean(pointsInCluster, axis = 0)
print 'Congratulations, cluster complete!'
return centroids, clusterAssment
# show your cluster only available with 2-D data
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 xrange(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()

熱點內容
安卓機其他文件40g怎麼清理 發布:2025-10-02 15:47:34 瀏覽:477
遺產資料庫 發布:2025-10-02 15:45:52 瀏覽:60
密碼箱手把斷了用什麼膠水 發布:2025-10-02 15:41:44 瀏覽:484
中值的演算法 發布:2025-10-02 15:15:57 瀏覽:582
iphone6s文件加密 發布:2025-10-02 15:08:24 瀏覽:465
win伺服器搭建php環境 發布:2025-10-02 15:05:01 瀏覽:872
獲取上傳文件的擴展名 發布:2025-10-02 15:03:32 瀏覽:738
c語言源碼庫 發布:2025-10-02 15:01:17 瀏覽:129
傅里葉演算法c語言 發布:2025-10-02 14:58:18 瀏覽:257
為什麼伺服器喜歡老系統 發布:2025-10-02 14:34:15 瀏覽:667