"""Independent offline NLP lab for Ch 08 (Named Entity Recognition): regex rules, BIO HMM-Viterbi NER, span P/R/F1, context disambiguation."""
import json
import math
import platform
import re
from collections import Counter, defaultdict
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
def extract_spans(tokens, bio_tags):
spans = []
start = None
etype = None
for idx, tag in enumerate(bio_tags):
if tag.startswith("B-"):
if etype is not None:
spans.append((" ".join(tokens[start:idx]), etype, start, idx))
start = idx
etype = tag[2:]
elif tag.startswith("I-") and etype == tag[2:]:
continue
else:
if etype is not None:
spans.append((" ".join(tokens[start:idx]), etype, start, idx))
start, etype = None, None
if etype is not None:
spans.append((" ".join(tokens[start:]), etype, start, len(tokens)))
return spans
def run_cases():
cases = []
# 1. Source CODE 3 regex NER + ISO date & scale-suffix currency boundary improvement
sample = "会议定于12/15/2023举行,预算为$5000"
src_dates = re.findall(r"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}", sample)
src_currencies = re.findall(r"\$\d+\.?\d*", sample)
extended = "2023-12-15 签署协议,收购 U.K. 初创公司出价 $1 billion 或 ¥3,200。"
src_dates_on_iso = re.findall(r"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}", extended)
improved_dates = re.findall(r"(?:\d{4}[/-]\d{1,2}[/-]\d{1,2}|\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", extended)
improved_money = re.findall(r"[\$¥€]\d[\d,]*(?:\.\d+)?(?:\s*(?:million|billion|万|亿))?", extended)
c1_ok = (
src_dates == ["12/15/2023"]
and src_currencies == ["$5000"]
and src_dates_on_iso == ["23-12-15"] # Demonstrates prefix truncation bug of \d{1,2} on 4-digit year!
and improved_dates == ["2023-12-15"]
and improved_money == ["$1 billion", "¥3,200"]
)
cases.append(dict(
name="rule_based_date_currency_ner",
inputs=dict(source_sample=sample, extended_sample=extended),
prerequisites="对比来源基础正则(仅支持月/日/年与简单美元)与改进正则(支持 ISO 年-月-日、千分位与数量级后缀)。",
action="分别在原始例句与扩展例句上执行匹配,检验 4 位年份截断缺陷与改进提取效果。",
expected=dict(source_sample_matched=True, iso_truncation_bug_observed=True, improved_extracts_all=True),
actual=dict(
source_sample_matched=(src_dates == ["12/15/2023"] and src_currencies == ["$5000"]),
iso_truncation_bug_observed=(src_dates_on_iso == ["23-12-15"]),
improved_extracts_all=(improved_dates == ["2023-12-15"] and improved_money == ["$1 billion", "¥3,200"]),
),
measurements=dict(
source_dates=src_dates,
source_currencies=src_currencies,
source_regex_on_iso=src_dates_on_iso,
improved_dates=improved_dates,
improved_money=improved_money,
),
passed=c1_ok,
))
# 2. BIO-tagged HMM + Viterbi sequence NER handling Apple/U.K./$1 billion & multi-token "New York Times"
train_bio = [
[("Apple", "B-ORG"), ("is", "O"), ("buying", "O"), ("U.K.", "B-GPE"), ("startup", "O"), ("for", "O"), ("$1", "B-MONEY"), ("billion", "I-MONEY")],
[("Google", "B-ORG"), ("is", "O"), ("looking", "O"), ("at", "O"), ("buying", "O"), ("London", "B-GPE"), ("lab", "O"), ("for", "O"), ("$2", "B-MONEY"), ("billion", "I-MONEY")],
[("Microsoft", "B-ORG"), ("acquired", "O"), ("New", "B-ORG"), ("York", "I-ORG"), ("Times", "I-ORG"), ("unit", "O"), ("for", "O"), ("$500", "B-MONEY"), ("million", "I-MONEY")],
[("New", "B-ORG"), ("York", "I-ORG"), ("Times", "I-ORG"), ("reported", "O"), ("Apple", "B-ORG"), ("expanded", "O"), ("in", "O"), ("U.K.", "B-GPE")],
[("Steve", "B-PER"), ("Jobs", "I-PER"), ("founded", "O"), ("Apple", "B-ORG"), ("in", "O"), ("California", "B-GPE")],
[("OpenAI", "B-ORG"), ("is", "O"), ("looking", "O"), ("at", "O"), ("hiring", "O"), ("in", "O"), ("Tokyo", "B-GPE")],
]
trans = defaultdict(Counter)
emit = defaultdict(Counter)
tag_cnt = Counter()
vocab = set()
for sent in train_bio:
prev = "<START>"
for w, t in sent:
trans[prev][t] += 1
emit[t][w] += 1
tag_cnt[t] += 1
vocab.add(w)
prev = t
tags = sorted(tag_cnt.keys())
v_n = len(vocab) + 1
def viterbi_ner(tokens):
dp, bp_list = [], []
for idx, w in enumerate(tokens):
cur, bp = {}, {}
for t in tags:
ep = (emit[t][w] + 0.1) / (tag_cnt[t] + 0.1 * v_n)
if w not in vocab:
if w.startswith("$") and t == "B-MONEY":
ep *= 20.0
elif w[0].isupper() and t.startswith("B-"):
ep *= 2.0
elif w.islower() and t == "O":
ep *= 3.0
if idx == 0:
tp = (trans["<START>"][t] + 0.1) / (len(train_bio) + 0.1 * len(tags))
cur[t] = math.log(tp) + math.log(ep)
bp[t] = "<START>"
else:
best_sc, best_p = -1e18, tags[0]
for pt in tags:
tp = (trans[pt][t] + 0.1) / (tag_cnt[pt] + 0.1 * len(tags))
sc = dp[-1][pt] + math.log(tp) + math.log(ep)
if sc > best_sc:
best_sc, best_p = sc, pt
cur[t] = best_sc
bp[t] = best_p
dp.append(cur)
bp_list.append(bp)
last = max(tags, key=lambda t: dp[-1][t])
seq = [last]
for i in range(len(tokens) - 1, 0, -1):
seq.append(bp_list[i][seq[-1]])
return list(reversed(seq))
test1 = ["Apple", "is", "looking", "at", "buying", "U.K.", "startup", "for", "$1", "billion"]
tags1 = viterbi_ner(test1)
spans1 = [(txt, lab) for txt, lab, _, _ in extract_spans(test1, tags1)]
test2 = ["New", "York", "Times", "reported", "Microsoft", "invested", "$3", "billion"]
tags2 = viterbi_ner(test2)
spans2 = [(txt, lab) for txt, lab, _, _ in extract_spans(test2, tags2)]
c2_ok = (
spans1 == [("Apple", "ORG"), ("U.K.", "GPE"), ("$1 billion", "MONEY")]
and ("New York Times", "ORG") in spans2
and ("$3 billion", "MONEY") in spans2
)
cases.append(dict(
name="bio_hmm_viterbi_sequence_ner",
inputs=dict(sentence_1=" ".join(test1), sentence_2=" ".join(test2)),
prerequisites="在 BIO 标注语料上训练 HMM-Viterbi 序列标注器,覆盖 ORG/GPE/MONEY/PER 及多词边界。",
action="解码示例句“Apple is looking at buying U.K. startup for $1 billion”与含多词实体“New York Times”的新句。",
expected=dict(apple_uk_money_extracted=True, multi_token_nyt_intact=True, oov_money_recognized=True),
actual=dict(
apple_uk_money_extracted=(spans1 == [("Apple", "ORG"), ("U.K.", "GPE"), ("$1 billion", "MONEY")]),
multi_token_nyt_intact=(("New York Times", "ORG") in spans2),
oov_money_recognized=(("$3 billion", "MONEY") in spans2),
),
measurements=dict(spans_sentence_1=spans1, bio_tags_1=tags1, spans_sentence_2=spans2),
passed=c2_ok,
))
# 3. Exact NER Evaluation Arithmetic (TP=80, Pred=90, Gold=100) + strict span-boundary penalty
tp, pred_total, gold_total = 80, 90, 100
precision = tp / pred_total
recall = tp / gold_total
f1_exact = 2 * precision * recall / (precision + recall) # 16/19 = 0.842105...
gold_spans = {("New York Times", "ORG", 0, 3), ("Apple", "ORG", 4, 5)}
pred_spans_boundary_err = {("New York", "ORG", 0, 2), ("Apple", "ORG", 4, 5)}
strict_tp = len(gold_spans & pred_spans_boundary_err)
strict_fp = len(pred_spans_boundary_err - gold_spans)
strict_fn = len(gold_spans - pred_spans_boundary_err)
strict_f1 = 2 * strict_tp / (2 * strict_tp + strict_fp + strict_fn)
c3_ok = abs(precision - 8 / 9) < 1e-12 and abs(recall - 0.8) < 1e-12 and abs(f1_exact - 16 / 19) < 1e-12 and strict_fp == 1 and strict_fn == 1 and abs(strict_f1 - 0.5) < 1e-12
cases.append(dict(
name="entity_level_span_evaluation",
inputs=dict(tp=tp, pred_total=pred_total, gold_total=gold_total),
prerequisites="依据实体级严格跨度匹配口径核验 80/90/100 精确指标及多词实体边界截断误差惩罚。",
action="计算未四舍五入精确 P/R/F1,以及把“New York Times”截断为“New York”时的严格 TP/FP/FN。",
expected=dict(exact_p_8_9=True, exact_r_08=True, exact_f1_16_19=True, boundary_error_causes_fp_and_fn=True),
actual=dict(
exact_p_8_9=abs(precision - 8 / 9) < 1e-12,
exact_r_08=abs(recall - 0.8) < 1e-12,
exact_f1_16_19=abs(f1_exact - 16 / 19) < 1e-12,
boundary_error_causes_fp_and_fn=(strict_fp == 1 and strict_fn == 1 and abs(strict_f1 - 0.5) < 1e-12),
),
measurements=dict(
precision=round(precision, 4),
recall=round(recall, 4),
f1_exact=round(f1_exact, 4),
strict_boundary_tp=strict_tp,
strict_boundary_fp=strict_fp,
strict_boundary_fn=strict_fn,
strict_boundary_f1=round(strict_f1, 4),
),
passed=c3_ok,
))
# 4. Context-feature statistical disambiguation for "Apple" (ORG vs FRUIT)
ctx_train = [
(["Apple", "launched", "a", "new", "chip"], 0, "ORG"),
(["Apple", "reported", "record", "quarterly", "revenue"], 0, "ORG"),
(["investors", "bought", "Apple", "stock", "today"], 2, "ORG"),
(["engineers", "at", "Apple", "released", "software"], 2, "ORG"),
(["she", "ate", "a", "sweet", "Apple"], 4, "FRUIT"),
(["fresh", "red", "Apple", "juice", "tastes", "good"], 2, "FRUIT"),
(["slice", "the", "crisp", "Apple", "pie"], 3, "FRUIT"),
(["bought", "green", "Apple", "from", "fruit", "market"], 2, "FRUIT"),
]
def feat(tokens, idx):
prev_w = tokens[idx - 1].lower() if idx > 0 else "<BOS>"
next_w = tokens[idx + 1].lower() if idx + 1 < len(tokens) else "<EOS>"
ctx_bag = {f"ctx={w.lower()}": 1 for i, w in enumerate(tokens) if i != idx}
return {"word": tokens[idx], "prev": prev_w, "next": next_w, **ctx_bag}
x_ctx = [feat(toks, i) for toks, i, _ in ctx_train]
y_ctx = [lab for _, _, lab in ctx_train]
ctx_clf = Pipeline([("dv", DictVectorizer()), ("lr", LogisticRegression(max_iter=500))])
ctx_clf.fit(x_ctx, y_ctx)
test_org = feat(["Apple", "released", "quarterly", "software", "revenue"], 0)
test_fruit = feat(["ate", "fresh", "sweet", "Apple", "pie"], 3)
pred_org, pred_fruit = ctx_clf.predict([test_org, test_fruit]).tolist()
c4_ok = pred_org == "ORG" and pred_fruit == "FRUIT"
cases.append(dict(
name="context_disambiguation_apple",
inputs=dict(train_mentions=len(ctx_train), target_token="Apple"),
prerequisites="抽取目标词前词、后词与上下文词袋特征,训练 DictVectorizer + LogisticRegression 判别器。",
action="对同形词“Apple”在科技财报语境与水果饮食语境下分别预测实体类型。",
expected=dict(tech_context_org=True, food_context_fruit=True),
actual=dict(tech_context_org=(pred_org == "ORG"), food_context_fruit=(pred_fruit == "FRUIT")),
measurements=dict(pred_tech_context=pred_org, pred_food_context=pred_fruit),
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-named-entity-recognition-lab/explore-named-entity-recognition.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-named-entity-recognition.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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a553.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip