[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-taishan1994--pytorch_bert_bilstm_crf_ner":3,"tool-taishan1994--pytorch_bert_bilstm_crf_ner":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",158594,2,"2026-04-16T23:34:05",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":66,"readme_en":67,"readme_zh":68,"quickstart_zh":69,"use_case_zh":70,"hero_image_url":71,"owner_login":72,"owner_name":73,"owner_avatar_url":74,"owner_bio":75,"owner_company":76,"owner_location":77,"owner_email":76,"owner_twitter":76,"owner_website":78,"owner_url":79,"languages":80,"stars":93,"forks":94,"last_commit_at":95,"license":76,"difficulty_score":10,"env_os":96,"env_gpu":97,"env_ram":98,"env_deps":99,"category_tags":111,"github_topics":114,"view_count":32,"oss_zip_url":76,"oss_zip_packed_at":76,"status":17,"created_at":120,"updated_at":121,"faqs":122,"releases":160},8165,"taishan1994\u002Fpytorch_bert_bilstm_crf_ner","pytorch_bert_bilstm_crf_ner","基于pytorch的bert_bilstm_crf中文命名实体识别","pytorch_bert_bilstm_crf_ner 是一个基于 PyTorch 框架打造的中文命名实体识别（NER）开源项目。它旨在帮助开发者从非结构化的中文文本中精准提取关键信息，如人名、地名、机构名、职位等实体类别，有效解决了中文语境下实体边界模糊及标注复杂的难题。\n\n该工具特别适合自然语言处理领域的研究人员、算法工程师及需要构建文本分析应用的开发者使用。其核心架构灵活融合了预训练语言模型（如 BERT）、双向长短期记忆网络（BiLSTM）或迭代空洞卷积神经网络（IDCNN），并引入条件随机场（CRF）层来优化标签序列的全局一致性，从而显著提升识别准确率。\n\n除了基础的训练与推理功能，pytorch_bert_bilstm_crf_ner 还具备多项实用亮点：支持将模型转换为 ONNX 格式以加速 CPU 端的推理速度；提供知识蒸馏示例，便于在资源受限场景下部署轻量级模型；内置长文本自动切分与批量预测机制，并能通过 TensorBoard 可视化训练过程。项目配套了详细的数据预处理脚本和多数据集（如 CNER、Weibo、MSRA）适配指南，帮助用户快速上手并复现前沿效果。","# pytorch_bert_bilstm_crf_ner\n\n# 依赖\n```python\npython==3.6 (可选)\npytorch==1.6.0 (可选)\npytorch-crf==0.7.2\ntransformers==4.5.0\nnumpy==1.22.4\npackaging==21.3\n```\n\n****\n这里总结下步骤，以cner数据为例：\n```python\n先去hugging face下载相关文件到chinese-bert-wwwm-ext下。\n目录结构：\n--pytorch_bilstm_crf_ner\n--model_hub\n----chinese-bert-wwm-ext\n------vocab.txt\n------config.json\n------pytorch_model.bin\n\n1、原始数据放在data\u002Fcner\u002Fraw_data\u002F下，并新建mid_data和final_data两个文件夹。\n2、将raw_data下的数据处理成mid_data下的格式。其中：\n--labels.txt：实体类别\n[\"PRO\", \"ORG\", \"CONT\", \"RACE\", \"NAME\", \"EDU\", \"LOC\", \"TITLE\"]\n--nor_ent2id.json：BIOES格式的标签\n{\"O\": 0, \"B-PRO\": 1, \"I-PRO\": 2, \"E-PRO\": 3, \"S-PRO\": 4, \"B-ORG\": 5, \"I-ORG\": 6, \"E-ORG\": 7, \"S-ORG\": 8, \"B-CONT\": 9, \"I-CONT\": 10, \"E-CONT\": 11, \"S-CONT\": 12, \"B-RACE\": 13, \"I-RACE\": 14, \"E-RACE\": 15, \"S-RACE\": 16, \"B-NAME\": 17, \"I-NAME\": 18, \"E-NAME\": 19, \"S-NAME\": 20, \"B-EDU\": 21, \"I-EDU\": 22, \"E-EDU\": 23, \"S-EDU\": 24, \"B-LOC\": 25, \"I-LOC\": 26, \"E-LOC\": 27, \"S-LOC\": 28, \"B-TITLE\": 29, \"I-TITLE\": 30, \"E-TITLE\": 31, \"S-TITLE\": 32}\n--train.json\u002Fdev.json\u002Ftest.json：是一个列表，列表里面每个元素是：\n[\n  {\n    \"id\": 0,\n    \"text\": \"常建良，男，\",\n    \"labels\": [\n      [\n        \"T0\",\n        \"NAME\",  \n        0,\n        3,  # 后一位\n        \"常建良\"\n      ]\n    ]\n  },\n  ......\n]\n3、在preprocess.py里面修改数据集名称和设置文本最大长度，并按照其它数据一样添加一段代码。运行后得到final_data下的数据。\n4、运行指令进行训练、验证和测试：\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\# 默认为bert\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\# BIOES标签的数目\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\# 文本最大长度，和prepcoess.py里面保持一致\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\# 训练batch_size\n--train_epochs=3 \\# 训练epoch\n--eval_batch_size=32 \\# 验证batch_size\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\# 是否使用bilstm\n--use_idcnn=\"True\" \\# 是否使用idcnn。idcnn和bilstm只能选择一种\n--use_crf=\"True\" \\# 是否使用crf\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n运行的时候需要在命令行运行，且不要带上后面的注释。windows下运行需要将指令变成一行，即删除掉\"\\\\\"。\n\n****\n### 温馨提示\n\n- 新增了转换为onnx并进行推理，具体内容在convert_onnx下，```python convert_onnx.py```，只支持对单条数据的推理。在CPU下，原本推理时间：0.714256477355957s，转换后推理时间：0.4593505859375s。需要安装onnxruntime和onnx库。原本的pytorch-crf不能转换为onnx，这里使用了[here](https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fpytext\u002Fblob\u002Fmaster\u002Fpytext\u002Fmodels\u002Fcrf.py)。目前只测试了bert_crf模型，其余的可根据需要自行调整。\n\n#### 问题汇总\n- ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. \n\n解决方法：```pip install numpy==1.22.4```\n- packaging.version.InvalidVersion: Invalid version: '0.10.1,\u003C0.11'\n\n解决方法：```pip install packaging==21.3```\n\n#### 2023-05-12\n重新写了一个简洁版本的BERT-BILSTM-CRF，代码更简洁，更方便使用：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002FBERT-BILSTM-CRF\n\n#### 2023-03-17\n适配pytorch2.0版本，主要是加入torch.compile(model)。虽然程序已跑通，但可能还存在一些问题导致速度并没有提升。\n\n#### 2022-10-10\n\n补充知识蒸馏实例。在knowledge_distillation\u002Fkd.py里面是具体代码，该实例将bert_idcnn_crf_cner蒸馏到idcnn_crf_cner上。具体步骤：\n\n- 先训练一个教师模型：bert_idcnn_crf_cner。\n- 再训练一个学生模型：idcnn_crf_cner。\n- 然后修改kd.py里面参数文件的路径，并修改相关参数运行kd.py即可。\n\n在cner数据集上蒸馏之后的效果没有原来的好，可能是cner的数据量太少了。教师模型和学生模型之间的差异太小。\n\n\n#### 2022-09-23\n- 在predict.py里面新增batch_predict：若一条文本大于当前设置的文本最大长度，则对句子进行切分，切分后进行批量预测，在scripts\u002Fserver.py可使用merge_with_loc进行结果的合并。\n- 增加tensorboardX可视化损失函数变化过程。通过```--use_tensorboard==\"True\"```指定使用。命令行```tensorboard --logdir=.\u002Ftensorboard```查看结果。\n- 新增onenotes4.0数据，这里只提供训练数据，并提供转换数据process.py。\n\n#### 2022-08-18\n\n- 新增weibo和msra数据，具体运行实例这里不补充，可当练手用。\n\n- 将预测代码提取至predict.py里面，使用时需要注意以下几方面：\n\t- 修改args_path\n\t- 修改model_name\n\n#### 2022-09-15\n\n新增IDCNN模型，[IDCNN代码来源](https:\u002F\u002Fgithub.com\u002FcirclePi\u002FIDCNN-CRF-Pytorch\u002Fblob\u002Fmaster\u002FIDCNN-CRF\u002Fcnn.py)，使用单独的IDCNN_crf需要设置```model_name=\"idcnn\"```。另外，也可将其和bert相关模型结合使用，根据use_idcnn参数使用，另外bilstm和idcnn是不可同时使用：\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_idcnn=\"True\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n\n| 评价指标：F1        | 模型大小 | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| ------------------- | -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| idcnn_crf_cner      | 64.95M   | 0.76 | 0.86 | 1.00 | 0.97 | 0.97 | 0.95 | 0.80 | 0.87  | 0.8817 |\n| bert_idcnn_crf_cner | 393.25M  | 0.92 | 0.92 | 1.00 | 0.90 | 0.99 | 0.97 | 1.00 | 0.90  | 0.9232 |\n\n#### 2022-09-14\n\n新增单独的**bilstm_crf**和**crf**模型，使用的词汇表是根据自己选择的预训练模型的vocab.txt。使用bilstm_crf时需要设置```model_name=\"bilstm\"```，使用crf需要设置```model_name=\"crf\"```。需要注意bilstm默认使用crf，crf默认只使用其自己。运行：\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bilstm\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=20 \\\n--eval_batch_size=32 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"True\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n\n效果：针对于cner数据集\n\n| 评价指标：F1    | 模型大小 | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| --------------- | -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| bilstm_crf_cner | 65.45M   | 0.90 | 0.86 | 1.00 | 0.97 | 0.98 | 0.97 | 1.00 | 0.87  | 0.8853 |\n| crf_cner        | 62.00M   | 0.77 | 0.81 | 1.00 | 1.00 | 0.90 | 0.94 | 1.00 | 0.84  | 0.8453 |\n\n#### 2022-09-02\n\n- 补充将模型启动为服务代码，代码位于scripts目录下，针对于不同的数据集和模型，只需要修改开头的args的路径即可。\n\n\t在linux下使用：\n\n\t- .\u002Fstart_server.sh：启动服务\n\t- .\u002Fstop_server.sh：停止服务\n\t- .\u002Frestart_server.sh：停止服务并重新启动\n\n\t在windows下直接运行```python server.py```即可。\n\n\t最终可运行```python test_requests.py```来测试接口。\n\n- 新增页面展示，需要在scripts\u002Ftemplates\u002Fpredict.html里面修改ip地址。启动服务后输入：```http:\u002F\u002Fip地址:9277\u002F```，可以输入文本然后得到结果。\n\n#### 2022-08-19\n\n- 新增其它模型的训练结果，目录结构是：\n\n\t```\n\t——project\n\t————model_hub\n\t——————chinese-bert-wwm-ext\n\t————————vocab.txt\n\t————————pytorch_model.bin\n\t————————config.json\n\t——————其它模型路径\n\t————pytorch_bert_bilstm_crf_ner\n\t```\n\n- 需要修改的地方是：\n\n\t- --bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \n\t- --model_name=\"bert\"\n\t- 使用electra模型设置model_name=\"electra\"，使用albert模型设置model_name=\"albert\"，使用mengzi模型设置model_name=\"mengzi\"，其余的均可设置model_name=\"bert\"（或自己定义）\n\n主要参数：针对于cner数据集\n\n```\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=”False“ \\\n--use_crf=“True” \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n\n| 评价指标：F1                                                 | 模型大小 | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| ------------------------------------------------------------ | -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| [mengzi-bert-base](https:\u002F\u002Fhuggingface.co\u002FLangboat\u002Fmengzi-bert-base\u002Ftree\u002Fmain) | 196.28M  | 0.90 | 0.91 | 1.00 | 0.93 | 1.00 | 0.96 | 1.00 | 0.90  | 0.9154 |\n| [chinese-bert-wwm-ext](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-roberta-wwm-ext\u002Ftree\u002Fmain) | 392.51M  | 0.90 | 0.92 | 1.00 | 0.93 | 0.99 | 0.96 | 1.00 | 0.91  | 0.9148 |\n| [bert-base-chinese](https:\u002F\u002Fhuggingface.co\u002Fbert-base-chinese\u002Ftree\u002Fmain) | 392.51M  | 0.90 | 0.92 | 1.00 | 0.93 | 1.00 | 0.97 | 1.00 | 0.91  | 0.9233 |\n| [chinese-roberta-wwm-ext](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-roberta-wwm-ext\u002Ftree\u002Fmain) | 392.51M  | 0.90 | 0.92 | 1.00 | 0.93 | 0.99 | 0.97 | 1.00 | 0.90  | 0.9196 |\n| [chinese-macbert-base](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-macbert-base\u002Ftree\u002Fmain) | 392.52M  | 0.92 | 0.92 | 1.00 | 0.93 | 1.00 | 0.98 | 1.00 | 0.90  | 0.9203 |\n| [chinese-electra-180g-small-discriminator](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-electra-180g-small-discriminator\u002Ftree\u002Fmain) | 47.15M   | 0.74 | 0.88 | 0.99 | 0.12 | 0.97 | 0.81 | 0.00 | 0.87  | 0.8753 |\n| [chinese-electra-180g-base-discriminator](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-electra-180g-small-discriminator\u002Ftree\u002Fmain) | 390.17M  | 0.88 | 0.91 | 1.00 | 0.97 | 1.00 | 0.94 | 1.00 | 0.87  | 0.9012 |\n| [albert-base-chinese](https:\u002F\u002Fhuggingface.co\u002Fckiplab\u002Falbert-base-chinese\u002Ftree\u002Fmain) | 38.46M   | 0.00 | 0.68 | 0.95 | 0.00 | 0.62 | 0.53 | 0.00 | 0.71  | 0.6765 |\n\n\n# 补充观点抽取实例\n\n这里有点关系抽取的味道。我们要做的是抽取评论中的主体、评价及其情感。具体做法是转换为序列标注，主体标注为不同类别，评价标注为情感极性，最后识别出实体后再进行合并，具体步骤参考其它数据集。\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fgdcq\u002F\" \\\n--data_name=\"gdcq\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=65 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=70 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=64 \\\n--train_epochs=10 \\\n--eval_batch_size=64 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_idcnn=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n\nprecision:0.8301 recall:0.8723 micro_f1:0.8507\n            precision    recall  f1-score   support\n\n      功效       0.84      0.84      0.84        45\n      物流       0.88      0.96      0.91        45\n     新鲜度       0.00      0.00      0.00         2\n      包装       0.85      0.88      0.87        26\n      服务       1.00      0.82      0.90        11\n      气味       0.93      1.00      0.96        13\n      尺寸       0.00      0.00      0.00         0\n      整体       0.00      0.00      0.00         2\n      成分       0.50      0.60      0.55         5\n      其他       0.00      0.00      0.00         4\n      真伪       0.00      0.00      0.00         0\n      价格       0.69      0.97      0.81        37\n    使用体验       0.67      0.50      0.57         4\n      中性       0.75      0.30      0.43        10\n      负面       0.55      0.70      0.62        54\n      正面       0.87      0.90      0.88       588\n\nmicro-f1       0.83      0.87      0.85       846\n\nINFO:__main__:***的化妆品还是不错的，值得购买，性价比很高的活动就参加了！！！\nINFO:utils.trainUtils:Load ckpt from .\u002Fcheckpoints\u002Fbert_crf_gdcq\u002Fmodel.pt\nINFO:utils.trainUtils:Use single gpu in: ['0']\nINFO:__main__:{'正面': [('还是不错', 7), ('很高', 21)], '价格': [('性价比', 18), ('活动', 24)]}\n\n# 最后在predict_gdcq.py里面可进行后处理预测操作\npython predict_gdcq.py\n\n多次购买了，效果不错哦，价格便宜\n实体识别结果： [('不错', 8, '正面'), ('价格', 12, '价格'), ('便宜', 14, '正面')]\n未进行关联的实体： [('不错', 8, '正面')]\n关系合并： [('价格便宜', '正面')]\n```\n\n# 补充数据增强实例\n\n在data_augment下的aug.py用于对中文命名实体识别进行数据增强，运行指令：以cner数据集为例\n\n```python\npython aug.py --data_name \"cner\" --text_repeat 2\n```\n\ndata_name是数据集的名字，text_repeat是每条文本生成文本的数量。在data下需存在data_name的文件夹，先要参考其它数据集生成mid_data下的文件。增强思路：\n\n- 1、先将所有的不同类型的实体都提取出来并存储在\u002Fdata\u002Fcner\u002Faug_data\u002F下。\n- 2、将mid_data\u002Ftrain.json中的每一条文本中的实体用**#;#类型#;#**替代，并生成texts.txt在aug_data下。\n- 3、遍历texts.txt每一条文本，然后不放回随机从实体库中选择实体替代里面的类型，在和原来train.json里面的数据结合，最终存储在mid_data下的train_aug.json中。\n- 4、在preprocess.py里面指定数据集名称，并将use_aug设置为True。接下来的操作与各数据集的运行训练、验证、测试、预测相同。\n\n## 结果\n\n训练、验证、测试和预测运行指令：\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n```\n\n| 评价指标：F1      | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| ----------------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| baseline          | 0.90 | 0.92 | 1.00 | 0.93 | 0.99 | 0.96 | 1.00 | 0.91  | 0.9244 |\n| baseline+数据增强 | 0.92 | 0.93 | 1.00 | 0.97 | 1.00 | 0.97 | 1.00 | 0.91  | 0.9293 |\n\n除了数据量不一样，其余的参数均设置为一致。\n\n# 补充分词实例\n\n数据来源：链接: https:\u002F\u002Fpan.baidu.com\u002Fs\u002F1gvtqpjz05BglTy597AqbKQ?pwd=xuvp 提取码: xuvp 。具体实验过程参考其它数据集说明。\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fsighan2005\u002F\" \\\n--data_name=\"sighan2005\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=5 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=512 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=16 \\\n--train_epochs=3 \\\n--eval_batch_size=16 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n\nprecision:0.9667 recall:0.9549 micro_f1:0.9608\n          precision    recall  f1-score   support\n\n    word       0.97      0.95      0.96    104371\n\nmicro-f1       0.97      0.95      0.96    104371\n\n在１９９８年来临之际，我十分高兴地通过中央人民广播电台、中国国际广播电台和中央电视台，向全国各族人民，向香港特别行政区同胞、澳门和台湾同胞、海外侨胞，向世界各国的朋友们，致以诚挚的问候和良好的祝愿！\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf_sighan2005\u002Fmodel.pt\nUse single gpu in: ['0']\n{'word': [('在', 0), ('１９９８年', 1), ('来临', 6), ('之际', 8), ('，', 10), ('我', 11), ('十分', 12), ('高兴', 14), ('地', 16), ('通过', 17), ('中央', 19), ('人民', 21), ('广播', 23), ('电台', 25), ('、', 27), ('中国', 28), ('国际', 30), ('广播', 32), ('电台', 34), ('和', 36), ('中央', 37), ('电视台', 39), ('，', 42), ('向', 43), ('全国', 44), ('各族', 46), ('人民', 48), ('，', 50), ('向', 51), ('香港', 52), ('特别', 54), ('行政区', 56), ('同胞', 59), ('、', 61), ('澳门', 62), ('和', 64), ('台湾', 65), ('同胞', 67), ('、', 69), ('海外', 70), ('侨胞', 72), ('，', 74), ('向', 75), ('世界各国', 76), ('的', 80), ('朋友', 81), ('们', 83), ('，', 84), ('致以', 85), ('诚挚', 87), ('的', 89), ('问候', 90), ('和', 92), ('良好', 93), ('的', 95), ('祝愿', 96), ('！', 98)]}\n```\n\n# 补充商品标题要素抽取实例\n\n数据来源：[商品标题](https:\u002F\u002Fwww.heywhale.com\u002Fmw\u002Fdataset\u002F6241349d93e61600170895e5\u002Ffile)，就一个train.txt，初始格式为BIO。具体实验过程参考其它数据集说明。这里并没有运行完3个epoch，在720步手动终止了。类别数据进行了脱敏，要知道每类是什么意思，只有自己根据数据自己总结了=，=。\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fattr\u002F\" \\\n--data_name=\"attr\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=209 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=64 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=64 \\\n--train_epochs=3 \\\n--eval_batch_size=64 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.1 \\\n--dropout=0.1 \n\nprecision:0.7420 recall:0.7677 micro_f1:0.7546\n          precision    recall  f1-score   support\n\n      17       0.00      0.00      0.00         4\n      24       0.00      0.00      0.00         2\n      35       0.00      0.00      0.00         0\n      19       0.00      0.00      0.00        19\n      47       0.57      0.01      0.03       282\n      30       0.26      0.09      0.13       111\n      12       0.75      0.82      0.78      2460\n      44       0.00      0.00      0.00         8\n      49       0.32      0.33      0.33       266\n      31       0.44      0.23      0.30       169\n       1       0.82      0.89      0.85      5048\n      20       0.52      0.11      0.18       120\n      26       0.00      0.00      0.00         0\n      39       0.39      0.30      0.34      1059\n      36       0.42      0.53      0.47       736\n       5       0.75      0.74      0.74      7982\n      11       0.72      0.81      0.76     12250\n       6       0.58      0.79      0.67       303\n      18       0.73      0.77      0.75     11123\n      37       0.74      0.73      0.73      3080\n      42       0.00      0.00      0.00         4\n      46       0.00      0.00      0.00         7\n      33       0.00      0.00      0.00         4\n      23       0.00      0.00      0.00         4\n      15       0.62      0.58      0.60       146\n      28       0.00      0.00      0.00         8\n       9       0.50      0.61      0.55      2532\n      51       0.00      0.00      0.00         7\n      34       0.20      0.06      0.09        54\n       4       0.81      0.85      0.83     33645\n      14       0.87      0.89      0.88      4553\n      13       0.70      0.72      0.71     12992\n      32       0.00      0.00      0.00         8\n      38       0.60      0.68      0.64      6788\n      40       0.75      0.61      0.67      6588\n      53       0.00      0.00      0.00         0\n      43       0.00      0.00      0.00        13\n      22       0.38      0.32      0.35      1770\n      48       0.00      0.00      0.00        42\n       2       0.26      0.15      0.19       598\n      41       0.52      0.11      0.18       108\n      29       0.75      0.77      0.76       841\n      52       0.00      0.00      0.00        27\n      54       0.69      0.65      0.67      1221\n       3       0.52      0.61      0.56      1840\n       7       0.83      0.92      0.87      4921\n      10       0.49      0.46      0.48      1650\n      21       0.24      0.26      0.25       120\n      25       0.00      0.00      0.00         3\n      16       0.90      0.92      0.91      4604\n      50       0.56      0.38      0.46        91\n       8       0.86      0.90      0.88      3515\n\nmicro-f1       0.74      0.77      0.75    133726\n\n荣耀V9Play支架手机壳honorv9paly手机套新品情女款硅胶防摔壳\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf_attr\u002Fmodel.pt\nUse single gpu in: ['0']\n{'38': [('荣耀V9Play', 0), ('honorv9paly', 13)], '22': [('支架', 8)], '4': [('手机壳', 10), ('手机套', 24), ('防摔壳', 34)], '14': [('新品', 27)], '8': [('情女款', 29)], '12': [('硅胶', 32)]}\n```\n\n# 补充地址要素抽取实例\n数据集来源是：[CCKS2021中文NLP地址要素解析](https:\u002F\u002Ftianchi.aliyun.com\u002Fcompetition\u002Fentrance\u002F531900\u002Finformation)，报名后可下载数据，这里不提供。具体实验过程参考其它数据集说明。\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Faddr\u002F\" \\\n--data_name=\"addr\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=69 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=64 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=64 \\\n--train_epochs=3 \\\n--eval_batch_size=64 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.1 \\\n--dropout=0.1 \n\nprecision:0.9233 recall:0.9021 micro_f1:0.9125\n               precision    recall  f1-score   support\n\n     district       0.96      0.93      0.94      1444\nvillage_group       0.91      0.87      0.89        47\n       roadno       0.98      0.98      0.98       815\n          poi       0.77      0.85      0.81      1279\n       subpoi       0.82      0.65      0.73       459\n    community       0.81      0.70      0.75       373\n     distance       1.00      1.00      1.00         6\n         city       0.99      0.94      0.96      1244\n         road       0.94      0.95      0.95      1244\n         prov       0.99      0.97      0.98       994\n      floorno       0.97      0.94      0.95       211\n       assist       0.82      0.88      0.85        64\n       cellno       0.99      0.98      0.98       123\n         town       0.95      0.87      0.91       924\n      devzone       0.82      0.82      0.82       222\n      houseno       0.97      0.96      0.97       496\n intersection       0.93      0.65      0.76        20\n\n     micro-f1       0.92      0.90      0.91      9965\n    \n浙江省嘉兴市平湖市钟埭街道新兴六路法帝亚洁具厂区内万杰洁具\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf_addr\u002Fmodel.pt\nUse single gpu in: ['0']\n{'prov': [('浙江省', 0)], 'city': [('嘉兴市', 3)], 'district': [('平湖市', 6)], 'town': [('钟埭街道', 9)], 'road': [('新兴六路', 13)], 'poi': [('法帝亚洁具厂区', 17), ('万杰洁具', 25)]}\n```\n\n# 补充CLUE实例\n\n具体流程和医疗的类似，原始数据可以从这里下载：https:\u002F\u002Fgithub.com\u002FGuocaiL\u002Fnlp_corpus\u002Ftree\u002Fmain\u002Fopen_ner_data\u002Fcluener_public\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002FCLUE\u002F\" \\\n--data_name=\"clue\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=41 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n\nprecision:0.7802 recall:0.8176 micro_f1:0.7984\n              precision    recall  f1-score   support\n\n    position       0.77      0.82      0.80       425\n       movie       0.88      0.77      0.82       150\n        name       0.84      0.90      0.87       451\n        book       0.86      0.81      0.83       152\n     address       0.65      0.68      0.66       364\norganization       0.81      0.81      0.81       344\n       scene       0.73      0.76      0.74       199\n  government       0.77      0.87      0.82       244\n        game       0.76      0.90      0.82       287\n     company       0.80      0.81      0.81       366\n\n    micro-f1       0.78      0.82      0.80      2982\n\n彭小军认为，国内银行现在走的是台湾的发卡模式，先通过跑马圈地再在圈的地里面选择客户，\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf\u002Fmodel.pt\nUse single gpu in: ['0']\n{'name': [('彭小军', 0)], 'address': [('台湾', 15)]}\n```\n\n****\n# 补充医疗实例\n1、在data\u002FCHIP2020\u002Fraw_data下是原始数据，使用process.py处理raw_data以获取mid_data下的数据。原始数据可以去这里下载：https:\u002F\u002Fgithub.com\u002Fzhangzhiyi0108\u002FCHIP2020_Entity\u003Cbr>\n2、修改preprocess.py里面为自己定义的数据集，并指定数据地址及最大长度，稍后的自定义参数需要保持和这里的一致。\u003Cbr>\n3、修改main.py里面为自己定义的数据集及相关参数。\u003Cbr>\n4、修改main.sh里面运行指令的相关参数，最后运行即可。\u003Cbr>\n5、基于bert_crf训练好的模型可以去这里下载：链接：https:\u002F\u002Fpan.baidu.com\u002Fs\u002F1if6G00ERfXSWfe_h23hgDg?pwd=2s3e \n提取码：2s3e\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002FCHIP2020\u002F\" \\\n--data_name=\"chip\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=37 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf\u002Fmodel.pt\nUse single gpu in: ['0']\nprecision:0.6477 recall:0.6530 micro_f1:0.6503\n          precision    recall  f1-score   support\n\n     equ       0.57      0.57      0.57       238\n     sym       0.59      0.45      0.51      4130\n     pro       0.60      0.68      0.64      2057\n     bod       0.63      0.66      0.64      5883\n     dis       0.71      0.78      0.74      4935\n     dru       0.77      0.86      0.81      1440\n     mic       0.73      0.82      0.77       584\n     dep       0.59      0.53      0.56       110\n     ite       0.47      0.40      0.43       923\n\nmicro-f1       0.65      0.65      0.65     20300\n\n大动脉转换手术要求左心室流出道大小及肺动脉瓣的功能正常，但动力性左心室流出道梗阻并非大动脉转换术的禁忌证。\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf\u002Fmodel.pt\nUse single gpu in: ['0']\n{'pro': [('大动脉转换手术', 0), ('大动脉转换术', 42)], 'bod': [('左心室流出道', 9), ('肺动脉瓣', 18)], 'dis': [('动力性左心室流出道梗阻', 29)]}\n```\n****\n# 最初说明\n基于pytorch的bert_bilstm_crf中文命名实体识别\u003Cbr>\n要预先下载好预训练的bert模型，放在和该项目同级下的model_hub文件夹下，即：\u003Cbr>\nmodel_hub\u002Fbert-base-chinese\u002F\u003Cbr>\n相关下载地址：\u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fbert-base-chinese\u002Ftree\u002Fmain=\">bert-base-chinese\u003C\u002Fa>\u003Cbr>\n需要的是vocab.txt、config.json、pytorch_model.bin\u003Cbr>\n你也可以使用我已经训练好的模型，将其放在checkpoints下：\u003Cbr>\n链接：https:\u002F\u002Fpan.baidu.com\u002Fs\u002F1yIGnQ9I_4HAfQSqHod-hMQ \u003Cbr>\n提取码：4j47\u003Cbr>\n里面有四种模型对应的model.pt\u003Cbr>\n\n**后面重构了代码，不要使用上面的保存的模型了，自己训练个。**\n\n# 目录结构\n--checkpoints：模型保存的位置\u003Cbr>\n--data：数据位置\u003Cbr>\n--|--cner：数据集名称\u003Cbr>\n--|--|--raw_data：原始数据存储位置，里面有个process.py用于转换文本+标签json\u003Cbr>\n--|--|--mid_data：保存处理之后的json文件，标签等；\u003Cbr>\n--|--|--final_data：存储处理好之后可用的pickle文件\u003Cbr>\n--logs：日志存储位置\u003Cbr>\n--utils：辅助函数存储位置，包含了解码、评价指标、设置随机种子、设置日志等\u003Cbr>\n--config.py：配置文件\u003Cbr>\n--dataset.py：数据转换为pytorch的DataSet\u003Cbr>\n--main.py：主运行程序\u003Cbr>\n--main.sh：运行命令\u003Cbr>\n--bert_base_model.py：Bert模型\u003Cbr>\n--bert_ner_modelpy：利用Bert进行Ner的模型\u003Cbr>\n--preprocess.py：预处理，主要是处理数据然后转换成DataSet\u003Cbr>\n\n\n# 运行命令\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fbert-base-chinese\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n```\n我们可以通过控制--use_lstm和--use_crf来切换使用bilstm或crf。\n\n# 结果\n# 训练、验证、测试和预测\n由于忘记保存其它测试和预测了，这里就只展示bert的。\n```python\n2021-08-05 16:19:12,787 - INFO - main.py - train - 52 - 【train】 epoch:2 359\u002F360 loss:0.0398\n2021-08-05 16:19:14,717 - INFO - main.py - train - 56 - [eval] loss:1.8444 precision=0.9484 recall=0.8732 f1_score=0.9093\n2021-08-05 16:32:20,751 - INFO - main.py - test - 130 -           \n             precision    recall  f1-score   support\n\n     PRO       0.86      0.63      0.73        19\n     ORG       0.94      0.91      0.92       543\n    CONT       1.00      1.00      1.00        33\n    RACE       1.00      0.93      0.97        15\n    NAME       0.99      0.93      0.96       110\n     EDU       0.98      0.94      0.96       109\n     LOC       0.00      0.00      0.00         2\n   TITLE       0.95      0.84      0.89       770\n\nmicro-f1       0.95      0.88      0.91      1601\n\n2021-08-05 16:32:20,752 - INFO - main.py - \u003Cmodule> - 218 - 虞兔良先生：1963年12月出生，汉族，中国国籍，无境外永久居留权，浙江绍兴人，中共党员，MBA，经济师。\n2021-08-05 16:32:22,892 - INFO - trainUtils.py - load_model_and_parallel - 96 - Load ckpt from .\u002Fcheckpoints\u002Fbert\u002Fmodel.pt\n2021-08-05 16:32:23,205 - INFO - trainUtils.py - load_model_and_parallel - 106 - Use single gpu in: ['0']\n2021-08-05 16:32:23,239 - INFO - main.py - predict - 156 - {'NAME': [('虞兔良', 0)], 'RACE': [('汉族', 17)], 'CONT': [('中国国籍', 20)], 'TITLE': [('中共党员', 40), ('经济师', 49)], 'EDU': [('MBA', 45)]}\n```\n## 验证集上对比\n| models | loss | precision | recall | f1_score |\n| :-----------: | :-----------: | :-----------: | :-----------: | :-----------: |\n|bert|1.8444 |0.9484 |0.8732 |0.9093 |\n|bert_bilstm|2.0856 |0.9540 |0.8670 |0.9084 |\n|bert_crf|26.9665 |0.9385 |0.8957 |0.9166 |\n|bert_bilstm_crf|30.8463 |0.9382 |0.8919 |0.9145 |\n\n以上训练的都是3个epoch。\n\n# 延申：\n- 百度UIE通用信息抽取：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_uie_ner\n- 一种基于globalpointer的命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_GlobalPointer_Ner\n- 一种基于TPLinker_plus的命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_TPLinker_Plus_Ner\n- 一种one vs rest方法进行命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_OneVersusRest_Ner\n- 一种级联Bert用于命名实体识别，解决标签过多问题：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_Cascade_Bert_Ner\n- 一种多头选择Bert用于命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_Multi_Head_Selection_Ner\n- 中文命名实体识别最新进展：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fawesome-chinese-ner\n- 信息抽取三剑客：实体抽取、关系抽取、事件抽取：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fchinese_information_extraction\n- 一种基于机器阅读理解的命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002FBERT_MRC_NER_chinese\n- W2NER：命名实体识别最新sota：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002FW2NER_predict\n\n","# pytorch_bert_bilstm_crf_ner\n\n# 依赖\n```python\npython==3.6（可选）\npytorch==1.6.0（可选）\npytorch-crf==0.7.2\ntransformers==4.5.0\nnumpy==1.22.4\npackaging==21.3\n```\n\n****\n这里总结下步骤，以cner数据为例：\n```python\n先去hugging face下载相关文件到chinese-bert-wwwm-ext下。\n目录结构：\n--pytorch_bilstm_crf_ner\n--model_hub\n----chinese-bert-wwm-ext\n------vocab.txt\n------config.json\n------pytorch_model.bin\n\n1、原始数据放在data\u002Fcner\u002Fraw_data\u002F下，并新建mid_data和final_data两个文件夹。\n2、将raw_data下的数据处理成mid_data下的格式。其中：\n--labels.txt：实体类别\n[\"PRO\", \"ORG\", \"CONT\", \"RACE\", \"NAME\", \"EDU\", \"LOC\", \"TITLE\"]\n--nor_ent2id.json：BIOES格式的标签\n{\"O\": 0, \"B-PRO\": 1, \"I-PRO\": 2, \"E-PRO\": 3, \"S-PRO\": 4, \"B-ORG\": 5, \"I-ORG\": 6, \"E-ORG\": 7, \"S-ORG\": 8, \"B-CONT\": 9, \"I-CONT\": 10, \"E-CONT\": 11, \"S-CONT\": 12, \"B-RACE\": 13, \"I-RACE\": 14, \"E-RACE\": 15, \"S-RACE\": 16, \"B-NAME\": 17, \"I-NAME\": 18, \"E-NAME\": 19, \"S-NAME\": 20, \"B-EDU\": 21, \"I-EDU\": 22, \"E-EDU\": 23, \"S-EDU\": 24, \"B-LOC\": 25, \"I-LOC\": 26, \"E-LOC\": 27, \"S-LOC\": 28, \"B-TITLE\": 29, \"I-TITLE\": 30, \"E-TITLE\": 31, \"S-TITLE\": 32}\n--train.json\u002Fdev.json\u002Ftest.json：是一个列表，列表里面每个元素是：\n[\n  {\n    \"id\": 0,\n    \"text\": \"常建良，男，\",\n    \"labels\": [\n      [\n        \"T0\",\n        \"NAME\",  \n        0,\n        3,  # 后一位\n        \"常建良\"\n      ]\n    ]\n  },\n  ......\n]\n3、在preprocess.py里面修改数据集名称和设置文本最大长度，并按照其它数据一样添加一段代码。运行后得到final_data下的数据。\n4、运行指令进行训练、验证和测试：\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\# 默认为bert\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\# BIOES标签的数目\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\# 文本最大长度，和prepcoess.py里面保持一致\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\# 训练batch_size\n--train_epochs=3 \\# 训练epoch\n--eval_batch_size=32 \\# 验证batch_size\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\# 是否使用bilstm\n--use_idcnn=\"True\" \\# 是否使用idcnn。idcnn和bilstm只能选择一种\n--use_crf=\"True\" \\# 是否使用crf\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n运行的时候需要在命令行运行，且不要带上后面的注释。windows下运行需要将指令变成一行，即删除掉\"\\\\\"。\n\n****\n\n### 温馨提示\n\n- 新增了转换为ONNX并进行推理的功能，具体内容在`convert_onnx`目录下，运行命令为```python convert_onnx.py```，目前仅支持对单条数据的推理。在CPU环境下，原始推理时间为0.714256477355957秒，转换为ONNX后推理时间为0.4593505859375秒。需要安装`onnxruntime`和`onnx`库。原有的PyTorch CRF模型无法直接转换为ONNX，此处使用了[此处](https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fpytext\u002Fblob\u002Fmaster\u002Fpytext\u002Fmodels\u002Fcrf.py)提供的实现。目前仅测试了`bert_crf`模型，其他模型可根据需求自行调整。\n\n#### 问题汇总\n- `ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions.`\n\n解决方法：```pip install numpy==1.22.4```\n- `packaging.version.InvalidVersion: Invalid version: '0.10.1,\u003C0.11'`\n\n解决方法：```pip install packaging==21.3```\n\n#### 2023-05-12\n重新编写了一个简洁版的BERT-BILSTM-CRF模型，代码更加简洁，使用起来也更为方便：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002FBERT-BILSTM-CRF\n\n#### 2023-03-17\n适配PyTorch 2.0版本，主要加入了`torch.compile(model)`。虽然程序已成功运行，但可能仍存在一些问题，导致速度并未显著提升。\n\n#### 2022-10-10\n\n补充了知识蒸馏的实例。具体代码位于`knowledge_distillation\u002Fkd.py`中，该实例将`bert_idcnn_crf_cner`模型蒸馏到`idcnn_crf_cner`模型上。具体步骤如下：\n\n- 首先训练一个教师模型：`bert_idcnn_crf_cner`。\n- 然后训练一个学生模型：`idcnn_crf_cner`。\n- 接着修改`kd.py`中参数文件的路径，并调整相关参数后运行`kd.py`即可。\n\n在CNER数据集上进行知识蒸馏的效果不如预期，可能是由于CNER数据量较少，导致教师模型和学生模型之间的差异过小。\n\n#### 2022-09-23\n- 在`predict.py`中新增了`batch_predict`功能：若输入文本长度超过当前设置的最大长度，则会对句子进行切分，切分后再进行批量预测。结果可在`scripts\u002Fserver.py`中通过`merge_with_loc`函数进行合并。\n- 增加了`tensorboardX`用于可视化损失函数的变化过程。可通过指定`--use_tensorboard==\"True\"`来启用，使用命令行```tensorboard --logdir=.\u002Ftensorboard```查看结果。\n- 新增了OneNERS 4.0数据集，此处仅提供训练数据，并附带数据转换脚本`process.py`。\n\n#### 2022-08-18\n\n- 新增了微博和MSRA数据集，具体运行示例未在此处补充，可供练习使用。\n- 将预测代码提取至`predict.py`文件中，使用时需注意以下几点：\n\t- 修改`args_path`。\n\t- 修改`model_name`。\n\n#### 2022-09-15\n\n新增了IDCNN模型，[IDCNN代码来源](https:\u002F\u002Fgithub.com\u002FcirclePi\u002FIDCNN-CRF-Pytorch\u002Fblob\u002Fmaster\u002FIDCNN-CRF\u002Fcnn.py)。单独使用IDCNN_CRF模型时，需设置`model_name=\"idcnn\"`。此外，IDCNN也可以与BERT相关模型结合使用，通过`use_idcnn`参数进行控制。需要注意的是，BILSTM和IDCNN不能同时使用：\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_idcnn=\"True\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n\n| 评价指标：F1        | 模型大小 | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| ------------------- | -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| idcnn_crf_cner      | 64.95M   | 0.76 | 0.86 | 1.00 | 0.97 | 0.97 | 0.95 | 0.80 | 0.87  | 0.8817 |\n| bert_idcnn_crf_cner | 393.25M  | 0.92 | 0.92 | 1.00 | 0.90 | 0.99 | 0.97 | 1.00 | 0.90  | 0.9232 |\n\n#### 2022-09-14\n\n新增了单独的**BILSTM_CRF**和**CRF**模型，使用的词汇表是根据所选预训练模型的`vocab.txt`生成的。使用BILSTM_CRF时需设置`model_name=\"bilstm\"`，使用CRF时需设置`model_name=\"crf\"`。需要注意的是，BILSTM默认会使用CRF，而CRF则只使用其自身。运行命令如下：\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bilstm\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=20 \\\n--eval_batch_size=32 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"True\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n\n效果：针对CNER数据集\n\n| 评价指标：F1    | 模型大小 | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| --------------- | -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| bilstm_crf_cner | 65.45M   | 0.90 | 0.86 | 1.00 | 0.97 | 0.98 | 0.97 | 1.00 | 0.87  | 0.8853 |\n| crf_cner        | 62.00M   | 0.77 | 0.81 | 1.00 | 1.00 | 0.90 | 0.94 | 1.00 | 0.84  | 0.8453 |\n\n#### 2022-09-02\n\n- 补充了将模型启动为服务的代码，代码位于`scripts`目录下。针对不同的数据集和模型，只需修改开头的`args`路径即可。\n\n在Linux系统下使用：\n\n- `.\u002Fstart_server.sh`：启动服务。\n- `.\u002Fstop_server.sh`：停止服务。\n- `.\u002Frestart_server.sh`：停止服务并重新启动。\n\n在Windows系统下可以直接运行`python server.py`。\n\n最终可运行`python test_requests.py`来测试接口。\n\n- 新增了页面展示功能，需在`scripts\u002Ftemplates\u002Fpredict.html`中修改IP地址。启动服务后，访问`http:\u002F\u002Fip地址:9277\u002F`，输入文本即可获得结果。\n\n#### 2022-08-19\n\n- 新增了其他模型的训练结果，目录结构如下：\n\n\t```\n\t——project\n\t————model_hub\n\t——————chinese-bert-wwm-ext\n\t————————vocab.txt\n\t————————pytorch_model.bin\n\t————————config.json\n\t——————其它模型路径\n\t————pytorch_bert_bilstm_crf_ner\n\t```\n\n- 需要修改的地方是：\n\n\t- `--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\"` \n\t- `--model_name=\"bert\"`\n\t- 使用Electra模型时设置`model_name=\"electra\"`，使用Albert模型时设置`model_name=\"albert\"`，使用Mengzi模型时设置`model_name=\"mengzi\"`，其余均可设置`model_name=\"bert\"`（或自定义）。\n\n主要参数：针对CNER数据集\n\n```\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=”False“ \\\n--use_crf=“True” \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n\n| 评价指标：F1                                                 | 模型大小 | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| ------------------------------------------------------------ | -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| [mengzi-bert-base](https:\u002F\u002Fhuggingface.co\u002FLangboat\u002Fmengzi-bert-base\u002Ftree\u002Fmain) | 196.28M  | 0.90 | 0.91 | 1.00 | 0.93 | 1.00 | 0.96 | 1.00 | 0.90  | 0.9154 |\n| [chinese-bert-wwm-ext](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-roberta-wwm-ext\u002Ftree\u002Fmain) | 392.51M  | 0.90 | 0.92 | 1.00 | 0.93 | 0.99 | 0.96 | 1.00 | 0.91  | 0.9148 |\n| [bert-base-chinese](https:\u002F\u002Fhuggingface.co\u002Fbert-base-chinese\u002Ftree\u002Fmain) | 392.51M  | 0.90 | 0.92 | 1.00 | 0.93 | 1.00 | 0.97 | 1.00 | 0.91  | 0.9233 |\n| [chinese-roberta-wwm-ext](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-roberta-wwm-ext\u002Ftree\u002Fmain) | 392.51M  | 0.90 | 0.92 | 1.00 | 0.93 | 0.99 | 0.97 | 1.00 | 0.90  | 0.9196 |\n| [chinese-macbert-base](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-macbert-base\u002Ftree\u002Fmain) | 392.52M  | 0.92 | 0.92 | 1.00 | 0.93 | 1.00 | 0.98 | 1.00 | 0.90  | 0.9203 |\n| [chinese-electra-180g-small-discriminator](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-electra-180g-small-discriminator\u002Ftree\u002Fmain) | 47.15M   | 0.74 | 0.88 | 0.99 | 0.12 | 0.97 | 0.81 | 0.00 | 0.87  | 0.8753 |\n| [chinese-electra-180g-base-discriminator](https:\u002F\u002Fhuggingface.co\u002Fhfl\u002Fchinese-electra-180g-small-discriminator\u002Ftree\u002Fmain) | 390.17M  | 0.88 | 0.91 | 1.00 | 0.97 | 1.00 | 0.94 | 1.00 | 0.87  | 0.9012 |\n| [albert-base-chinese](https:\u002F\u002Fhuggingface.co\u002Fckiplab\u002Falbert-base-chinese\u002Ftree\u002Fmain) | 38.46M   | 0.00 | 0.68 | 0.95 | 0.00 | 0.62 | 0.53 | 0.00 | 0.71  | 0.6765 |\n\n# 补充观点抽取实例\n\n这里有点关系抽取的味道。我们要做的是抽取评论中的主体、评价及其情感。具体做法是转换为序列标注，主体标注为不同类别，评价标注为情感极性，最后识别出实体后再进行合并，具体步骤参考其它数据集。\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fgdcq\u002F\" \\\n--data_name=\"gdcq\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=65 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=70 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=64 \\\n--train_epochs=10 \\\n--eval_batch_size=64 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_idcnn=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n\nprecision:0.8301 recall:0.8723 micro_f1:0.8507\n            precision    recall  f1-score   support\n\n      功效       0.84      0.84      0.84        45\n      物流       0.88      0.96      0.91        45\n     新鲜度       0.00      0.00      0.00         2\n      包装       0.85      0.88      0.87        26\n      服务       1.00      0.82      0.90        11\n      气味       0.93      1.00      0.96        13\n      尺寸       0.00      0.00      0.00         0\n      整体       0.00      0.00      0.00         2\n      成分       0.50      0.60      0.55         5\n      其他       0.00      0.00      0.00         4\n      真伪       0.00      0.00      0.00         0\n      价格       0.69      0.97      0.81        37\n    使用体验       0.67      0.50      0.57         4\n      中性       0.75      0.30      0.43        10\n      负面       0.55      0.70      0.62        54\n      正面       0.87      0.90      0.88       588\n\nmicro-f1       0.83      0.87      0.85       846\n\nINFO:__main__:***的化妆品还是不错的，值得购买，性价比很高的活动就参加了！！！\nINFO:utils.trainUtils:Load ckpt from .\u002Fcheckpoints\u002Fbert_crf_gdcq\u002Fmodel.pt\nINFO:utils.trainUtils:Use single gpu in: ['0']\nINFO:__main__:{'正面': [('还是不错', 7), ('很高', 21)], '价格': [('性价比', 18), ('活动', 24)]}\n\n# 最后在predict_gdcq.py里面可进行后处理预测操作\npython predict_gdcq.py\n\n多次购买了，效果不错哦，价格便宜\n实体识别结果： [('不错', 8, '正面'), ('价格', 12, '价格'), ('便宜', 14, '正面')]\n未进行关联的实体： [('不错', 8, '正面')]\n关系合并： [('价格便宜', '正面')]\n```\n\n# 补充数据增强实例\n\n在data_augment下的aug.py用于对中文命名实体识别进行数据增强，运行指令：以cner数据集为例\n\n```python\npython aug.py --data_name \"cner\" --text_repeat 2\n```\n\ndata_name是数据集的名字，text_repeat是每条文本生成文本的数量。在data下需存在data_name的文件夹，先要参考其它数据集生成mid_data下的文件。增强思路：\n\n- 1、先将所有的不同类型的实体都提取出来并存储在\u002Fdata\u002Fcner\u002Faug_data\u002F下。\n- 2、将mid_data\u002Ftrain.json中的每一条文本中的实体用**#;#类型#;#**替代，并生成texts.txt在aug_data下。\n- 3、遍历texts.txt每一条文本，然后不放回随机从实体库中选择实体替代里面的类型，在和原来train.json里面的数据结合，最终存储在mid_data下的train_aug.json中。\n- 4、在preprocess.py里面指定数据集名称，并将use_aug设置为True。接下来的操作与各数据集的运行训练、验证、测试、预测相同。\n\n## 结果\n\n训练、验证、测试和预测运行指令：\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n```\n\n| 评价指标：F1      | PRO  | ORG  | CONT | RACE | NAME | EDU  | LOC  | TITLE | F1     |\n| ----------------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------ |\n| baseline          | 0.90 | 0.92 | 1.00 | 0.93 | 0.99 | 0.96 | 1.00 | 0.91  | 0.9244 |\n| baseline+ 数据增强 | 0.92 | 0.93 | 1.00 | 0.97 | 1.00 | 0.97 | 1.00 | 0.91  | 0.9293 |\n\n除了数据量不一样，其余的参数均设置为一致。\n\n# 补充分词实例\n\n数据来源：链接: https:\u002F\u002Fpan.baidu.com\u002Fs\u002F1gvtqpjz05BglTy597AqbKQ?pwd=xuvp 提取码: xuvp 。具体实验过程参考其它数据集说明。\n\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fsighan2005\u002F\" \\\n--data_name=\"sighan2005\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=5 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=512 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=16 \\\n--train_epochs=3 \\\n--eval_batch_size=16 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n\nprecision:0.9667 recall:0.9549 micro_f1:0.9608\n          precision    recall  f1-score   support\n\n    word       0.97      0.95      0.96    104371\n\nmicro-f1       0.97      0.95      0.96    104371\n\n在１９９８年来临之际，我十分高兴地通过中央人民广播电台、中国国际广播电台和中央电视台，向全国各族人民，向香港特别行政区同胞、澳门和台湾同胞、海外侨胞，向世界各国的朋友们，致以诚挚的问候和良好的祝愿！\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf_sighan2005\u002Fmodel.pt\nUse single gpu in: ['0']\n{'word': [('在', 0), ('１９９８年', 1), ('来临', 6), ('之际', 8), ('，', 10), ('我', 11), ('十分', 12), ('高兴', 14), ('地', 16), ('通过', 17), ('中央', 19), ('人民', 21), ('广播', 23), ('电台', 25), ('、', 27), ('中国', 28), ('国际', 30), ('广播', 32), ('电台', 34), ('和', 36), ('中央', 37), ('电视台', 39), ('，', 42), ('向', 43), ('全国', 44), ('各族', 46), ('人民', 48), ('，', 50), ('向', 51), ('香港', 52), ('特别', 54), ('行政区', 56), ('同胞', 59), ('、', 61), ('澳门', 62), ('和', 64), ('台湾', 65), ('同胞', 67), ('、', 69), ('海外', 70), ('侨胞', 72), ('，', 74), ('向', 75), ('世界各国', 76), ('的', 80), ('朋友', 81), ('们', 83), ('，', 84), ('致以', 85), ('诚挚', 87), ('的', 89), ('问候', 90), ('和', 92), ('良好', 93), ('的', 95), ('祝愿', 96), ('！', 98)]}\n```\n\n# 补充商品标题要素抽取实例\n\n数据来源：[商品标题](https:\u002F\u002Fwww.heywhale.com\u002Fmw\u002Fdataset\u002F6241349d93e61600170895e5\u002Ffile)，就一个train.txt，初始格式为BIO。具体实验过程参考其它数据集说明。这里并没有运行完3个epoch，在720步手动终止了。类别数据进行了脱敏，要知道每类是什么意思，只有自己根据数据自己总结了=，=。\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fattr\u002F\" \\\n--data_name=\"attr\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=209 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=64 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=64 \\\n--train_epochs=3 \\\n--eval_batch_size=64 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.1 \\\n--dropout=0.1 \n\nprecision:0.7420 recall:0.7677 micro_f1:0.7546\n          precision    recall  f1-score   support\n\n      17       0.00      0.00      0.00         4\n      24       0.00      0.00      0.00         2\n      35       0.00      0.00      0.00         0\n      19       0.00      0.00      0.00        19\n      47       0.57      0.01      0.03       282\n      30       0.26      0.09      0.13       111\n      12       0.75      0.82      0.78      2460\n      44       0.00      0.00      0.00         8\n      49       0.32      0.33      0.33       266\n      31       0.44      0.23      0.30       169\n       1       0.82      0.89      0.85      5048\n      20       0.52      0.11      0.18       120\n      26       0.00      0.00      0.00         0\n      39       0.39      0.30      0.34      1059\n      36       0.42      0.53      0.47       736\n       5       0.75      0.74      0.74      7982\n      11       0.72      0.81      0.76     12250\n       6       0.58      0.79      0.67       303\n      18       0.73      0.77      0.75     11123\n      37       0.74      0.73      0.73      3080\n      42       0.00      0.00      0.00         4\n      46       0.00      0.00      0.00         7\n      33       0.00      0.00      0.00         4\n      23       0.00      0.00      0.00         4\n      15       0.62      0.58      0.60       146\n      28       0.00      0.00      0.00         8\n       9       0.50      0.61      0.55      2532\n      51       0.00      0.00      0.00         7\n      34       0.20      0.06      0.09        54\n       4       0.81      0.85      0.83     33645\n      14       0.87      0.89      0.88      4553\n      13       0.70      0.72      0.71     12992\n      32       0.00      0.00      0.00         8\n      38       0.60      0.68      0.64      6788\n      40       0.75      0.61      0.67      6588\n      53       0.00      0.00      0.00         0\n      43       0.00      0.00      0.00        13\n      22       0.38      0.32      0.35      1770\n      48       0.00      0.00      0.00        42\n       2       0.26      0.15      0.19       598\n      41       0.52      0.11      0.18       108\n      29       0.75      0.77      0.76       841\n      52       0.00      0.00      0.00        27\n      54       0.69      0.65      0.67      1221\n       3       0.52      0.61      0.56      1840\n       7       0.83      0.92      0.87      4921\n      10       0.49      0.46      0.48      1650\n      21       0.24      0.26      0.25       120\n      25       0.00      0.00      0.00         3\n      16       0.90      0.92      0.91      4604\n      50       0.56      0.38      0.46        91\n       8       0.86      0.90      0.88      3515\n\nmicro-f1       0.74      0.77      0.75    133726\n\n荣耀V9Play支架手机壳honorv9paly手机套新品情女款硅胶防摔壳\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf_attr\u002Fmodel.pt\nUse single gpu in: ['0']\n{'38': [('荣耀V9Play', 0), ('honorv9paly', 13)], '22': [('支架', 8)], '4': [('手机壳', 10), ('手机套', 24), ('防摔壳', 34)], '14': [('新品', 27)], '8': [('情女款', 29)], '12': [('硅胶', 32)]}\n```\n\n# 补充地址要素抽取实例\n数据集来源是：[CCKS2021中文NLP地址要素解析](https:\u002F\u002Ftianchi.aliyun.com\u002Fcompetition\u002Fentrance\u002F531900\u002Finformation)，报名后可下载数据，这里不提供。具体实验过程参考其它数据集说明。\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Faddr\u002F\" \\\n--data_name=\"addr\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=69 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=64 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=64 \\\n--train_epochs=3 \\\n--eval_batch_size=64 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.1 \\\n--dropout=0.1 \n\nprecision:0.9233 recall:0.9021 micro_f1:0.9125\n               precision    recall  f1-score   support\n\n     district       0.96      0.93      0.94      1444\nvillage_group       0.91      0.87      0.89        47\n       roadno       0.98      0.98      0.98       815\n          poi       0.77      0.85      0.81      1279\n       subpoi       0.82      0.65      0.73       459\n    community       0.81      0.70      0.75       373\n     distance       1.00      1.00      1.00         6\n         city       0.99      0.94      0.96      1244\n         road       0.94      0.95      0.95      1244\n         prov       0.99      0.97      0.98       994\n      floorno       0.97      0.94      0.95       211\n       assist       0.82      0.88      0.85        64\n       cellno       0.99      0.98      0.98       123\n         town       0.95      0.87      0.91       924\n      devzone       0.82      0.82      0.82       222\n      houseno       0.97      0.96      0.97       496\n intersection       0.93      0.65      0.76        20\n\n     micro-f1       0.92      0.90      0.91      9965\n    \n浙江省嘉兴市平湖市钟埭街道新兴六路法帝亚洁具厂区内万杰洁具\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf_addr\u002Fmodel.pt\nUse single gpu in: ['0']\n{'prov': [('浙江省', 0)], 'city': [('嘉兴市', 3)], 'district': [('平湖市', 6)], 'town': [('钟埭街道', 9)], 'road': [('新兴六路', 13)], 'poi': [('法帝亚洁具厂区', 17), ('万杰洁具', 25)]}\n```\n\n# 补充CLUE实例\n\n具体流程和医疗的类似，原始数据可以从这里下载：https:\u002F\u002Fgithub.com\u002FGuocaiL\u002Fnlp_corpus\u002Ftree\u002Fmain\u002Fopen_ner_data\u002Fcluener_public\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002FCLUE\u002F\" \\\n--data_name=\"clue\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=41 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n\nprecision:0.7802 recall:0.8176 micro_f1:0.7984\n              precision    recall  f1-score   support\n\n    position       0.77      0.82      0.80       425\n       movie       0.88      0.77      0.82       150\n        name       0.84      0.90      0.87       451\n        book       0.86      0.81      0.83       152\n     address       0.65      0.68      0.66       364\norganization       0.81      0.81      0.81       344\n       scene       0.73      0.76      0.74       199\n  government       0.77      0.87      0.82       244\n        game       0.76      0.90      0.82       287\n     company       0.80      0.81      0.81       366\n\n    micro-f1       0.78      0.82      0.80      2982\n\n彭小军认为，国内银行现在走的是台湾的发卡模式，先通过跑马圈地再在圈的地里面选择客户，\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf\u002Fmodel.pt\nUse single gpu in: ['0']\n{'name': [('彭小军', 0)], 'address': [('台湾', 15)]}\n```\n\n****\n# 补充医疗实例\n1、在data\u002FCHIP2020\u002Fraw_data下是原始数据，使用process.py处理raw_data以获取mid_data下的数据。原始数据可以去这里下载：https:\u002F\u002Fgithub.com\u002Fzhangzhiyi0108\u002FCHIP2020_Entity\u003Cbr>\n2、修改preprocess.py里面为自己定义的数据集，并指定数据地址及最大长度，稍后的自定义参数需要保持和这里的一致。\u003Cbr>\n3、修改main.py里面为自己定义的数据集及相关参数。\u003Cbr>\n4、修改main.sh里面运行指令的相关参数，最后运行即可。\u003Cbr>\n5、基于bert_crf训练好的模型可以去这里下载：链接：https:\u002F\u002Fpan.baidu.com\u002Fs\u002F1if6G00ERfXSWfe_h23hgDg?pwd=2s3e \n提取码：2s3e\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002FCHIP2020\u002F\" \\\n--data_name=\"chip\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=37 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf\u002Fmodel.pt\nUse single gpu in: ['0']\nprecision:0.6477 recall:0.6530 micro_f1:0.6503\n          precision    recall  f1-score   support\n\n     equ       0.57      0.57      0.57       238\n     sym       0.59      0.45      0.51      4130\n     pro       0.60      0.68      0.64      2057\n     bod       0.63      0.66      0.64      5883\n     dis       0.71      0.78      0.74      4935\n     dru       0.77      0.86      0.81      1440\n     mic       0.73      0.82      0.77       584\n     dep       0.59      0.53      0.56       110\n     ite       0.47      0.40      0.43       923\n\nmicro-f1       0.65      0.65      0.65     20300\n\n大动脉转换手术要求左心室流出道大小及肺动脉瓣的功能正常，但动力性左心室流出道梗阻并非大动脉转换术的禁忌证。\nLoad ckpt from .\u002Fcheckpoints\u002Fbert_crf\u002Fmodel.pt\nUse single gpu in: ['0']\n{'pro': [('大动脉转换手术', 0), ('大动脉转换术', 42)], 'bod': [('左心室流出道', 9), ('肺动脉瓣', 18)], 'dis': [('动力性左心室流出道梗阻', 29)]}\n```\n****\n# 最初说明\n基于pytorch的bert_bilstm_crf中文命名实体识别\u003Cbr>\n要预先下载好预训练的bert模型，放在和该项目同级下的model_hub文件夹下，即：\u003Cbr>\nmodel_hub\u002Fbert-base-chinese\u002F\u003Cbr>\n相关下载地址：\u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fbert-base-chinese\u002Ftree\u002Fmain=\">bert-base-chinese\u003C\u002Fa>\u003Cbr>\n需要的是vocab.txt、config.json、pytorch_model.bin\u003Cbr>\n你也可以使用我已经训练好的模型，将其放在checkpoints下：\u003Cbr>\n链接：https:\u002F\u002Fpan.baidu.com\u002Fs\u002F1yIGnQ9I_4HAfQSqHod-hMQ \u003Cbr>\n提取码：4j47\u003Cbr>\n里面有四种模型对应的model.pt\u003Cbr>\n\n**后面重构了代码，不要使用上面的保存的模型了，自己训练个。**\n\n# 目录结构\n--checkpoints：模型保存的位置\u003Cbr>\n--data：数据位置\u003Cbr>\n--|--cner：数据集名称\u003Cbr>\n--|--|--raw_data：原始数据存储位置，里面有个process.py用于转换文本+标签json\u003Cbr>\n--|--|--mid_data：保存处理之后的json文件，标签等；\u003Cbr>\n--|--|--final_data：存储处理好之后可用的pickle文件\u003Cbr>\n--logs：日志存储位置\u003Cbr>\n--utils：辅助函数存储位置，包含了解码、评价指标、设置随机种子、设置日志等\u003Cbr>\n--config.py：配置文件\u003Cbr>\n--dataset.py：数据转换为pytorch的DataSet\u003Cbr>\n--main.py：主运行程序\u003Cbr>\n--main.sh：运行命令\u003Cbr>\n--bert_base_model.py：Bert模型\u003Cbr>\n--bert_ner_modelpy：利用Bert进行Ner的模型\u003Cbr>\n--preprocess.py：预处理，主要是处理数据然后转换成DataSet\u003Cbr>\n\n\n# 运行命令\n```python\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fbert-base-chinese\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--max_grad_norm=1 \\\n--warmup_proportion=0.1 \\\n--adam_epsilon=1e-8 \\\n--weight_decay=0.01 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3 \n```\n我们可以通过控制--use_lstm和--use_crf来切换使用bilstm或crf。\n\n# 结果\n# 训练、验证、测试和预测\n由于忘记保存其它测试和预测了，这里就只展示bert的。\n```python\n2021-08-05 16:19:12,787 - INFO - main.py - train - 52 - 【train】 epoch:2 359\u002F360 loss:0.0398\n2021-08-05 16:19:14,717 - INFO - main.py - train - 56 - [eval] loss:1.8444 precision=0.9484 recall=0.8732 f1_score=0.9093\n2021-08-05 16:32:20,751 - INFO - main.py - test - 130 -           \n             precision    recall  f1-score   support\n\n     PRO       0.86      0.63      0.73        19\n     ORG       0.94      0.91      0.92       543\n    CONT       1.00      1.00      1.00        33\n    RACE       1.00      0.93      0.97        15\n    NAME       0.99      0.93      0.96       110\n     EDU       0.98      0.94      0.96       109\n     LOC       0.00      0.00      0.00         2\n   TITLE       0.95      0.84      0.89       770\n\nmicro-f1       0.95      0.88      0.91      1601\n\n2021-08-05 16:32:20,752 - INFO - main.py - \u003Cmodule> - 218 - 虞兔良先生：1963年12月出生，汉族，中国国籍，无境外永久居留权，浙江绍兴人，中共党员，MBA，经济师。\n2021-08-05 16:32:22,892 - INFO - trainUtils.py - load_model_and_parallel - 96 - Load ckpt from .\u002Fcheckpoints\u002Fbert\u002Fmodel.pt\n2021-08-05 16:32:23,205 - INFO - trainUtils.py - load_model_and_parallel - 106 - Use single gpu in: ['0']\n2021-08-05 16:32:23,239 - INFO - main.py - predict - 156 - {'NAME': [('虞兔良', 0)], 'RACE': [('汉族', 17)], 'CONT': [('中国国籍', 20)], 'TITLE': [('中共党员', 40), ('经济师', 49)], 'EDU': [('MBA', 45)]}\n```\n## 验证集上对比\n| models | loss | precision | recall | f1_score |\n| :-----------: | :-----------: | :-----------: | :-----------: | :-----------: |\n|bert|1.8444 |0.9484 |0.8732 |0.9093 |\n|bert_bilstm|2.0856 |0.9540 |0.8670 |0.9084 |\n|bert_crf|26.9665 |0.9385 |0.8957 |0.9166 |\n|bert_bilstm_crf|30.8463 |0.9382 |0.8919 |0.9145 |\n\n以上训练的都是3个epoch。\n\n# 延伸：\n- 百度UIE通用信息抽取：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_uie_ner\n- 一种基于globalpointer的命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_GlobalPointer_Ner\n- 一种基于TPLinker_plus的命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_TPLinker_Plus_Ner\n- 一种one vs rest方法进行命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_OneVersusRest_Ner\n- 一种级联Bert用于命名实体识别，解决标签过多问题：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_Cascade_Bert_Ner\n- 一种多头选择Bert用于命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_Multi_Head_Selection_Ner\n- 中文命名实体识别最新进展：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fawesome-chinese-ner\n- 信息抽取三剑客：实体抽取、关系抽取、事件抽取：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fchinese_information_extraction\n- 一种基于机器阅读理解的命名实体识别：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002FBERT_MRC_NER_chinese\n- W2NER：命名实体识别最新sota：https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002FW2NER_predict","# pytorch_bert_bilstm_crf_ner 快速上手指南\n\n本工具基于 PyTorch、BERT 和 CRF 实现中文命名实体识别（NER），支持 BiLSTM、IDCNN 等多种结构，并提供数据增强、模型蒸馏及 ONNX 导出功能。\n\n## 1. 环境准备\n\n### 系统要求\n- **Python**: 推荐 3.6+\n- **操作系统**: Linux \u002F Windows \u002F macOS\n- **GPU**: 可选（用于加速训练），需安装对应版本的 CUDA\n\n### 前置依赖\n请确保已安装以下核心库（版本需严格匹配以避免报错）：\n- `pytorch` == 1.6.0 (或适配 PyTorch 2.0)\n- `transformers` == 4.5.0\n- `pytorch-crf` == 0.7.2\n- `numpy` == 1.22.4\n- `packaging` == 21.3\n\n> **国内加速建议**：安装依赖时推荐使用清华或阿里镜像源，例如：\n> `pip install -r requirements.txt -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple`\n\n## 2. 安装步骤\n\n### 2.1 克隆项目\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_bert_bilstm_crf_ner.git\ncd pytorch_bert_bilstm_crf_ner\n```\n\n### 2.2 安装依赖\n创建虚拟环境并安装所需包：\n```bash\npip install torch==1.6.0 transformers==4.5.0 pytorch-crf==0.7.2 numpy==1.22.4 packaging==21.3\n```\n*(注：若使用 PyTorch 2.0，可忽略 torch 版本限制，但需注意兼容性)*\n\n### 2.3 下载预训练模型\n从 Hugging Face 下载中文预训练模型（以 `chinese-bert-wwm-ext` 为例），存放至 `model_hub` 目录：\n```text\n--model_hub\n  --chinese-bert-wwm-ext\n    --vocab.txt\n    --config.json\n    --pytorch_model.bin\n```\n> **国内加速**：可通过 [Hugging Face 镜像站](https:\u002F\u002Fhf-mirror.com) 或国内 Gitee 镜像下载模型文件。\n\n### 2.4 准备数据\n以 CNER 数据集为例，构建如下目录结构：\n```text\n--data\n  --cner\n    --raw_data      # 放置原始数据\n    --mid_data      # 运行预处理后生成\n    --final_data    # 最终输入模型的数据\n```\n1. 将原始数据放入 `raw_data`。\n2. 运行 `preprocess.py`（需先在脚本中配置数据集名称和最大序列长度），生成 `mid_data` 和 `final_data`。\n\n## 3. 基本使用\n\n### 3.1 模型训练\n使用默认配置训练 BERT+CRF 模型（Windows 用户请将命令合并为一行，去除 `\\`）：\n\n```bash\npython main.py \\\n--bert_dir=\"..\u002Fmodel_hub\u002Fchinese-bert-wwm-ext\u002F\" \\\n--data_dir=\".\u002Fdata\u002Fcner\u002F\" \\\n--data_name=\"cner\" \\\n--model_name=\"bert\" \\\n--log_dir=\".\u002Flogs\u002F\" \\\n--output_dir=\".\u002Fcheckpoints\u002F\" \\\n--num_tags=33 \\\n--seed=123 \\\n--gpu_ids=\"0\" \\\n--max_seq_len=150 \\\n--lr=3e-5 \\\n--crf_lr=3e-2 \\\n--other_lr=3e-4 \\\n--train_batch_size=32 \\\n--train_epochs=3 \\\n--eval_batch_size=32 \\\n--lstm_hidden=128 \\\n--num_layers=1 \\\n--use_lstm=\"False\" \\\n--use_idcnn=\"False\" \\\n--use_crf=\"True\" \\\n--dropout_prob=0.3 \\\n--dropout=0.3\n```\n\n**关键参数说明：**\n- `--model_name`: 支持 `bert`, `electra`, `albert`, `bilstm`, `idcnn` 等。\n- `--use_lstm` \u002F `--use_idcnn`: 二者互斥，设为 `\"True\"` 启用对应结构。\n- `--use_crf`: 是否启用 CRF 层，默认为 `\"True\"`。\n\n### 3.2 模型预测\n训练完成后，使用 `predict.py` 进行单条或批量预测。需修改脚本内的 `args_path` 指向训练生成的配置文件路径。\n\n```bash\npython predict.py\n```\n\n### 3.3 进阶功能（可选）\n\n#### 导出 ONNX 模型\n加速推理（仅支持单条数据推理）：\n```bash\npython convert_onnx.py\n```\n*需额外安装：`pip install onnx onnxruntime`*\n\n#### 启动 API 服务\n在 `scripts` 目录下启动 HTTP 服务：\n- **Linux**: `.\u002Fstart_server.sh`\n- **Windows**: `python server.py`\n\n启动后访问 `http:\u002F\u002Fip地址:9277\u002F` 即可通过网页或接口提交文本进行识别。\n\n#### 数据增强\n对现有数据进行增强以提升效果：\n```bash\npython data_augment\u002Faug.py --data_name \"cner\" --text_repeat 2\n```\n运行后需在 `preprocess.py` 中设置 `use_aug=True` 再执行训练流程。","某医疗科技公司的数据团队正在构建智能病历分析系统，需要从海量非结构化的中文医生问诊记录中自动提取患者姓名、疾病名称、用药信息及就诊科室等关键实体。\n\n### 没有 pytorch_bert_bilstm_crf_ner 时\n- **识别精度低且边界模糊**：传统规则或简单模型难以处理中文复杂的语境，常将“高血压”误拆为“高”和“血压”，或无法区分同名不同义的词汇（如人名与药名）。\n- **长文本处理能力弱**：面对详细的病程描述，普通模型容易丢失前后文依赖关系，导致位于句子末尾的实体漏检。\n- **开发迭代周期长**：团队需从零搭建 BERT+BiLSTM+CRF 架构，手动调试标签编码（BIOES）、损失函数及超参数，耗时数周才能跑通基线。\n- **部署推理速度慢**：原始 PyTorch 模型在 CPU 环境下推理延迟高，无法满足临床实时辅助诊断的低延迟需求。\n\n### 使用 pytorch_bert_bilstm_crf_ner 后\n- **实体抽取精准度显著提升**：利用预训练的 Chinese-BERT-WWM-Ext 结合 CRF 层，完美解决了实体边界问题，对“复方甘草片”等复杂药名的识别准确率大幅提升。\n- **全局上下文理解增强**：BiLSTM 层有效捕捉长距离依赖，即使关键信息分散在长段落中，也能准确关联并提取出完整的实体片段。\n- **开箱即用加速落地**：直接复用其成熟的数据预处理脚本（preprocess.py）和训练指令，支持 CNER、Weibo 等多种数据集格式，将模型研发周期从数周缩短至几天。\n- **推理性能优化**：通过内置的 ONNX 转换功能，将模型推理时间从 0.71 秒降低至 0.46 秒，成功在低成本 CPU 服务器上实现了高效的批量病历处理。\n\npytorch_bert_bilstm_crf_ner 通过集成先进的深度学习架构与工程化优化，将高难度的中文命名实体识别任务转化为高效、可落地的标准化流程。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftaishan1994_pytorch_bert_bilstm_crf_ner_925a2efa.png","taishan1994","西西嘛呦","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Ftaishan1994_0a684805.jpg","NLP Scientist, Master of Wuhan University of Technology, Working on large language model, Worked as an algorithm engineer at  Intellifusion.",null,"shenzhen","https:\u002F\u002Fwww.cnblogs.com\u002Fxiximayou\u002F","https:\u002F\u002Fgithub.com\u002Ftaishan1994",[81,85,89],{"name":82,"color":83,"percentage":84},"Python","#3572A5",98.9,{"name":86,"color":87,"percentage":88},"HTML","#e34c26",1,{"name":90,"color":91,"percentage":92},"Shell","#89e051",0.1,594,84,"2026-04-14T03:47:20","Linux, Windows","非必需（支持 CPU 推理），若训练建议使用 NVIDIA GPU（命令行参数 --gpu_ids 默认为 \"0\"），未说明具体型号、显存大小及 CUDA 版本","未说明",{"notes":100,"python":101,"dependencies":102},"1. Windows 下运行训练命令时需将多行指令合并为一行（删除换行符 '\\'）。2. 必须严格安装指定版本的 numpy(1.22.4) 和 packaging(21.3) 以避免数组形状和版本解析错误。3. 需手动从 Hugging Face 下载预训练模型文件（如 chinese-bert-wwm-ext）并按特定目录结构存放。4. 原生 pytorch-crf 不支持 ONNX 导出，项目使用了 facebookresearch\u002Fpytext 中的 CRF 实现进行替代以支持 ONNX 转换。5. BiLSTM 和 IDCNN 模型组件不可同时启用，需通过参数二选一。","3.6 (可选，但依赖 numpy 1.22.4 通常要求 Python\u003C3.11)",[103,104,105,106,107,108,109,110],"pytorch==1.6.0","pytorch-crf==0.7.2","transformers==4.5.0","numpy==1.22.4","packaging==21.3","onnxruntime","onnx","tensorboardX",[35,112,113,15,14],"音频","视频",[115,116,117,118,119],"bert","crf","named-entity-recognition","ner","pytorch","2026-03-27T02:49:30.150509","2026-04-17T09:52:33.724977",[123,128,132,136,141,145,150,155],{"id":124,"question_zh":125,"answer_zh":126,"source_url":127},36518,"加载模型时报错 'Missing key(s)' 或 'Unexpected key(s)' 是什么原因？","这通常是因为代码配置与保存的模型结构不一致导致的。例如，代码中开启了 LSTM 和 CRF 层，但加载的模型权重是仅使用 BERT 训练的（或者相反）。请检查 main.py 中的配置参数（如 use_lstm, use_crf），确保它们与训练模型时的设置完全一致。如果只使用 BERT 模型，请确保没有加载包含 LSTM\u002FCRF 权重的文件，或者修改代码结构以匹配权重。","https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_bert_bilstm_crf_ner\u002Fissues\u002F2",{"id":129,"question_zh":130,"answer_zh":131,"source_url":127},36519,"预测时报错 'Boolean value of Tensor with more than one value is ambiguous' 如何解决？","这是因为在 decodeUtils.py 的 bioes_decode 方法中，传入的 decode_tokens 是一个张量（Tensor），不能直接用 if 语句判断等于 0。需要将其转换为一维数组或列表。解决方法是打印查看 decode_tokens 的类型，并将其转换为 list 或 numpy 数组后再进行索引判断，例如确保传入的是类似 [0,1,2,2,3,0,0] 的一维数组格式。",{"id":133,"question_zh":134,"answer_zh":135,"source_url":127},36520,"运行报错 'FileNotFoundError: No such file or directory: .\u002Fcheckpoints\u002F...\u002Fmodel.pt' 怎么办？","这个错误表示指定路径下找不到模型文件。原因通常有两点：1. 路径错误：Windows 和 Linux 的路径分隔符不同，建议将相对路径改为绝对路径尝试；2. 模型未训练：checkpoints 文件夹为空是因为尚未执行训练代码。请检查 main.py，确保取消注释了训练代码（如 bertForNer.train()），先运行训练生成模型文件后，再进行预测或测试。",{"id":137,"question_zh":138,"answer_zh":139,"source_url":140},36521,"训练或预测时报错 'Expected tensor ... to have scalar type Long; but got torch.cuda.IntTensor' 如何修复？","这是数据类型不匹配问题，Embedding 层需要 Long 类型的索引，但输入的是 Int 类型。请在 predict 部分的数据预处理代码中，显式地将 attention_mask 或其他输入张量转换为 long 类型。修改代码如下：attention_masks = torch.from_numpy(np.array(encode_dict['attention_mask'])).long().unsqueeze(0).to(device)。","https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_bert_bilstm_crf_ner\u002Fissues\u002F36",{"id":142,"question_zh":143,"answer_zh":144,"source_url":140},36522,"遇到环境兼容性问题导致训练报错（如高版本 PyTorch\u002FTransformers）怎么办？","该项目可能对依赖库的版本敏感。如果使用的是较高版本的 PyTorch 或 Transformers 出现未知错误，建议严格按照项目要求的环境版本进行安装。可以尝试降低 PyTorch 和 transformers 的版本至作者推荐的稳定版本，通常能解决此类兼容性导致的训练中断或评估失败问题。",{"id":146,"question_zh":147,"answer_zh":148,"source_url":149},36523,"代码中出现 'RuntimeError: stack expects a non-empty TensorList' 或数据维度不一致报错如何解决？","这通常发生在 batch_size 为 1 或数据处理不当时。对于 numpy 拼接报错（axis=0 维度不一致），是因为当某个 batch 只有一条数据时，数组自动降维。解决方案是修改数据处理逻辑，强制保持二维数组结构，或者直接注释掉\u002F删除导致问题的转换代码（如 batch_output = np.array(batch_output)），具体视上下文而定，维护者建议直接删除该非必要转换行。","https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_bert_bilstm_crf_ner\u002Fissues\u002F30",{"id":151,"question_zh":152,"answer_zh":153,"source_url":154},36524,"报错 'AssertionError: pretrained bert file does not exist' 是什么意思？","这表示程序在指定的 bert_dir 路径下找不到预训练的 BERT 模型文件（如 pytorch_model.bin 或 config.json）。请检查命令行参数或配置文件中的 bert_dir 路径是否正确，确保该目录下确实存放了完整的预训练模型文件。如果是相对路径，请确认当前工作目录是否正确，建议改用绝对路径。","https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_bert_bilstm_crf_ner\u002Fissues\u002F33",{"id":156,"question_zh":157,"answer_zh":158,"source_url":159},36525,"max_seq_len 参数应该如何设置？","max_seq_len 应根据数据集的平均句子长度来设定。如果设置过短会截断长句信息，过长则会增加计算负担并引入过多 padding。建议先统计训练集中句子长度的分布，取一个覆盖大多数样本的长度值（例如 70 或 128），并在实验中微调以获得最佳效果。","https:\u002F\u002Fgithub.com\u002Ftaishan1994\u002Fpytorch_bert_bilstm_crf_ner\u002Fissues\u002F27",[]]