您好,登錄后才能下訂單哦!
本文實例講述了Python基于聚類算法實現(xiàn)密度聚類(DBSCAN)計算。分享給大家供大家參考,具體如下:
算法思想
基于密度的聚類算法從樣本密度的角度考察樣本之間的可連接性,并基于可連接樣本不斷擴展聚類簇得到最終結(jié)果。
幾個必要概念:
ε-鄰域:對于樣本集中的xj, 它的ε-鄰域為樣本集中與它距離小于ε的樣本所構(gòu)成的集合。
核心對象:若xj的ε-鄰域中至少包含MinPts個樣本,則xj為一個核心對象。
密度直達(dá):若xj位于xi的ε-鄰域中,且xi為核心對象,則xj由xi密度直達(dá)。
密度可達(dá):若樣本序列p1, p2, ……, pn。pi+1由pi密度直達(dá),則p1由pn密度可達(dá)。
大致思想如下:
1. 初始化核心對象集合T為空,遍歷一遍樣本集D中所有的樣本,計算每個樣本點的ε-鄰域中包含樣本的個數(shù),如果個數(shù)大于等于MinPts,則將該樣本點加入到核心對象集合中。初始化聚類簇數(shù)k = 0, 初始化未訪問樣本集和為P = D。
2. 當(dāng)T集合中存在樣本時執(zhí)行如下步驟:
Q = Q+S, P = P-S
3. 劃分為C= {C1, C2, ……, Ck}
Python代碼實現(xiàn)
#-*- coding:utf-8 -*- import math import numpy as np import pylab as pl #數(shù)據(jù)集:每三個是一組分別是西瓜的編號,密度,含糖量 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個樣本(密度,含糖量)的列表 a = data.split(',') dataset = [(float(a[i]), float(a[i+1])) for i in range(1, len(a)-1, 3)] #計算歐幾里得距離,a,b分別為兩個元組 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): #初始化核心對象集合T,聚類個數(shù)k,聚類集合C, 未訪問集合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) #開始聚類 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 #畫圖 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)
本機測試運行結(jié)果圖:
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學(xué)運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。