本文實(shí)例講述了Python基于聚類(lèi)算法實(shí)現(xiàn)密度聚類(lèi)(DBSCAN)計(jì)算。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)專(zhuān)注于十堰鄖陽(yáng)網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供十堰鄖陽(yáng)營(yíng)銷(xiāo)型網(wǎng)站建設(shè),十堰鄖陽(yáng)網(wǎng)站制作、十堰鄖陽(yáng)網(wǎng)頁(yè)設(shè)計(jì)、十堰鄖陽(yáng)網(wǎng)站官網(wǎng)定制、微信小程序開(kāi)發(fā)服務(wù),打造十堰鄖陽(yáng)網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供十堰鄖陽(yáng)網(wǎng)站排名全網(wǎng)營(yíng)銷(xiāo)落地服務(wù)。算法思想
基于密度的聚類(lèi)算法從樣本密度的角度考察樣本之間的可連接性,并基于可連接樣本不斷擴(kuò)展聚類(lèi)簇得到最終結(jié)果。
幾個(gè)必要概念:
ε-鄰域:對(duì)于樣本集中的xj, 它的ε-鄰域?yàn)闃颖炯信c它距離小于ε的樣本所構(gòu)成的集合。
核心對(duì)象:若xj的ε-鄰域中至少包含MinPts個(gè)樣本,則xj為一個(gè)核心對(duì)象。
密度直達(dá):若xj位于xi的ε-鄰域中,且xi為核心對(duì)象,則xj由xi密度直達(dá)。
密度可達(dá):若樣本序列p1, p2, ……, pn。pi+1由pi密度直達(dá),則p1由pn密度可達(dá)。
大致思想如下:
1. 初始化核心對(duì)象集合T為空,遍歷一遍樣本集D中所有的樣本,計(jì)算每個(gè)樣本點(diǎn)的ε-鄰域中包含樣本的個(gè)數(shù),如果個(gè)數(shù)大于等于MinPts,則將該樣本點(diǎn)加入到核心對(duì)象集合中。初始化聚類(lèi)簇?cái)?shù)k = 0, 初始化未訪問(wèn)樣本集和為P = D。
2. 當(dāng)T集合中存在樣本時(shí)執(zhí)行如下步驟:
Q = Q+S, P = P-S
3. 劃分為C= {C1, C2, ……, Ck}
Python代碼實(shí)現(xiàn)
#-*- coding:utf-8 -*- import math import numpy as np import pylab as pl #數(shù)據(jù)集:每三個(gè)是一組分別是西瓜的編號(hào),密度,含糖量 data = """ 1,0.697,0.46,2,0.774,0.376,3,0.634,0.264,4,0.608,0.318,5,0.556,0.215, 6,0.403,0.237,7,0.481,0.149,8,0.437,0.211,9,0.666,0.091,10,0.243,0.267, 11,0.245,0.057,12,0.343,0.099,13,0.639,0.161,14,0.657,0.198,15,0.36,0.37, 16,0.593,0.042,17,0.719,0.103,18,0.359,0.188,19,0.339,0.241,20,0.282,0.257, 21,0.748,0.232,22,0.714,0.346,23,0.483,0.312,24,0.478,0.437,25,0.525,0.369, 26,0.751,0.489,27,0.532,0.472,28,0.473,0.376,29,0.725,0.445,30,0.446,0.459""" #數(shù)據(jù)處理 dataset是30個(gè)樣本(密度,含糖量)的列表 a = data.split(',') dataset = [(float(a[i]), float(a[i+1])) for i in range(1, len(a)-1, 3)] #計(jì)算歐幾里得距離,a,b分別為兩個(gè)元組 def dist(a, b): return math.sqrt(math.pow(a[0]-b[0], 2)+math.pow(a[1]-b[1], 2)) #算法模型 def DBSCAN(D, e, Minpts): #初始化核心對(duì)象集合T,聚類(lèi)個(gè)數(shù)k,聚類(lèi)集合C, 未訪問(wèn)集合P, T = set(); k = 0; C = []; P = set(D) for d in D: if len([ i for i in D if dist(d, i) <= e]) >= Minpts: T.add(d) #開(kāi)始聚類(lèi) while len(T): P_old = P o = list(T)[np.random.randint(0, len(T))] P = P - set(o) Q = []; Q.append(o) while len(Q): q = Q[0] Nq = [i for i in D if dist(q, i) <= e] if len(Nq) >= Minpts: S = P & set(Nq) Q += (list(S)) P = P - S Q.remove(q) k += 1 Ck = list(P_old - P) T = T - set(Ck) C.append(Ck) return C #畫(huà)圖 def draw(C): colValue = ['r', 'y', 'g', 'b', 'c', 'k', 'm'] for i in range(len(C)): coo_X = [] #x坐標(biāo)列表 coo_Y = [] #y坐標(biāo)列表 for j in range(len(C[i])): coo_X.append(C[i][j][0]) coo_Y.append(C[i][j][1]) pl.scatter(coo_X, coo_Y, marker='x', color=colValue[i%len(colValue)], label=i) pl.legend(loc='upper right') pl.show() C = DBSCAN(dataset, 0.11, 5) draw(C)