关键参数:
Eps:邻域范围
Minpts:邻域密度
步骤:
1、遍历所有数据点,若已被标记,跳过,否则,则进行邻域查询
2、若该点的邻近点个数>Minpts,说明是核心点,生成新的簇并以此为中心进行扩张查询,否则,则将其标记为噪声点
import numpy as np
from collections import deque
def dbscan(data, Eps, MinPts):
#获取距离
def get_dist(data):
dist_matrix = np.linalg.norm(data[:,np.newaxis] - data, axis=2) #np.newaxis插入新的列,用来存储每个数据点与其它数据点的差值
return dist_matrix #axis=2,沿着第三个维度的方向求欧几里得距离,结果的第一维度代表第几个数据点,第二维度代表点与点的间距
#获取邻域
def region_quary(point_idx, dist, Eps):
neighbours = np.where(dist[point_idx] < Eps)[0] #获取索引
return neighbours #np.where返回一个元组,第一个为位置索引,第二个为符合条件的数组值
def expand_cluster(point_idx, neighbours, cluster_id, labels, dist):
labels[point_idx] = cluster_id
queue = deque(neighbours)
while queue: #只要队列不空
neighbours_idx = queue.popleft() #取出队头
if labels[neighbours_idx] == -1: #若该点在核