语义去重(余弦相似度)
更新时间:2026-07-29
简介
在同一聚类簇内基于余弦相似度做近重复剔除。与「GPU KMeans 聚类」串联:先聚 K 簇,同簇内两两 cosine 相似度 > threshold 视为近重复,贪心保留先出现者、剔除后来者。
功能描述
• 簇内比较:仅在相同 cluster_id 内两两比较,不跨簇,复杂度按簇规模控制
• 贪心保留:按下标顺序保留最先出现者,后来者与任一已保留向量超过阈值则剔除
• 未聚类保留:cluster_id < 0 或 embedding 为空的行不参与比较,直接保留
• 阈值可调:threshold 越接近 1 越严格(判重越少)
算子参数
输入
| 输入 | 含义 |
|---|---|
| embeddings | L2 归一化的语义向量,元素类型为 list |
| cluster_ids | int32 簇号,通常由「GPU KMeans 聚类」产出。 |
输出
| 输出 | 含义 |
|---|---|
| result | bool,True=保留,False=剔除。 |
参数
| 参数名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| threshold | float | 0.95 | cosine 相似度阈值,超过判为近重复 默认值:0.95 |
| fail_on_error | bool | False | 出错是否抛异常 默认值:False |
调用示例
Python
1from __future__ import annotations
2
3import os
4
5import daft
6from daft import col
7
8from daft.aihc.common.udf import aihc_udf
9from daft.aihc.functions.cluster.semantic_dedup_by_cosine import SemanticDedupByCosine
10
11if __name__ == "__main__":
12 if os.getenv("DAFT_RUNNER", "native") == "ray":
13 import ray
14 ray.init(dashboard_host="0.0.0.0", ignore_reinit_error=True)
15 daft.set_runner_ray()
16 daft.set_execution_config(min_cpu_per_task=0)
17
18 # emb:L2 归一化向量;cid:由 GPU KMeans 聚类产出的簇号
19 samples = {
20 "emb": [[1.0, 0.0, 0.0], [1.0, 0.01, 0.0], [0.0, 1.0, 0.0]],
21 "cid": [0, 0, 0],
22 }
23 ds = daft.from_pydict(samples)
24 ds = ds.with_column(
25 "keep",
26 aihc_udf(
27 SemanticDedupByCosine,
28 construct_args={"threshold": 0.95},
29 num_cpus=1,
30 concurrency=1,
31 batch_size=3,
32 )(col("emb"), col("cid")),
33 )
34 ds.show() # 期望 [True, False, True]:同簇近重复的后来者被剔除
评价此篇文章
