k-means算法思想較簡單,說的通俗易懂點(diǎn)就是物以類聚,花了一點(diǎn)時(shí)間在python中實(shí)現(xiàn)k-means算法,k-means算法有本身的缺點(diǎn),比如說k初始位置的選擇,針對這個(gè)有不少人提出k-means++算法進(jìn)行改進(jìn);另外一種是要對k大小的選擇也沒有很完善的理論,針對這個(gè)比較經(jīng)典的理論是輪廓系數(shù),二分聚類的算法確定k的大小,在最后還寫了二分聚類算法的實(shí)現(xiàn),代碼主要參考機(jī)器學(xué)習(xí)實(shí)戰(zhàn)那本書:
創(chuàng)新互聯(lián)建站網(wǎng)站建設(shè)服務(wù)商,為中小企業(yè)提供網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)服務(wù),網(wǎng)站設(shè)計(jì),網(wǎng)站改版維護(hù)等一站式綜合服務(wù)型公司,專業(yè)打造企業(yè)形象網(wǎng)站,讓您在眾多競爭對手中脫穎而出創(chuàng)新互聯(liá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)
新聞名稱:python中kmeans聚類實(shí)現(xiàn)代碼-創(chuàng)新互聯(lián)
文章轉(zhuǎn)載:http://jinyejixie.com/article28/iscjp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營銷型網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化、電子商務(wù)、微信公眾號(hào)、網(wǎng)站制作、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容