{"id":13535304,"url":"https://github.com/Brokenwind/BertSimilarity","last_synced_at":"2025-04-02T01:30:33.160Z","repository":{"id":39366061,"uuid":"171440202","full_name":"Brokenwind/BertSimilarity","owner":"Brokenwind","description":"Computing similarity of two sentences with google's BERT algorithm。利用Bert计算句子相似度。语义相似度计算。文本相似度计算。","archived":false,"fork":false,"pushed_at":"2023-03-24T23:27:13.000Z","size":2897,"stargazers_count":495,"open_issues_count":10,"forks_count":69,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-11-02T23:32:47.738Z","etag":null,"topics":["bert","nlp","python","semantic","similarity","tensorflow"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Brokenwind.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-19T08:58:35.000Z","updated_at":"2024-10-12T03:56:00.000Z","dependencies_parsed_at":"2024-11-02T23:31:29.288Z","dependency_job_id":"6a803f7f-03fc-4aab-8dd0-31fb72952ce5","html_url":"https://github.com/Brokenwind/BertSimilarity","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Brokenwind%2FBertSimilarity","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Brokenwind%2FBertSimilarity/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Brokenwind%2FBertSimilarity/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Brokenwind%2FBertSimilarity/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Brokenwind","download_url":"https://codeload.github.com/Brokenwind/BertSimilarity/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246738381,"owners_count":20825775,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bert","nlp","python","semantic","similarity","tensorflow"],"created_at":"2024-08-01T08:00:53.100Z","updated_at":"2025-04-02T01:30:32.259Z","avatar_url":"https://github.com/Brokenwind.png","language":"Python","funding_links":[],"categories":["BERT Text Match:","Libraries and Tools","文本匹配 文本检索 文本相似度"],"sub_categories":["2023","其他_文本生成、文本对话"],"readme":"# BertSimilarity\n\n基于Google的BERT模型来进行语义相似度计算。代码基于tensorflow 1。\n\n## 1. 基本原理\n\n简单来说就是将需要计算的相似的两个句子先拼接在一起，然后通过Bert模型获取获取整体的编码信息，接着通过全连接层将维，输出相似和不相似的概率。\n\n\n## 1.1 模型结构\n\n模型结构如图所示：\n\n![](wiki/pictures/bert_similarity.png)\n\n### 1.1.1 数据预处理\n\n本文使用Bert模型计算相似度前，首先要对输入数据进行预处理，例如当要处理的文本是：\n\n```text\n如何得知关闭借呗   想永久关闭借呗\n```\n\n首先要将文本按token化，切分成字数组:\n\n```json\n[如 何 得 知 关 闭 借 呗]\n\n[想 永 久 关 闭 借 呗]\n```\n\n然后将两个切分后的句子，按照如下的方式拼接：\n\n```json\n[CLS] 如 何 得 知 关 闭 借 呗 [SEP] 想 永 久 关 闭 借 呗 [SEP]\n```\n\n拼接后句子中的[CLS]是一个特殊分隔符表示每个样本的开头，[SEP]是样本中每个句子的结束标记符。拼接后的样本长度是len(A)+len(B)+3，因为加上了[CLS]和[SEP]特殊标识符的，3指的是1个[CLS]和2个[SEP]。在模型中，会指定最大样本长度LEN，本次实验中指定的是30），也就处理后的样本长度和不能超过LEN，即\n\n```python\nlen(A) + len(B) + 3 \u003c= LEN\n```\n\n超出最大长度的部分会被截取。然后继续对输入数据进行处理，将内容数字化。将token数组转化为token的索引数组，所有的样本会被转化为固定长度（LEN）的索引数组。[CLS]的索引是101，[SEP]的索引是102，不够最大样本长度的部分补0。然后对输入进行mask操作，样本有效部分是1，无效部分是0，0表示在训练时不会被关注。再对两个句子进行分割，分割操作是通过一个数组来标记，属于第一个句子标记为0，属于第二个句子的标记为1，不足部分也填0。\n\n处理后结果如下图所示：\n\n![](wiki/pictures/similarity_data_process.png)\n\ninput_ids，input_mask，segment_ids都是Bert预训练模型需要的输入。\n\n### 1.1.2 Bert编码阶段\n\n**Bert预训练简介**\n\nBert模型结构如图所示：\n\n![](wiki/pictures/similarity_bert_model.png)\n\nBert没有使用word2vec进行词嵌入，而是直接在原始语料库上训练，并且在训练过程中同时进行两个预测任务，分别是遮蔽语言模型MLM（masked language model）任务和根据上一个句子预测下一个句子的任务。Bert使用MLM来解决单向局限，其随机地从输入中遮蔽一些词块，然后通过上下文语境来预测被遮蔽的词块。从Bert的双向Transformer结构中我们可以发现MLM任务并不只是从左到右进行预测，而是它融合了遮蔽词块左右两边的句子语境，充分利用两个方向的注意力机制。同时训练数据不需要人工标注，而是在训练之前随机产生训练数据，减少了由人工标注所带来的误差，只需要通过合适的方法，对现有语料中的句子进行随机的遮掩即可得到可以用来训练的语料。很多自然语言处理任务比如问答系统和自然语言推断任务都需要对两个句子之间关系进行理解，而这种理解并不能通过语言模型直接获得。在预训练任务中加入预测下一个句子的训练可以达到理解句子关系的目的，具体做法是随机替换一些句子，然后利用上一句进行预测下一句的真伪。\n\n**利用Bert对句子对进行编码**\n\n使用已经训练好的Bert模型对句子对进行编码时，因为Bert中双向Attention机制，两个句子会相互Attention，也就是通过训练会学到两个句子的相似程度。\n\n### 1.1.3 微调阶段\n\n将句子对通过Bert预训练模型计算之后，获取两个句子的的最终编码。并对其进行0.1的Dropout，主要是为了防止模型过拟合，Dropout后的结果后边接一层全连接层，全连接层的输出维度为2，然后通过softmax计算，得到相似和不相似的概率。\n\n## 2. 使用方式\n\n### 2.1 数据准备\n\n在使用前需要先下载Google预训练的Bert模型。\n\n下载地址 [https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip](https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip)\n\n下载完后，解压，然后将chinese_L-12_H-768_A-12文件夹复制到 data/pretrained_model/目录中\n\n### 2.2 运行说明\n\n为了方便执行，已经编写了Shell脚本，在linux机器上直接运行start.sh，根据提示输入对应的mode(train/eval/infer)即可。\n\n**2.2.1 训练阶段**\n\n```bash\ncd BertSimilarity/\nsh start.sh\n# 然后根据提示输入 train\n```\n\n执行效果:\n\n![](wiki/pictures/similarity_train.png)\n\n执行日志查看:\n\n```bash\ntail -f logs/similarity_train.log\n```\n\n如果没有机器进行训练，我这里已经训练好了一份参数文件:\n\n[点击此处获取参数文件](https://pan.baidu.com/s/19pR3PS8AVIPpKZAXPkHdSA)，提取码: fud8\n\n解压之后，model_output复制到项目根目录的data目录下边，然后就可以进行评价和测试\n\n**2.2.2 评价阶段**\n\n```bash\ncd BertSimilarity/\nsh start.sh\n# 然后根据提示输入 eval\n```\n\n执行效果:\n\n![](wiki/pictures/similarity_eval.png)\n\n执行日志查看:\n\n```bash\ntail -f logs/similarity_eval.log\n```\n\n评价结果：\n![](wiki/pictures/similarity_eval_1.png)\n\n\n\n**2.2.3 测试阶段**\n\n```bash\ncd BertSimilarity/\nsh start.sh\n# 然后根据提示输入 infer，待程序启动好之后，就可以分别输入两个句子，测试其相似程度\n```\n\n执行效果:\n\n![](wiki/pictures/similarity_infer.png)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBrokenwind%2FBertSimilarity","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBrokenwind%2FBertSimilarity","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBrokenwind%2FBertSimilarity/lists"}