"""Independent offline NLP lab for Ch 09 (Relation Extraction): regex bug/fix, 2-sample OOV pitfall, entity-marked supervised RE, distant supervision & triple eval."""
import json
import platform
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC, LinearSVC
def run_cases():
cases = []
# 1. Source CODE 0 non-greedy regex bug (.+?) -> returns only '阿' vs fixed pattern -> '阿里巴巴'
text = "马云创立了阿里巴巴"
buggy_match = re.search(r"(.+?)创立了(.+?)", text)
buggy_groups = (buggy_match.group(1), buggy_match.group(2)) if buggy_match else None
fixed_patterns = [
("创始人", re.compile(r"([^,。!?]+)创立了([^,。!?]+)")),
("创始人", re.compile(r"([^,。!?]+)是([^,。!?]+)的创始人")),
("首都", re.compile(r"([^,。!?]+)是([^,。!?]+)的首都")),
]
def extract_rule_triple(sentence: str):
for rel, pat in fixed_patterns:
m = pat.search(sentence)
if m:
return (m.group(1).strip(), rel, m.group(2).strip())
return None
t1 = extract_rule_triple("马云创立了阿里巴巴")
t2 = extract_rule_triple("比尔盖茨是微软的创始人")
t3 = extract_rule_triple("北京是中国的首都")
c1_ok = (
buggy_groups == ("马云", "阿")
and t1 == ("马云", "创始人", "阿里巴巴")
and t2 == ("比尔盖茨", "创始人", "微软")
and t3 == ("北京", "首都", "中国")
)
cases.append(dict(
name="rule_regex_non_greedy_bug_and_fix",
inputs=dict(sample=text, buggy_pattern=r"(.+?)创立了(.+?)"),
prerequisites="直接复现来源非贪婪捕获组 r'(.+?)创立了(.+?)' 与修复后的标点边界正则规则集。",
action="验证来源正则仅捕获单字“阿”,而修复规则完整抽取三条中文 (头实体, 关系, 尾实体) 三元组。",
expected=dict(buggy_captures_single_char=True, fixed_extracts_three_triples=True),
actual=dict(
buggy_captures_single_char=(buggy_groups == ("马云", "阿")),
fixed_extracts_three_triples=(
t1 == ("马云", "创始人", "阿里巴巴")
and t2 == ("比尔盖茨", "创始人", "微软")
and t3 == ("北京", "首都", "中国")
),
),
measurements=dict(
buggy_groups=list(buggy_groups),
fixed_triples=[list(t1), list(t2), list(t3)],
),
passed=c1_ok,
))
# 2. Source CODE 3-6 pitfall: 2-sample unsegmented TfidfVectorizer + SVC -> test_vec is all zeros
src_data = [
{"text": "比尔盖茨是微软的创始人", "relations": [{"head": "比尔盖茨", "tail": "微软", "type": "创始人"}]},
{"text": "北京是中国的首都", "relations": [{"head": "北京", "tail": "中国", "type": "首都"}]},
]
src_vec = TfidfVectorizer()
x_src = src_vec.fit_transform([d["text"] for d in src_data])
y_src = [d["relations"][0]["type"] for d in src_data]
src_svc = SVC().fit(x_src, y_src)
test_text = "乔布斯创立了苹果公司"
test_vec = src_vec.transform([test_text])
src_pred = str(src_svc.predict(test_vec)[0])
c2_ok = x_src.shape == (2, 2) and int(test_vec.nnz) == 0
cases.append(dict(
name="source_two_sample_oov_pitfall",
inputs=dict(train_samples=2, test_text=test_text),
prerequisites="按来源代码原样用默认 TfidfVectorizer() 拟合 2 条未分词中文句并转换测试句。",
action="检查训练特征矩阵维度与测试句的非零特征数(nnz),确认未分词 2 样本场景下测试向量全零。",
expected=dict(train_matrix_2x2=True, test_vector_all_zero=True),
actual=dict(
train_matrix_2x2=(x_src.shape == (2, 2)),
test_vector_all_zero=(int(test_vec.nnz) == 0),
),
measurements=dict(
train_vocab=src_vec.get_feature_names_out().tolist(),
test_nnz=int(test_vec.nnz),
arbitrary_zero_vec_prediction=src_pred,
),
passed=c2_ok,
))
# 3. Entity-marked supervised relation classification (char+word n-grams + LinearSVC, leak-free train/test)
founder_sents = [
"<E1>马云</E1>创立了<E2>阿里巴巴</E2>", "<E1>比尔盖茨</E1>是<E2>微软</E2>的创始人",
"<E1>任正非</E1>创办了<E2>华为</E2>", "<E1>马化腾</E1>创立了<E2>腾讯</E2>",
"<E1>李彦宏</E1>是<E2>百度</E2>的创始人", "<E1>雷军</E1>创办了<E2>小米</E2>",
"<E1>张一鸣</E1>创立了<E2>字节跳动</E2>", "<E1>黄峥</E1>是<E2>拼多多</E2>的创始人",
"<E1>Google</E1> was founded by <E2>Larry Page</E2>", "<E1>Tesla</E1> was founded by <E2>Martin Eberhard</E2>",
"<E1>Amazon</E1> was founded by <E2>Jeff Bezos</E2>", "<E1>Meta</E1> was founded by <E2>Mark Zuckerberg</E2>",
]
capital_sents = [
"<E1>北京</E1>是<E2>中国</E2>的首都", "<E1>东京</E1>是<E2>日本</E2>的首都",
"<E1>巴黎</E1>是<E2>法国</E2>的首都", "<E1>伦敦</E1>是<E2>英国</E2>的首都",
"<E1>柏林</E1>是<E2>德国</E2>的首都", "<E1>罗马</E1>是<E2>意大利</E2>的首都",
"<E1>首尔</E1>是<E2>韩国</E2>的首都", "<E1>渥太华</E1>是<E2>加拿大</E2>的首都",
"<E1>Madrid</E1> is the capital of <E2>Spain</E2>", "<E1>Cairo</E1> is the capital of <E2>Egypt</E2>",
"<E1>Canberra</E1> is the capital of <E2>Australia</E2>", "<E1>Brasilia</E1> is the capital of <E2>Brazil</E2>",
]
located_sents = [
"<E1>阿里巴巴</E1>总部位于<E2>杭州</E2>", "<E1>腾讯</E1>总部位于<E2>深圳</E2>",
"<E1>百度</E1>总部坐落于<E2>北京</E2>", "<E1>字节跳动</E1>总部位于<E2>北京</E2>",
"<E1>华为</E1>总部坐落于<E2>深圳</E2>", "<E1>小米</E1>总部位于<E2>北京</E2>",
"<E1>网易</E1>总部位于<E2>杭州</E2>", "<E1>复旦大学</E1>坐落于<E2>上海</E2>",
"<E1>Apple</E1> headquarters is located in <E2>Cupertino</E2>", "<E1>CERN</E1> is located in <E2>Geneva</E2>",
"<E1>MIT</E1> is located in <E2>Cambridge</E2>", "<E1>Oxford</E1> is located in <E2>England</E2>",
]
def mask_entities(s: str) -> str:
s = re.sub(r"<E1>.*?</E1>", " ENT1 ", s)
s = re.sub(r"<E2>.*?</E2>", " ENT2 ", s)
return s
all_sents = founder_sents + capital_sents + located_sents
all_labels = ["founder"] * 12 + ["capital"] * 12 + ["located_in"] * 12
masked_sents = [mask_entities(s) for s in all_sents]
x_tr, x_te, y_tr, y_te = train_test_split(
masked_sents, all_labels, test_size=0.25, random_state=42, stratify=all_labels
)
re_pipe = Pipeline([
("tfidf", TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4))),
("clf", LinearSVC(random_state=42)),
])
re_pipe.fit(x_tr, y_tr)
y_pred = re_pipe.predict(x_te)
acc = float(accuracy_score(y_te, y_pred))
macro_f1 = float(f1_score(y_te, y_pred, average="macro"))
probes = [
mask_entities("<E1>乔布斯</E1>创立了<E2>苹果公司</E2>"),
mask_entities("<E1>Apple</E1> was founded by <E2>Steve Jobs</E2> in 1976."),
mask_entities("<E1>微软</E1>总部位于<E2>西雅图</E2>"),
]
probe_preds = re_pipe.predict(probes).tolist()
c3_ok = acc == 1.0 and macro_f1 == 1.0 and probe_preds == ["founder", "founder", "located_in"]
cases.append(dict(
name="entity_marked_supervised_re",
inputs=dict(total_samples=len(all_sents), train_samples=len(x_tr), test_samples=len(x_te), relations=3),
prerequisites="将实体替换为 ENT1/ENT2 槽位以防止模型死记实体名,先 75/25 分层划分再拟合 char_wb (2,4)-gram + LinearSVC。",
action="评估 9 条留出测试句准确率/宏平均 F1,并对乔布斯/Steve Jobs/微软三条新句预测关系。",
expected=dict(test_acc_1=True, macro_f1_1=True, probes_exact=True),
actual=dict(
test_acc_1=(acc == 1.0),
macro_f1_1=(macro_f1 == 1.0),
probes_exact=(probe_preds == ["founder", "founder", "located_in"]),
),
measurements=dict(
test_accuracy=round(acc, 4),
test_macro_f1=round(macro_f1, 4),
probe_predictions=probe_preds,
),
passed=c3_ok,
))
# 4. Distant supervision alignment & triple-level Precision/Recall/F1 evaluation
kb = {("马云", "阿里巴巴"): "创始人", ("北京", "中国"): "首都", ("比尔盖茨", "微软"): "创始人"}
unlabeled_corpus = [
"马云创立了阿里巴巴并担任董事局主席", # True positive alignment
"马云昨天访问了阿里巴巴杭州园区", # Distant-supervision noise (co-occurrence without founder relation!)
"北京是中国的首都也是文化中心", # True positive alignment
"比尔盖茨退休后仍关注微软技术生态", # Distant-supervision noise
]
auto_labeled = []
for sent in unlabeled_corpus:
for (h, t), rel in kb.items():
if h in sent and t in sent:
auto_labeled.append((sent, h, rel, t))
# Evaluate predicted triples against gold triples
gold_triples = {
("马云", "创始人", "阿里巴巴"),
("北京", "首都", "中国"),
("乔布斯", "创始人", "苹果公司"),
("任正非", "创始人", "华为"),
}
pred_triples = {
("马云", "创始人", "阿里巴巴"),
("北京", "首都", "中国"),
("乔布斯", "创始人", "苹果公司"),
("马云", "创始人", "华为"), # False positive
("微软", "首都", "北京"), # False positive
}
tp_n = len(gold_triples & pred_triples)
p_val = tp_n / len(pred_triples) # 3/5 = 0.6
r_val = tp_n / len(gold_triples) # 3/4 = 0.75
f1_val = 2 * p_val * r_val / (p_val + r_val) # 2/3 = 0.6667
c4_ok = len(auto_labeled) == 4 and abs(p_val - 0.6) < 1e-12 and abs(r_val - 0.75) < 1e-12 and abs(f1_val - 2 / 3) < 1e-12
cases.append(dict(
name="distant_supervision_and_triple_eval",
inputs=dict(kb_triples=len(kb), unlabeled_sentences=len(unlabeled_corpus)),
prerequisites="演示知识库回标未标注句子的远程监督机制(含实体共现误标噪声)及三元组级严格 P/R/F1 计算。",
action="统计远程监督自动对齐条数(4 条中含 2 条共现噪声),并核对 5 预测/4 真实/3 命中场景下的精确指标。",
expected=dict(auto_aligned_4=True, precision_06=True, recall_075=True, f1_two_thirds=True),
actual=dict(
auto_aligned_4=(len(auto_labeled) == 4),
precision_06=abs(p_val - 0.6) < 1e-12,
recall_075=abs(r_val - 0.75) < 1e-12,
f1_two_thirds=abs(f1_val - 2 / 3) < 1e-12,
),
measurements=dict(
distant_supervision_aligned=len(auto_labeled),
triple_tp=tp_n,
triple_precision=round(p_val, 4),
triple_recall=round(r_val, 4),
triple_f1=round(f1_val, 4),
),
passed=c4_ok,
))
print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/nlp-relation-extraction-lab/explore-relation-extraction.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-relation-extraction.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a557.zip