HDBSCAN:从密度层次到稳定簇
HDBSCAN
计算互达距离、并列层次事件、凝聚树与精确稳定性选簇。
hdbscan相邻的簇,不必在同一个距离尺度上存活
维护小车记录了走廊上的七个停靠位置:0、1、2、10、12、14、30 米。前三个位置挤得很近,中间三个较分散,最后一个离得很远。一个距离阈值有时就能还原这种结构;但如果密集组内部有间隙,稀疏组又靠近其他点,阈值就不容易选了。
HDBSCAN 先建立跨距离尺度的层次结构,再简化它,最后按持久程度选出互不重叠的分支。不同分支可以覆盖不同的尺度范围。结果仍取决于距离表示和参数,并不等于发现了一套客观正确的分类。Campello、Moulavi 和 Sander 在 2013 年论文中提出了这种层次结构与稳定性选簇方法。
两个参数回答不同问题。min_samples 决定评估局部拥挤程度时使用多大的邻域;min_cluster_size 决定多大的分支才够资格成为簇。调大一个,不能代替调大另一个。下面把两者分别写明,用一维精确计算观察每个决定。
从局部拥挤程度到分支选择
让稀疏区域的连接变贵
对于互不重复的点,核心距离定义为到第 m 个近邻样本的距离,计入点自身。m 为 1 时,核心距离为零;m 为 2 时,它是到最近另一个点的距离。对于不同点,只要任一端点的核心距离较大,互达距离就会抬高原本较短的几何距离:
因此,核心距离较大的点,其连接权重不会低于该核心距离。核心距离有多大,取决于近邻计数;m 为 1 时,这项调整就消失了。这里改变的是边权,并没有删除原始坐标。图中不设自环。计入自身的约定与 scikit-learn 1.7.2 一致;该文档明确指出,contrib hdbscan 包的 min_samples 不计自身。跨实现搬用参数前,先对齐实际的近邻数量。
用一棵树保留所有阈值下的连接
想象一个以互达距离为边权的完全图。在某个距离阈值下,只保留不超过阈值的边;其连通分量组成单链接层次结构。最小生成树,简称 MST,可以保留每个阈值下的这种划分。事实上,对任意两个不同顶点:
为什么?移除树路径上最重的边,会把树分成两部分。任何替代路径都要跨过这个切口。如果某条替代路径的所有跨界边都更轻,就能用其中一条替换被移除的边,得到更轻的生成树,与最小性矛盾。原树路径本身则给出另一方向的不等式。边权并列时,这个论证仍成立。
程序从反方向遍历层次:起初把所有点放在一起,再同时删除当前最大权重的全部边。记录的是删除刚完成后的划分,因此剩余边权严格小于本轮权重。一次并列事件可能产生三个乃至更多子分量。如果把这些边逐条处理成各有持续时间的分裂,层次就会受任意边顺序影响。MST 方法及其加速方案见 McInnes 和 Healy 原始论文的第 2.2、3 节。
这里与密度聚类的联系通过 DBSCAN* 建立;它去掉了普通 DBSCAN 的边界点分配规则。这不意味着把多个半径下普通 DBSCAN 的输出拼起来就行。我们的图划分仍显示孤立顶点,但它们不会成为合格的簇,因为 min_cluster_size 至少为二。
凝聚:丢几个点,不必换一个簇名
接下来沿逆距离方向前进,即 lambda = 1 / 距离。在一次分裂中,检查所得各分量。至少两个分量达到最小簇大小时,父簇结束,这些分量成为新簇。只有一个达到要求时,它延续父簇的身份,较小的部分脱落。一个都达不到时,父簇结束,没有子簇。这就区分了“失去几个点”和“真正分成几个组”。
对每个凝聚后的簇,记录它出生时的成员,以及每个成员离开这个簇时的逆距离。离开既可能是单点脱落,也可能是在真正分裂时转入子簇。其稳定性为:
簇结束后,成员计数视为零。一个很大却迅速消失的分支,得分可能不如持续更久的小分支。这是逆距离轴上的持久程度,不是“这个簇正确”的概率,也不是经过归一化的概率密度。项目官方算法指南用图示解释了凝聚与逐点计分。
选父簇,还是选它的后代
选中的簇不能重叠。凝聚分支之间要么嵌套、要么分离,因此可以选父簇,也可以选它的一组后代,却不能两者兼得。一个分支内部能取得的最高分为:
这个递推是精确的:只要不选父簇,各子分支就不共享点,可以独立选优后相加。从叶子向上归纳,便能证明它对这棵树和这个目标最优。它没有声称在坐标点的所有可能聚类中最优。本文规定得分相等时选父簇,并禁止选择人工根节点。最终得分是根节点各子分支最优选择之和。排除根节点对应常见的 allow_single_cluster=False 设置;若整棵树从未出现合格分裂,结果就是全部噪声。
看清每个停靠点贡献了多少
以下标准库程序实现完整的教学流程:核心距离、互达边、Kruskal 最小生成树、并列距离同时切分、凝聚、稳定性与 EOM 选择。它接受 2–20 个互不重复的整数或 Fraction 坐标;拒绝浮点数、布尔值、重复点和越界参数。两个参数都明确使用整数。程序不提供距离重缩放参数、其他选簇方法、根节点选择、成员概率或新点预测。
簇 ID 按出生顺序分配。最终数字标签按所选分支中最小的原始行号排序,因此重排行时标签名称可能改变。选中的非根簇给其出生时的成员打标签,其中也包括它延续期间后来脱落的点。如果一个点在任何被选簇出生前就已脱落,它保持噪声标签。可以用 exits 区分这两种情况。
from fractions import Fraction as F
def hdbscan_1d(values, min_samples=2, min_cluster_size=2):
"""Exact small HDBSCAN* pipeline; self-inclusive neighbors, no root selection."""
if not isinstance(values, (list, tuple)) or not 2 <= len(values) <= 20:
raise ValueError('values must contain 2 to 20 distinct rational points')
if any(type(x) not in (int, F) for x in values):
raise ValueError('coordinates must be integers or Fractions, not bool/float')
x = tuple(map(F, values))
n = len(x)
if len(set(x)) != n:
raise ValueError('duplicate coordinates are outside this example')
if type(min_samples) is not int or not 1 <= min_samples <= n:
raise ValueError('min_samples must be an integer from 1 to n')
if type(min_cluster_size) is not int or not 2 <= min_cluster_size <= n:
raise ValueError('min_cluster_size must be an integer from 2 to n')
core = tuple(sorted(abs(a - b) for b in x)[min_samples - 1] for a in x)
edges = sorted((max(core[i], core[j], abs(x[i] - x[j])), i, j)
for i in range(n) for j in range(i + 1, n))
parent = list(range(n))
rank = [0] * n
def find(i):
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
mst = []
for w, i, j in edges:
a, b = find(i), find(j)
if a == b:
continue
if rank[a] < rank[b]:
a, b = b, a
parent[b] = a
if rank[a] == rank[b]:
rank[a] += 1
mst.append((w, i, j))
if len(mst) == n - 1:
break
def components(cut):
# Immediately AFTER removing every edge with weight >= cut.
adjacency = [[] for _ in x]
for w, i, j in mst:
if w < cut:
adjacency[i].append(j)
adjacency[j].append(i)
seen, groups = set(), []
for i in range(n):
if i in seen:
continue
stack, group = [i], []
seen.add(i)
while stack:
v = stack.pop()
group.append(v)
for u in adjacency[v]:
if u not in seen:
seen.add(u)
stack.append(u)
groups.append(tuple(sorted(group)))
return tuple(groups)
levels = tuple((w, components(w))
for w in sorted({e[0] for e in mst}, reverse=True))
clusters = []
def born(members, birth):
cid = len(clusters)
clusters.append(dict(members=members, birth=birth, exits=[], children=[]))
return cid
born(tuple(range(n)), F(0))
active = {0: tuple(range(n))}
for cut, groups in levels:
lam = 1 / cut
owner = {i: j for j, g in enumerate(groups) for i in g}
updated = {}
for cid, current in active.items():
parts = [groups[j] for j in sorted({owner[i] for i in current})]
large = [g for g in parts if len(g) >= min_cluster_size]
if len(large) == 1:
survivor = large[0]
keep = set(survivor)
clusters[cid]['exits'].extend((i, lam) for i in current if i not in keep)
updated[cid] = survivor
else:
# A real split, or no surviving child: the parent ends.
clusters[cid]['exits'].extend((i, lam) for i in current)
for g in large:
child = born(g, lam)
clusters[cid]['children'].append(child)
updated[child] = g
active = updated
assert not active
for c in clusters:
c['exits'] = tuple(sorted(c['exits']))
c['children'] = tuple(c['children'])
assert tuple(i for i, _ in c['exits']) == c['members']
c['stability'] = sum((lam - c['birth'] for _, lam in c['exits']), F(0))
def best(cid):
c = clusters[cid]
choices = [best(j) for j in c['children']]
total = sum((score for score, _ in choices), F(0))
if c['stability'] >= total:
return c['stability'], (cid,)
return total, tuple(j for _, ids in choices for j in ids)
selected = tuple(sorted((j for child in clusters[0]['children']
for j in best(child)[1]),
key=lambda j: min(clusters[j]['members'])))
labels = [-1] * n
for label, cid in enumerate(selected):
for i in clusters[cid]['members']:
assert labels[i] == -1
labels[i] = label
return dict(points=x, core=core, mst=tuple(mst), levels=levels,
clusters=tuple(clusters), selected=selected, labels=tuple(labels),
score=sum((clusters[j]['stability'] for j in selected), F(0)))
if __name__ == '__main__':
model = hdbscan_1d([0, 1, 2, 10, 12, 14, 30], 2, 3)
print('core:', ', '.join(map(str, model['core'])))
print('cut distances:', ', '.join(str(w) for w, _ in model['levels']))
for cid, c in enumerate(model['clusters']):
print('cluster', cid, 'members', c['members'], 'birth', c['birth'],
'stability', c['stability'])
print('selected:', model['selected'], 'labels:', model['labels'],
'score:', model['score'])
print('tied chain:', hdbscan_1d([0, 1, 2, 3], 1, 2)['labels'])
core: 1, 1, 1, 2, 2, 2, 16
cut distances: 16, 8, 2, 1
cluster 0 members (0, 1, 2, 3, 4, 5, 6) birth 0 stability 13/16
cluster 1 members (0, 1, 2) birth 1/8 stability 21/8
cluster 2 members (3, 4, 5) birth 1/8 stability 9/8
selected: (1, 2) labels: (0, 0, 0, 1, 1, 1, -1) score: 15/4
tied chain: (-1, -1, -1, -1)
在距离 16 处,位置 30 脱落,其余六点继续使用根簇的身份。在距离 8 处,这六点分成两个合格组;两者都在逆距离 1/8 出生。第一组的三个点在 1 处离开,第二组的三个点在 1/2 处离开,所以得分分别是 21/8 和 9/8,总分为 15/4。选簇步骤没有接收一个统一的全局切割阈值。
| 分支 | 出生时成员,以行号表示 | 各点离开时刻 | 稳定性 | 是否选中 |
|---|---|---|---|---|
| 0,根 | 0–6 | 行 6 在 1/16;行 0–5 在 1/8 | 13/16 | 否 |
| 1 | 0、1、2 | 全部在 1 | 21/8 | 是 |
| 2 | 3、4、5 | 全部在 1/2 | 9/8 | 是 |
等间距四点链的三条 MST 边权都为一。一起删除后,只剩四个单点。没有非根簇达到大小二,四个标签因此都是 −1。这个例子能抓出一种错误:把并列距离处理成了不存在的分支。
设点数为 n,完全边表、保存的层次划分和每簇逐点记录给出如下运算界:
对完全边表以及每行距离排序,不超过这个时间界。切割层数至多 n − 1;每轮树遍历是线性的,附加排序每层至多 n log n。凝聚每层处理的当前成员总数至多 n;其中的小集合存的是整数分量 ID,而不是反复散列整个分量。EOM 对每个凝聚节点访问一次,返回 ID 列表的累计复制量至多为平方量级。这里按有理数运算单位成本计;分子分母很大时,还须计入位运算成本。点数上限是为了便于检查,不代表生产库的渐近性能。
对哪些选择稳定?
距离度量与特征尺度决定了邻域。走廊坐标容易解释;把图像嵌入、时间戳、金额混在一起则没那么简单。在不合适的几何表示里,一个稳定分支仍可能是糟糕的分组。噪声表示“在当前设置下未分配”,并不等于确认故障或异常。某个业务上很重要的小组,也可能因为人数不足而消失。
修改 min_samples,会在建层次之前改变互达距离。只修改 min_cluster_size,则改变同一层次上的凝聚和选择。EOM 可能偏爱一个宽泛父簇,而不是几个更细的子簇;只选叶节点是另一个目标。需要细分时,应结合树和业务实例检查这种差别。
本例要求坐标互不重复,且合格簇至少含两个点,从而避开零分裂距离。一般情形下,重复点可能组成一个达到最小大小的零距离分量,导致逆距离无穷,稳定性也可能无穷。实现必须说明如何表示和比较这些量;悄悄换成一个大常数,会改变目标。本文是明确拒绝这种输入。相等的正距离仍受支持,并且同时处理;这是写明的约定,不保证与每个库的二叉链接并列行为一致。
平移不会改变本例。统一乘一个正比例因子,会改变距离单位,并让得分按倒数缩放:
因此,本例在统一尺度变换下选出的分支不变。多维问题若分别缩放不同特征,则没有这个保证。持久程度以及这项有限计算,都不能证明任意分布、任意参数下的统计一致性。
追踪分支,不只看最终标签
-
对位置 0、2、10,计算计入自身的
min_samples分别为 1、2、3 时的核心距离。只使用一个其他近邻对应哪个值?答案: 三个向量分别为 (0, 0, 0)、(2, 2, 8)、(10, 8, 10)。一个其他近邻对应计入自身时的值 2。这就是不能把不同约定下的
min_samples原样照搬的原因。 -
解释走廊例中根簇为何得到 13/16。为什么不是七乘 1/8?
答案: 六个点留到 1/8,最后一点在 1/16 离开;总贡献为六乘 1/8 再加 1/16,等于 13/16。七乘 1/8 会把孤立点离开后的时间也算进去。
-
某个合格分支稳定性为 4/3,两个叶子子簇的稳定性各为 2/3。程序会选谁?若全部坐标乘三,这个决定会改变吗?
答案: 得分相等时偏向父簇,因此选父簇。统一缩放让这三个得分都除以三,等式与选择不变。数据 (0, 1, 5/2, 7/2, 13/2, 15/2),两个参数均为二时,就含有这样的分支;不必使用任意小量打破得分并列。
-
对 (0, 2, 3, 5, 20, 21) 运行程序,两个参数都取二。第一个被选簇包含行 0–3;其中行 0、3 在 1/2 离开,行 1、2 在 1 离开。前面提到的两个较早离开的点,应改标噪声吗?若把七点走廊例的
min_cluster_size改为七,又会怎样?答案: 不应改标。它们从该被选簇出生起就是成员;提前离开会减少稳定性,却不会取消它们对这个被选分支的最终归属。最小大小为七时,走廊根簇从未产生合格子簇;又因禁止选择根节点,七点全部成为噪声。这两种结果都不能证明观测中没有有用结构。
层次、目标与更快的计算
2013 年 HDBSCAN 论文把简化后的密度层次与明确的稳定性选择问题连接起来。由此可以分清两件事:层次描述哪些组可以相互嵌套,选择准则决定最终报告其中哪些组。
McInnes 和 Healy 的 2017 年论文联系了统计簇树、DBSCAN* 与拓扑解释,再用空间树和改进的 Borůvka 方法加速计算。可将它的计算视角与官方算法讲解对照阅读:前者解释数学联系与工程问题,后者便于理解点的脱落和分支选择。更快的几何搜索依赖数据与表示,并不会让本文的完全图程序自动变成近线性算法。
固定版本 scikit-learn API列出了 EOM 与叶选择、根节点资格、近邻计入自身等实际约定。作为对照,可从 DBSCAN了解单一半径,从层次聚类了解链接准则。它们都在回答“什么样的连接应该把一个簇维系起来”;HDBSCAN 在此基础上加入了经过密度调整的连接,以及按持久程度进行的分支选择。
先判断,再看解释
凝聚过程中,一个簇丢失了小分量,只剩一个子分量达到最小大小,会怎样?
学习目标
- 计算计入自身的核心距离,解释 MST 在不同阈值下保留了什么。
- 区分点脱落、真正簇分裂和距离并列事件。
- 推导逐点稳定性,证明互不重叠分支选择的最优性。
先修与延伸
查看知识关联图 →参考文献
- Density-Based Clustering Based on Hierarchical Density Estimates
Ricardo J. G. B. Campello; Davoud Moulavi; Joerg Sander · 2013 - Accelerated Hierarchical Density Clustering
Leland McInnes; John Healy · 2017 - How HDBSCAN Works — hdbscan documentation
hdbscan developers - HDBSCAN — scikit-learn 1.7
scikit-learn developers
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- 6 项测试通过。10 个针对性模型用独立完全图布尔连通性与分量时间区间的商结构核对核心距离、每个返回的层次划分、全部簇出生/退出时刻及稳定性。枚举所有非根互不重叠簇子集核对全局选择得分。参照不使用 MST 或正文的活跃簇更新,并按区间面积计算稳定性。
- 核查父簇胜出、子簇胜出、精确得分并列、脱落后身份延续、三种行序下的等距链、自计数 1/2/3、全噪声、仿射尺度/反射与行重排、非法范围/类型/重复点及输入保留。主程序实际得分为 21/8 与 9/8,总分 15/4,一个噪声点,并给出全噪声等距链反例。
- 原创完整双语、相同可运行 Python 与七行实际输出、6 显示式、6 锚点、4 已答练习。严格 MDX/KaTeX 与实际 React HTML 通过,6 个数学注解对应。按 Humanizer 复读;仅 AI 作者检查,written 待独立审校。仅草稿,未修改仓库或运行生产聚类库。
- 最终 6 项作者测试通过。独立核对 8 份完整报告:以 m 记录子集最大距离的最小值求核心距离,按相同全序边权用 Prim 扩展 MST(35 边),以一维合格点排序扫描核对 20 个层次划分;扫描依赖核心距离资格与相邻坐标间隙,不遍历图或使用布尔/Floyd 闭包。递归原始层次经剪除小枝、收缩最大单子链后,核对 26 个凝聚簇、出生次序/ID、子节点、每点退出与稳定性。
- 用通用精确线性规划顶点参照检查互不重叠选择问题,不运行 EOM 递推或枚举反链子集;共 548 个活跃基、104 个可行顶点。第二线性目标在分数相等时优先祖先,核对所选 ID、标签与总分,覆盖选中祖先保留后来脱落点、父子胜出、等距全噪声链及根排除。
- 完整复读双语、代码、公式、4 题答案、参数/输入限制与复杂度。独立重跑严格 MDX/KaTeX/React HTML:每语 6 对应显示式及实际 MathML 注解、6 标准锚点、4 答案通过。ID 与条件表述修正后,全部最终五 SHA 一致;在声明范围内未发现剩余数学或实现缺陷。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- Density-Based Clustering Based on Hierarchical Density Estimates · Actually read the Springer chapter landing page: authors, PAKDD 2013, pages 160–172 and abstract lines 38–40 describing the hierarchy, simplification and stability optimization. Year precision only: the inspected publisher page does not give a month or day. Full PDF redirects to the subscription page; no full-text reading claimed. The 2015 CORE PDF could not be fetched (web errors and shell DNS failure); it is not counted as a read mathematical source.
- Accelerated Hierarchical Density Clustering · Actually read the 32-page arXiv PDF, v2 footer dated 23 May 2017 and title dated 25 May 2017. Read sections 2.1–2.2 (printed pages 4–9) on cluster trees, condensation, DBSCAN*, per-point stability and disjoint-branch optimization; sections 3.2–3.3 passages on MST construction and Boruvka (printed pages 13, 16 and 19–20). The extracted page-8 formula has d(Xj,Xj) in the off-diagonal maximum; the implementation uses d(Xi,Xj), independently derived and consistent with Algorithm 6 on printed page 20 and the official guide. The article uses >= minimum size explicitly, rather than reproducing the paper’s uneven more-than wording. No claimed visual PDF inspection, paper code reuse, acceleration implementation or universal near-linear bound.
- How HDBSCAN Works — hdbscan documentation · Actually opened the official algorithm page, heading rendered hdbscan 0.8.1 documentation. Read lines 38–127: five pipeline stages, kth other neighbor convention, mutual reachability, MST threshold connectivity, one-child continuation, point exit levels, sum stability and bottom-up parent-versus-children selection. This is an accessed documentation snapshot, not a pinned source revision; no figures or code copied.
- HDBSCAN — scikit-learn 1.7 · Actually opened the fixed /1.7 API rendered 1.7.2. Read parameters lines 631–681, noise and membership-strength attributes 701–720, self-inclusive versus contrib offset note 759–760, and DBSCAN* versus border-point assignment 796–802. Example follows self inclusion and root exclusion but uses exact rational one-dimensional inputs and explicit simultaneous positive-distance ties; no sklearn/contrib execution or full API output equivalence claimed.
- Density-Based Clustering Based on Hierarchical Density Estimates · Independently opened Springer landing page: authors, PAKDD 2013, pages 160–172 and abstract lines 38–40 on simplified hierarchy, stability and disjoint flat selection. Full chapter was not read; no precise month/day or performance replication asserted.
- Accelerated Hierarchical Density Clustering · Independently opened the 32-page arXiv v2 PDF. Read §2.2 printed pages 8–9: DBSCAN* removes borders, mutual reachability, point fallout, condensed identities and disjoint stability objective; also §3.2–3.3 passages on MST, spatial trees, Boruvka and Algorithm 6 at printed page 20. The extracted off-diagonal formula repeats Xj; Algorithm 6 and the official guide use distinct endpoints. No reproduction of theoretical consistency results, figures or acceleration; no visual PDF inspection claimed.
- How HDBSCAN Works — hdbscan documentation · Independently opened official latest walkthrough, rendered hdbscan 0.8.1. Read lines 38–58, 78–104 and 112–127: stages, kth other-neighbor convention, mutual reachability, MST, one-child continuation, point exits and stability selection. Mutable documentation snapshot, not a pinned release; no figures or library code reused.
- HDBSCAN — scikit-learn 1.7 · Independently read fixed 1.7 API displayed as 1.7.2, lines 631–681, 701–720 and 759–760: min cluster size, EOM/leaf, root eligibility, label/member-strength distinctions and self-inclusive count offset. The exact example’s simultaneous positive ties and duplicate rejection are explicit teaching conventions, not a full library-equivalence claim.
相关主题