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