正在打开模型库
正在打开模型库
按密度连成簇,能识别噪声,不必预先指定类数。
密的地方是一类,孤零零的点先当噪声。
你怀疑数据里有异常点,或不想拍脑袋定 K 时用。
Python 代码
import numpy as np
X = np.array([[0, 0], [0.1, 0.1], [0.2, 0], [8, 8], [8.1, 8.2], [20, 0]])
eps, min_pts = 0.5, 2
labels = -np.ones(len(X), dtype=int)
cid = 0
for i, p in enumerate(X):
if labels[i] != -1:
continue
nbrs = np.where(((X - p) ** 2).sum(axis=1) <= eps ** 2)[0]
if len(nbrs) < min_pts:
continue
labels[nbrs] = cid
cid += 1
print(labels)