TensorFlow不提供开箱即用的NER流水线,推荐使用Hugging Face的TFBertForTokenClassification;需注意subword与原始token的label对齐,首个subword分配标签、其余设为-100,并用offset_mapping处理边界。

TensorFlow 本身不提供开箱即用的实体命名识别(NER)流水线,你需要自己构建模型或加载预训练模型;直接调用 tensorflow.keras.layers.BiLSTM 或 tf.keras.Model 搭建序列标注结构是可行路径,但更推荐用 Hugging Face 的 transformers 库加载 TFBertForTokenClassification ——它底层依赖 TensorFlow,且支持 fine-tuning 和推理。
为什么不用 tf.keras 自己从头写 CRF 层
CRF(条件随机场)层能提升 NER 标签序列一致性,但 TensorFlow 原生不带稳定可用的 CRF 实现;社区版 tfa.text.crf(来自 tensorflow-addons)存在梯度兼容问题,尤其在 TF 2.10+ 和 eager mode 下容易报 TypeError: Cannot convert a symbolic Tensor。除非你明确需要定制转移矩阵或复现某篇论文,否则绕过 CRF、用 softmax + 维特比后处理更稳妥。
实操建议:
- 优先用
transformers提供的TFBertForTokenClassification,它已内置 token-level 分类头,输出 shape 是(batch_size, seq_len, num_labels) - 若必须用纯 TF 实现,用
tf.keras.layers.Dense接 BiLSTM 输出,loss 选sparse_categorical_crossentropy,标签用整数编码(非 one-hot) - 避免在 model.compile() 中传入
tf.keras.losses.CategoricalCrossentropy(from_logits=True)—— 这会导致 logits 和 softmax 混用,引发 nan loss
如何正确对齐 subword 和原始 token 的 label
BERT 类模型会把词切分成 subword(如 "playing" → ["play", "##ing"]),但 NER 标签只标在原始 token 上,直接按 subword 分配 label 会导致错位。常见错误是把第一个 subword 标为实体起始(B-PER),其余标为 I-PER,却忽略后续 subword 对应原始 token 已结束。
实操建议:
- 用
tokenizer.convert_ids_to_tokens()检查 subword 切分结果,确认[CLS]和[SEP]占位符位置 - 对每个原始 token,用
tokenizer.encode_plus(..., return_offsets_mapping=True)获取其在原文中的字符区间,再映射到 subword 索引 - label 对齐时:仅给首个 subword 分配原始 token 的 label,其余 subword 统一设为
-100(PyTorch 风格 ignore_index,TF 中需在 loss 计算时 mask 掉)
加载 Hugging Face 模型并做 inference 的最小可行代码
以下代码片段可直接运行(需安装 transformers[tf-cpu] 和 tensorflow):
from transformers import TFBertForTokenClassification, AutoTokenizer
import tensorflow as tf
<p>model = TFBertForTokenClassification.from_pretrained("dslim/bert-base-NER")
tokenizer = AutoTokenizer.from_pretrained("dslim/bert-base-NER")</p><p>text = "Apple Inc. is based in Cupertino."
inputs = tokenizer(text, return_tensors="tf", padding=True, truncation=True)</p><p>outputs = model(inputs)
predictions = tf.argmax(outputs.logits, axis=-1)[0].numpy()</p><h1>将预测 ID 映射回 label 名</h1><p>labels = model.config.id2label
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
for token, pred_id in zip(tokens, predictions):
if token not in ["[CLS]", "[SEP]", "[PAD]"]:
print(f"{token} → {labels[pred_id]}")
</p>
注意:TFBertForTokenClassification 默认输出的是每个 subword 的 logits,不是原始句子 token 的;上面代码只是演示流程,实际部署需补全 offset 映射逻辑,否则 “Apple Inc.” 可能被拆成两个独立实体。
真正难的不是跑通 inference,而是 label 对齐和边界处理——尤其是中英文混合、缩写、标点粘连时,return_offsets_mapping 返回的 (start, end) 很容易漏掉空格或换行符,导致 token 切分偏移。这点在训练数据预处理阶段就该验证,别等到 eval 时发现 F1 掉点才回头查。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











