蓝色天空网mbsky.com · 知识 · 实践 · 创造自然语言处理 NLP · 本地阅读预览
教程 / AI / 智能开发 / 自然语言处理 NLP

命名实体识别(NER)

核对 NER 概念、应用场景、规则/统计/深度三类实现及精确率/召回率/F1 指标;精确核验 80/90/100 实体级 F1 = 16/19 (0.8421)、多词边界惩罚,并实测正则改进、BIO HMM-Viterbi 与上下文歧义消解。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

NER 核心概念与行业应用场景

命名实体识别(Named Entity Recognition,NER)从非结构化文本中定位具特定指称对象的专有名词(人名、地名、组织机构、时间、日期、货币等)并归入预定义类别,直观上相当于用不同颜色荧光笔为文档关键信息做高亮标注。

NER 是信息抽取与知识图谱的上游基石,覆盖新闻事件人物提取、搜索引擎语义理解、客服工单关键实体识别、医疗病历药物与疾病抽取、金融财经公司/股票监控、法律合同条款与参与方定位以及电商评论品牌和产品属性挖掘。

NER 技术实现路线与 BIO 序列标注实测

NER 技术路线按方法分为规则匹配、统计学习(如条件随机场 CRF、HMM)和深度学习(双向 LSTM、BERT 预训练序列标注),三类优劣见下表。针对来源 spaCy 英文示例句“Apple is looking at buying U.K. startup for $1 billion”,本机离线环境未安装 spaCy,本站实现了纯 Python BIO(Begin/Inside/Outside)标注体系的 HMM-Viterbi 序列标注器,在同句上精准解码出 [('Apple', 'ORG'), ('U.K.', 'GPE'), ('$1 billion', 'MONEY')],并在新句中完整保持多词实体边界 ('New York Times', 'ORG') 以及识别未登录金额 ('$3 billion', 'MONEY')。

实体级严格评估指标、挑战与实践练习核验

NER 采用实体跨度级严格匹配(起止边界与类别均完全一致才算正确)计算精确率 P = TP/预测总数、召回率 R = TP/真实总数及调和平均 F1 = 2PR/(P+R)。按来源 100 个真实实体、系统识别 90 个且命中 80 个核验:精确率 80/90 = 8/9 ≈ 0.8889(88.89%)、召回率 80/100 = 0.8000(80%)、未提前舍入的精确 F1 = 16/19 ≈ 0.8421(84.21%,来源四舍五入记为约 84%)。本站同时实测多词边界错误惩罚:若双实体句中将“New York Times”误截断为“New York”,严格口径下既产生 1 个假阳性(FP)又产生 1 个假阴性(FN),令 F1 直接由 1.0 跌至 0.5。

NER 三大典型挑战为实体边界切分(如“New York Times”整体与拆分)、实体歧义(如“Apple”指公司或水果)及医疗等垂直领域术语迁移,工程上综合运用上下文特征建模、领域预训练微调与规则+统计集成应对。本站对实践练习 2 与歧义消解完成离线实测:(1)来源正则在“会议定于12/15/2023举行,预算为$5000”准确提取日期 ['12/15/2023'] 与货币 ['$5000'],但在 ISO 日期 2023-12-15 上会因 \d{1,2} 前缀截断误匹配为 ['23-12-15'],改进后的联合正则完整提取 ['2023-12-15'] 与 ['$1 billion', '¥3,200'];(2)基于前后词与语境词袋的 DictVectorizer + LogisticRegression 分类器准确将财报语境下的“Apple”判为 ORG、将饮食语境下的“Apple”判为 FRUIT。练习 1 安装 spaCy 及 en_core_web_sm 模型留作外部工具待办。

NER 三类核心技术路线对比

方法类型描述优缺点
规则匹配基于正则表达式、触发词模板与领域专名词典抽取实体高精度且无需标注训练,但泛化差、覆盖率低且易受格式边界影响
统计学习采用 HMM、CRF 等概率图模型对 BIO/BIOES 词元序列联合解码能利用上下文转移约束与词形特征,但依赖手工特征工程与标注语料
深度学习基于 BiLSTM-CRF 或 BERT 预训练编码器实现端到端特征学习边界识别与歧义消解性能强,但需要较多标注数据与较高算力

运行正则日期/货币边界改进、BIO HMM-Viterbi 序列标注、实体级 F1 精确校验与上下文消歧实验

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对原始正则 ISO 截断缺陷与改进提取、BIO 解码 Apple/U.K./$1 billion 及多词 New York Times、80/90/100 精确 F1=0.8421 与边界错切惩罚 F1=0.5,以及 Apple 语境消歧。
运行正则日期/货币边界改进、BIO HMM-Viterbi 序列标注、实体级 F1 精确校验与上下文消歧实验

所需环境: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。

当前源码 SHA256:75e3c2ad9738ff21181088aacbe62b610c68ab75070b8ea6ca048bc4754be0ab

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载命名实体识别(NER)实验

所需环境: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。

ZIP SHA256:9a8d834b735ba73c4834ae16237b60ae9e26709f290792aab08fe7be339165d1

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在严格实体级 NER 评测中,把“New York Times”识别成“New York”会同时拉低精确率和召回率?

展开参考解答

严格跨度评测要求实体起止位置与类型完全吻合;输出错误边界“New York”既被计作 1 条错误预测(FP,拉低精确率),又因漏掉完整真实实体“New York Times”而被计作 1 条漏报(FN,拉低召回率)。

规范与官方依据