设计一个三层顺序标注器:默认→正则→CRF 的 NLTK 代码

解读

国内面试官抛出这道题,不是让你背API,而是考察三层递进思想:

  1. 默认标注器(Most-frequent-tag)作为兜底,保证零召回也能出结果;
  2. 正则标注器(RegexTagger)用人工规则快速解决高置信场景(日期、人名、货币);
  3. CRF标注器(CRFTagger)用序列级判别模型精修剩余歧义。
    三层顺序执行,后一层只处理前一层打上的“未登录”或“低置信”标签,既节省算力,又符合工业“规则+模型”的落地套路。
    面试官还会追问:如何回退、如何评测、如何增量更新,必须提前准备。

知识点

  1. SequentialBackoffTagger机制:NLTK内置的回退链基类,子类通过self.backoff调用下一层。
  2. CRFTagger:NLTK-contrib包中的nltk.tag.CRFTagger,底层封装CRF++,训练文件格式为字\t特征1\t特征2\t标签,特征模板可自定义。
  3. 特征模板设计:国内工业界常用“当前字+前后2字+部首+拼音首字母+词边界”五维特征,既防过拟合又兼顾中文稀疏性。
  4. 评测指标:中文分词与POS任务用精确率/召回率/F1,面试官会要求你现场跑nltk.metrics.scores,并解释为何宏平均比微平均更严格。
  5. 增量更新:CRF模型支持热插拔式重训,只需把新增句子追加到训练文件,重新train(),无需动前后两层,符合国内“日更”需求。

答案

# -*- coding: utf-8 -*-
"""
三层顺序标注器:Default → Regex → CRF
可直接在中文POS任务上运行,符合国内工业落地习惯
"""

import nltk, os, tempfile, subprocess
from nltk.tag import DefaultTagger, RegexpTagger, SequentialBackoffTagger
from nltk.metrics import accuracy
from nltk.corpus import sinica_treebank  # 中文语料

# 1. 默认标注器:最高频标签兜底
default_tagger = DefaultTagger('Nc')  # sinica里Nc(普通名词)占比最高

# 2. 正则标注器:高置信规则,优先命中
patterns = [
    (r'.*年$', 'Nd'),      # 1998年
    (r'.*月$', 'Nd'),      # 12月
    (r'.*日$', 'Nd'),      # 31日
    (r'.*元$', 'M'),       # 五百元
    (r'.*公司$', 'Nc'),    # 腾讯公司
    (r'.*先生$', 'Na'),    # 王先生
]
regex_tagger = RegexpTagger(patterns, backoff=default_tagger)

# 3. CRF标注器:精修剩余歧义
class CRFTaggerWrapper(SequentialBackoffTagger):
    def __init__(self, train_sents, backoff=None, model_file='crf_model'):
        super().__init__(backoff=backoff)
        self.model_file = model_file
        self._train_crf(train_sents)

    def _train_crf(self, sents):
        """生成CRF++训练文件并训练"""
        crf_train = []
        for sent in sents:
            for w, t in sent:
                # 五维特征:字、前2字、后2字、拼音首、部首(简化版)
                feats = self._feats(w, sent)
                crf_train.append('\t'.join(feats + [t]))
            crf_train.append('')  # 句子边界
        tmp = tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.crf', encoding='utf8')
        tmp.write('\n'.join(crf_train))
        tmp.close()
        # 调用CRF++,需本机已安装且可执行文件在PATH
        subprocess.run(['crf_learn', '-f', '3', '-c', '1.5', 'template', tmp.name, self.model_file],
                       check=True, stdout=subprocess.DEVNULL)
        os.unlink(tmp.name)

    def _feats(self, word, sent):
        idx = next(i for i, (w, _) in enumerate(sent) if w == word)
        pre2 = sent[idx-2][0] if idx >= 2 else '<BOS>'
        pre1 = sent[idx-1][0] if idx >= 1 else '<BOS>'
        nex1 = sent[idx+1][0] if idx < len(sent)-1 else '<EOS>'
        nex2 = sent[idx+2][0] if idx < len(sent)-2 else '<EOS>'
        py = word[0]  # 简化:首字代替拼音首
        bihua = str(len(word))  # 简化:字长代替部首
        return [word, pre2, pre1, nex1, nex2, py, bihua]

    def tag(self, tokens):
        # 先让回退链打一遍
        backoff_tags = [t for _, t in self.backoff.tag(tokens)]
        # 生成CRF测试格式
        test_lines = []
        for w, bt in zip(tokens, backoff_tags):
            feats = self._feats(w, list(zip(tokens, backoff_tags)))
            test_lines.append('\t'.join(feats))
        tmp = tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.crf', encoding='utf8')
        tmp.write('\n'.join(test_lines))
        tmp.close()
        # 解码
        res = subprocess.run(['crf_test', '-m', self.model_file, tmp.name],
                             capture_output=True, text=True, encoding='utf8')
        os.unlink(tmp.name)
        # 解析输出
        crf_tags = [line.split('\t')[-1] for line in res.stdout.strip().split('\n') if line]
        return list(zip(tokens, crf_tags))

# 组装三层链
train_sents = sinica_treebank.tagged_sents()[:3000]  # 取前3k句做演示
crf_tagger = CRFTaggerWrapper(train_sents, backoff=regex_tagger)

# 快速验证
test_sents = sinica_treebank.tagged_sents()[3000:3200]
test_tokens = [w for s in test_sents for w, _ in s]
gold_tags = [t for s in test_sents for _, t in s]
pred_tags = [t for _, t in crf_tagger.tag(test_tokens)]
print('三层链 Accuracy:', accuracy(gold_tags, pred_tags))

运行前请确保:

  • pip install nltk python-crfsuite(或本机已装CRF++可执行文件)
  • 首次执行会下载sinica_treebank,需外网或配置国内镜像

拓展思考

  1. 回退策略升级:可把CRF的置信度(CRF++输出概率)作为阈值,低于0.8自动回退到Regex,形成“置信度门控”而非死板顺序,面试官会点赞。
  2. 在线学习:国内业务要求“今天上线、明天修正”,可把用户点击行为转成伪标签,每晚增量crf_learn -m 旧模型 新数据 新模型,实现热更新。
  3. 多任务共享:三层链思想可无缝迁移到中文分词、命名实体、语义角色标注,只需把CRF输出层换成对应标签集,一套框架吃遍NLP基础任务。
  4. 性能优化:CRF解码耗时高,可用多进程+缓存(把已解码句子放到Redis),在QPS>500的搜索场景也能扛住。