关系抽取与知识图谱 本节摘要:NER 找到了实体,实体链接把它们锚定,关系抽取找出它们之间的边——一个知识图谱就是节点、边及其出处的总和。分析师读「蒂姆·库克 2011 年成为苹果 CEO」,这里有四条事实。关系抽取把自由文本变成结构化三元组 ,跨语料聚合就成了知识图谱,再加上查询就成了 RAG、分析、合规审计的推理基底。2026 的问题是:LLM 抽关系抽得太起劲,会幻觉出源文本不支撑的三元组,没有出处就分不清真假,答案是 AEVS 式的「锚定-抽取-验证-补全」流水线。
本节摘要:NER 找到了实体,实体链接把它们锚定,关系抽取找出它们之间的边——一个知识图谱就是节点、边及其出处的总和。分析师读「蒂姆·库克 2011 年成为苹果 CEO」,这里有四条事实。关系抽取把自由文本变成结构化三元组
(主语, 关系, 宾语),跨语料聚合就成了知识图谱,再加上查询就成了 RAG、分析、合规审计的推理基底。2026 的问题是:LLM 抽关系抽得太起劲,会幻觉出源文本不支撑的三元组,没有出处就分不清真假,答案是 AEVS 式的「锚定-抽取-验证-补全」流水线。本节讲透三种抽取法(规则/Hearst 模式、监督分类器、生成式 LLM)、闭环本体的取舍,以及 REBEL 这类 seq2seq 抽取器如何文本进、三元组出;然后用 AEVS 把每条三元组按字符 span 锚回原文、拒掉一切无支撑的,再做规范化和时间限定,最终搭出可查询的小图,并指出共指前置、实体规范化、时间错误等生产陷阱。
对应原课程:Phase 5 · Lesson 26 ·
relation-extraction-kg(原英文phases/05-nlp-foundations-to-advanced/26-relation-extraction-kg/docs/en.md)。前置依赖:第 06 节(NER)、第 25 节(实体链接)。
阅读完本节,你应当能够:
(主语, 关系, 宾语),并区分闭环本体与开放 IE。分析师读:「Tim Cook became CEO of Apple in 2011.」四条事实:
(Tim Cook, role, CEO)(Tim Cook, employer, Apple)(Tim Cook, start_date, 2011)(Apple, type, Organization)关系抽取(RE) 把自由文本变成结构化三元组 (主语, 关系, 宾语)。跨语料聚合,你就有一个知识图谱;聚合加查询,你就有 RAG、分析、合规审计的推理基底。
2026 的问题:LLM 抽关系抽得太起劲,会幻觉出源文本不支撑的三元组。没有出处,你分不清真实三元组与貌似合理的虚构。2026 的答案是 AEVS 式「锚定-验证」流水线。
三元组形式:(主语实体, 关系类型, 宾语实体)。关系来自闭环本体(Wikidata 属性、FIBO、UMLS)或开放集合(OpenIE 式,什么都可以)。
三种抽取法:
(Y, isA, X)。加手写正则。脆、精确、可解释。AEVS(锚定-抽取-验证-补全, 2026) 当前的幻觉缓解框架:
幻觉骤降。算力更高,但可审计。
💡 开 vs 闭的取舍:闭环本体(如 Wikidata 的一万一+属性)可预测、可查询、难造;Open IE 任何动词短语都能当关系,召回高、精度低、查询乱。生产 KG 常两者混用:开放 IE 做发现,再规范化到闭环本体后并入主图。
PATTERNS = [ (r"(?P<s>[A-Z]\w+) (?:is|was) (?:a|an|the) (?P<o>[A-Z]?\w+)", "isA"), (r"(?P<s>[A-Z]\w+) (?:is|was) born in (?P<o>\w+)", "bornIn"), (r"(?P<s>[A-Z]\w+) works? (?:at|for) (?P<o>[A-Z]\w+)", "worksAt"), (r"(?P<s>[A-Z]\w+) founded (?P<o>[A-Z]\w+)", "founded"), ]
见 code/main.py 的完整玩具抽取器。Hearst 模式至今在领域专用流水线里发布,因为它可调试。
from transformers import AutoTokenizer, AutoModelForSequenceClassification tok = AutoTokenizer.from_pretrained("Babelscape/rebel-large") model = AutoModelForSequenceClassification.from_pretrained("Babelscape/rebel-large") text = "Tim Cook was born in Alabama. He later became CEO of Apple." encoded = tok(text, return_tensors="pt", truncation=True) output = model.generate(**encoded, max_length=200) triples = tok.batch_decode(output, skip_special_tokens=False)
REBEL 是 seq2seq 关系抽取器:文本进、三元组出,已是 Wikidata 属性 id。在远程监督数据上微调。标准开源权重基线。
prompt = f"""Extract (subject, relation, object) triples from the text. For each triple, include the exact character span in the source text. Text: {text} Output JSON: [{{"subject": {{"text": "...", "span": [start, end]}}, "relation": "...", "object": {{"text": "...", "span": [start, end]}}}}, ...] Only include triples fully supported by the text. No inference beyond what is stated. """
把每个返回 span 对回源文本验证。text[start:end] != triple_entity 就拒。这是 AEVS「验证」步的最简形式。
RELATION_MAP = { "is the CEO of": "P169", # "chief executive officer" "was born in": "P19", # "place of birth" "founded": "P112", # "founded by"(主宾倒置) "works at": "P108", # "employer" } def canonicalize(relation): rel_low = relation.lower().strip() if rel_low in RELATION_MAP: return RELATION_MAP[rel_low] return None # 丢掉未映射的开放关系,或转人工复核
规范化常常占工程量的 60~80%。要为之留预算。
triples = extract(text) graph = {} for s, r, o in triples: graph.setdefault(s, []).append((r, o)) def neighbors(node, relation=None): return [(r, o) for r, o in graph.get(node, []) if relation is None or r == relation] print(neighbors("Tim Cook", relation="P108")) # -> [(P108, Apple)]
这是每个「KG 上的 RAG」系统的原子。用 RDF 三元组库(Blazegraph、Virtuoso)、属性图(Neo4j)或向量增强图库来扩展。
P580 起始、P582 结束)。2026 的栈:
| 情形 | 选 |
|---|---|
| 快速生产,通用领域 | REBEL 或 LlamaPred,配 Wikidata 规范化 |
| 领域专用(生医、法律) | SciREX 式领域微调 + 自定义本体 |
| LLM 提示式,需审计输出 | AEVS 流水线:锚定→抽取→验证→补全 |
| 高量新闻 IE | 模式 + 监督混合 |
| 从零建 KG | 开放 IE + 人工规范化遍 |
| 时间 KG | 带限定符抽取(起止时间、时点) |
💡 集成模式:NER → 共指 → 实体链接 → 关系抽取 → 本体映射 → 图载入。每一段都是潜在质量门。
保存为 outputs/skill-re-designer.md:
--- name: re-designer description: Design a relation extraction pipeline with provenance and canonicalization. version: 1.0.0 phase: 5 lesson: 26 tags: [nlp, relation-extraction, knowledge-graph] --- Given a corpus (domain, language, volume) and downstream use (KG-RAG, analytics, compliance), output: 1. Extractor. Pattern-based / supervised / LLM / AEVS hybrid. Reason tied to precision vs recall target. 2. Ontology. Closed property list (Wikidata / domain) or open IE with canonicalization pass. 3. Provenance. Every triple carries source char-span + doc id. Non-negotiable for audit. 4. Merge strategy. Canonical entity id + relation id + temporal qualifiers; dedup policy. 5. Evaluation. Precision / recall on 200 hand-labelled triples + hallucination-rate on LLM-extracted sample. Refuse any LLM-based RE pipeline without span verification (source provenance). Refuse open-IE output flowing into a production graph without canonicalization. Flag pipelines with no temporal qualifier on time-bounded relations (employer, spouse, position).
code/main.py 的模式抽取器,手检精确率。(s, r, o):关系来自闭环本体(Wikidata/UMLS/FIBO)或开放 IE。text[start:end] 必须等于三元组实体,否则拒。P580 起始、P582 结束,「库克是苹果 CEO」现在真 2005 假。下一节,我们从「抽取结构」转向「评判质量」——进入「LLM 评估框架」,看 RAGAS、DeepEval、Promptfoo、LLM-as-judge 如何系统化地度量生成系统的忠实度、相关性与有用性。