溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python中kmeans聚類實(shí)現(xiàn)代碼

發(fā)布時(shí)間:2020-10-06 12:41:17 來源:腳本之家 閱讀:260 作者:旭旭_哥 欄目:開發(fā)技術(shù)

k-means算法思想較簡(jiǎn)單,說的通俗易懂點(diǎn)就是物以類聚,花了一點(diǎn)時(shí)間在python中實(shí)現(xiàn)k-means算法,k-means算法有本身的缺點(diǎn),比如說k初始位置的選擇,針對(duì)這個(gè)有不少人提出k-means++算法進(jìn)行改進(jìn);另外一種是要對(duì)k大小的選擇也沒有很完善的理論,針對(duì)這個(gè)比較經(jīng)典的理論是輪廓系數(shù),二分聚類的算法確定k的大小,在最后還寫了二分聚類算法的實(shí)現(xiàn),代碼主要參考機(jī)器學(xué)習(xí)實(shí)戰(zhàn)那本書:

#encoding:utf-8 
''''' 
Created on 2015年9月21日 
@author: ZHOUMEIXU204 
''' 
 
 
path=u"D:\\Users\\zhoumeixu204\\Desktop\\python語言機(jī)器學(xué)習(xí)\\機(jī)器學(xué)習(xí)實(shí)戰(zhàn)代碼  python\\機(jī)器學(xué)習(xí)實(shí)戰(zhàn)代碼\\machinelearninginaction\\Ch20\\" 
import numpy as np 
def loadDataSet(fileName): #讀取數(shù)據(jù) 
  dataMat=[] 
  fr=open(fileName) 
  for line in fr.readlines(): 
    curLine=line.strip().split('\t') 
    fltLine=map(float,curLine) 
    dataMat.append(fltLine) 
  return dataMat 
def distEclud(vecA,vecB):  #計(jì)算距離 
  return np.sqrt(np.sum(np.power(vecA-vecB,2))) 
def randCent(dataSet,k):   #構(gòu)建鏃質(zhì)心 
  n=np.shape(dataSet)[1] 
  centroids=np.mat(np.zeros((k,n))) 
  for j in range(n): 
    minJ=np.min(dataSet[:,j]) 
    rangeJ=float(np.max(dataSet[:,j])-minJ) 
    centroids[:,j]=minJ+rangeJ*np.random.rand(k,1) 
  return centroids 
dataMat=np.mat(loadDataSet(path+'testSet.txt')) 
print(dataMat[:,0]) 
 
 
# 所有數(shù)都比-inf大 
# 所有數(shù)都比+inf小 
def kMeans(dataSet,k,distMeas=distEclud,createCent=randCent): 
  m=np.shape(dataSet)[0] 
  clusterAssment=np.mat(np.zeros((m,2))) 
  centroids=createCent(dataSet,k) 
  clusterChanged=True 
  while clusterChanged: 
    clusterChanged=False 
    for i in range(m): 
      minDist=np.inf;minIndex=-1 #np.inf表示無窮大 
      for j in range(k): 
        distJI=distMeas(centroids[j,:],dataSet[i,:]) 
        if distJI 
          minDist=distJI;minIndex=j 
      if clusterAssment[i,0]!=minIndex:clusterChanged=True 
      clusterAssment[i,:]=minIndex,minDist**2 
    print centroids 
    for cent in range(k): 
      ptsInClust=dataSet[np.nonzero(clusterAssment[:,0].A==cent)[0]] #[0]這里取0是指去除坐標(biāo)索引值,結(jié)果會(huì)有兩個(gè) 
      #np.nonzero函數(shù),尋找非0元素的下標(biāo) nz=np.nonzero([1,2,3,0,0,4,0])結(jié)果為0,1,2 
      centroids[cent,:]=np.mean(ptsInClust,axis=0) 
     
  return centroids,clusterAssment 
myCentroids,clustAssing=kMeans(dataMat,4)  
print(myCentroids,clustAssing)  
   
#二分均值聚類(bisecting k-means) 
def  biKmeans(dataSet,k,distMeas=distEclud): 
  m=np.shape(dataSet)[0] 
  clusterAssment=np.mat(np.zeros((m,2))) 
  centroid0=np.mean(dataSet,axis=0).tolist()[0] 
  centList=[centroid0] 
  for j in range(m): 
    clusterAssment[j,1]=distMeas(np.mat(centroid0),dataSet[j,:])**2 
  while (len(centList) 
    lowestSSE=np.Inf 
    for i in range(len(centList)): 
      ptsInCurrCluster=dataSet[np.nonzero(clusterAssment[:,0].A==i)[0],:] 
      centroidMat,splitClusAss=kMeans(ptsInCurrCluster,2,distMeas) 
      sseSplit=np.sum(splitClusAss[:,1]) 
      sseNotSplit=np.sum(clusterAssment[np.nonzero(clusterAssment[:,0].A!=i)[0],1]) 
      print "sseSplit, and notSplit:",sseSplit,sseNotSplit 
      if (sseSplit+sseNotSplit) 
        bestCenToSplit=i 
        bestNewCents=centroidMat 
        bestClustAss=splitClusAss.copy() 
        lowestSSE=sseSplit+sseNotSplit 
    bestClustAss[np.nonzero(bestClustAss[:,0].A==1)[0],0]=len(centList) 
    bestClustAss[np.nonzero(bestClustAss[:,0].A==0)[0],0]=bestCenToSplit 
    print "the bestCentToSplit is:",bestCenToSplit 
    print 'the len of bestClustAss is:',len(bestClustAss) 
    centList[bestCenToSplit]=bestNewCents[0,:] 
    centList.append(bestNewCents[1,:]) 
    clusterAssment[np.nonzero(clusterAssment[:,0].A==bestCenToSplit)[0],:]=bestClustAss 
  return centList,clusterAssment 
print(u"二分聚類分析結(jié)果開始") 
dataMat3=np.mat(loadDataSet(path+'testSet2.txt')) 
centList,myNewAssments=biKmeans(dataMat3, 3) 
print(centList) 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI