鼎鼎大名的日技 Bert 算法相信大部分同学都听说过,它是急速Google推出的NLP领域“王炸级”预训练模型,其在NLP任务中刷新了多项记录,搭建草莓视频网址地址并取得state of the art的问答成绩。
但是搜索有很多深度学习的新手发现BERT模型并不好搭建,上手难度很高,引擎普通人可能要研究几天才能勉强搭建出一个模型。日技
没关系,急速今天我们介绍的搭建草莓视频网址地址这个模块,能让你在3分钟内基于BERT算法搭建一个问答搜索引擎。问答它就是搜索 bert-as-service 项目。这个开源项目,引擎能够让你基于多GPU机器快速搭建BERT服务(支持微调模型),日技并且能够让多个客户端并发使用。急速
1.准备
开始之前,搭建你要确保Python和pip已经成功安装在电脑上,如果没有,可以访问这篇文章:超详细Python安装指南
进行安装。
(可选1) 如果你用Python的目的是数据分析,可以直接安装Anaconda:Python数据分析与挖掘好帮手—Anaconda,它内置了Python和pip.
(可选2) 此外,推荐大家用VSCode编辑器,它有许多的优点:Python 编程的最好搭档—VSCode 详细指南。
请选择以下任一种方式输入命令安装依赖:
1. Windows 环境 打开 Cmd (开始-运行-CMD)。
2. MacOS 环境 打开 Terminal (command+空格输入Terminal)。
3. 如果你用的是 VSCode编辑器 或 Pycharm,可以直接使用界面下方的Terminal. pip install bert-serving-server # 服务端pip install bert-serving-client # 客户端请注意,服务端的版本要求:Python >= 3.5,Tensorflow >= 1.10 。
此外还要下载预训练好的BERT模型,在 https://github.com/hanxiao/bert-as-service#install 上可以下载。
也可在Python实用宝典后台回复 bert-as-service 下载这些预训练好的模型。
下载完成后,将 zip 文件解压到某个文件夹中,例如 /tmp/english_L-12_H-768_A-12/
2.Bert-as-service 基本使用
安装完成后,输入以下命令启动BERT服务:
bert-serving-start -model_dir /tmp/english_L-12_H-768_A-12/ -num_worker=4-num_worker=4 代表这将启动一个有四个worker的服务,意味着它最多可以处理四个并发请求。超过4个其他并发请求将在负载均衡器中排队等待处理。
下面显示了正确启动时服务器的样子:
现在你可以简单地对句子进行编码,如下所示:
from bert_serving.client importBertClient
bc = BertClient()
bc.encode([First do it, then do it right, then do it better])作为 BERT 的一个特性,你可以通过将它们与 |||(前后有空格)连接来获得一对句子的编码,例如
bc.encode([First do it ||| then do it right])远程使用 BERT 服务
你还可以在一台 (GPU) 机器上启动服务并从另一台 (CPU) 机器上调用它,如下所示:
# on another CPU machinefrom bert_serving.client importBertClient
bc = BertClient(ip=xx.xx.xx.xx) # ip address of the GPU machinebc.encode([First do it, then do it right, then do it better])3.搭建问答搜索引擎
我们将通过 bert-as-service 从FAQ 列表中找到与用户输入的问题最相似的问题,并返回相应的答案。
FAQ列表你也可以在 Python实用宝典后台回复 bert-as-service 下载。
首先,加载所有问题,并显示统计数据:
prefix_q = ##### **Q:** with open(README.md) asfp:
questions = [v.replace(prefix_q, ).strip() for v in fp if v.strip() andv.startswith(prefix_q)]
print(%d questions loaded, avg. len of %d % (len(questions), np.mean([len(d.split()) for d inquestions])))
# 33 questions loaded, avg. len of 9一共有33个问题被加载,平均长度是9.
然后使用预训练好的模型:uncased_L-12_H-768_A-12 启动一个Bert服务:
bert-serving-start -num_worker=1 -model_dir=/data/cips/data/lab/data/model/uncased_L-12_H-768_A-12接下来,将我们的问题编码为向量:
bc = BertClient(port=4000, port_out=4001)
doc_vecs = bc.encode(questions)最后,我们准备好接收用户的查询,并对现有问题执行简单的“模糊”搜索。
为此,每次有新查询到来时,我们将其编码为向量并计算其点积 doc_vecs然后对结果进行降序排序,返回前N个类似的问题:
while True:
query = input(your question:)
query_vec = bc.encode([query])[0]
# compute normalized dot product as score score = np.sum(query_vec * doc_vecs, axis=1) / np.linalg.norm(doc_vecs, axis=1)
topk_idx = np.argsort(score)[::-1][:topk]
for idx intopk_idx:
print(> %s\t%s % (score[idx], questions[idx]))完成!现在运行代码并输入你的查询,看看这个搜索引擎如何处理模糊匹配:
完整代码如下,一共23行代码(在后台回复关键词也能下载):
上滑查看完整代码
import numpy asnp
from bert_serving.client importBertClient
from termcolor importcolored
prefix_q = ##### **Q:** topk = 5with open(README.md) asfp:
questions = [v.replace(prefix_q, ).strip() for v in fp if v.strip() andv.startswith(prefix_q)]
print(%d questions loaded, avg. len of %d % (len(questions), np.mean([len(d.split()) for d inquestions])))
with BertClient(port=4000, port_out=4001) asbc:
doc_vecs = bc.encode(questions)
while True:
query = input(colored(your question: , green))
query_vec = bc.encode([query])[0]
# compute normalized dot product as score score = np.sum(query_vec * doc_vecs, axis=1) / np.linalg.norm(doc_vecs, axis=1)
topk_idx = np.argsort(score)[::-1][:topk]
print(top %d questions similar to "%s" % (topk, colored(query, green)))
for idx intopk_idx:
print(> %s\t%s % (colored(%.1f % score[idx], cyan), colored(questions[idx], yellow)))够简单吧?当然,这是一个基于预训练的Bert模型制造的一个简单QA搜索模型。
你还可以微调模型,让这个模型整体表现地更完美,你可以将自己的数据放到某个目录下,然后执行 run_classifier.py 对模型进行微调,比如这个例子:
https://github.com/google-research/bert#sentence-and-sentence-pair-classification-tasks
它还有许多别的用法,我们这里就不一一介绍了,大家可以前往官方文档学习:
https://github.com/hanxiao/bert-as-service
END
未闻 Code·知识星球开放啦!
一对一答疑爬虫相关问题
职业生涯咨询
面试经验分享
每周直播分享
......
未闻 Code·知识星球期待与你相见~
一二线大厂在职员工
十多年码龄的编程老鸟
国内外高校在读学生
中小学刚刚入门的新人
在“未闻 Code技术交流群”等你来!
入群方式:添加微信“mekingname”,备注“粉丝群”(谢绝广告党,非诚勿扰!)
(责任编辑:综合)