应用场景:QA对话系统|检索系统
任务: 希望能够在数据库中找到与用户问题相似的【句子对|词语】,然后把答案返回给用户。这篇就是要解决这个问题的。
方法: 下面提供两个方法,一个是基于google 开源的bert,另一个是基于pytorch-transformer
BERT的全称是Bidirectional Encoder Representation from Transformers,是Google2018年提出的预训练模型,即双向Transformer的Encoder,因为decoder是不能获要预测的信息的。模型的主要创新点都在pre-train方法上,即用了Masked LM和Next Sentence Prediction两种方法分别捕捉词语和句子级别的representation。
文章简介引用自: http://mantchs.com/2020/03/14/Introduction-NLP/bert_service/
关于 BERT 的原理知识请访问: http://mantchs.com/2019/09/28/NLP/BERT/
下面介绍一个封装好的 BERT 工具,利用该工具能够快速的得到词向量表示。该工具的名称叫做: bert-as-service,从名称就可以看出作者是把 BERT 作为一种服务了,只要调用该服务就能够得到我们想要的向量表示,得到向量以后,就可以通过余弦相似度的计算公式计算向量之间的相似度。
bert-as-service 源码详见: https://github.com/hanxiao/bert-as-service
bert-as-service 使用文档: https://bert-as-service.readthedocs.io/en/latest/index.html
步骤如下:
环境要求:
Python版本 >= 3.5,Tensorflow版本 >= 1.10
(本人环境,Python = 3.7 Tensorflow = 1.13.1)
安装服务端和客户端
pip install -U bert-serving-server bert-serving-client
下载预训练模型
Google AI发布的经过预训练的BERT模型。这里我们下载 BERT-Base, Chinese,12-layer, 768-hidden, 12-heads, 110M parameters。
链接:https://pan.baidu.com/s/1jJudiTj__vbFb0WkEQUxWw 密码:mf4p
启动服务
解压缩后,运行如下命令进行启动,目录换成解压后的路径。(-num_worker指定使用多少个CPU)
运行
bert-serving-start -model_dir /Users/mantch/Downloads/chinese_L-12_H-768_A-12 -num_worker=4
如果显示以下信息就表示可以使用了
I:WORKER-0:[__i:gen:559]:ready and listening!
I:WORKER-3:[__i:gen:559]:ready and listening!
I:WORKER-1:[__i:gen:559]:ready and listening!
I:WORKER-2:[__i:gen:559]:ready and listening!
I:VENTILATOR:[__i:_ru:164]:all set, ready to serve request!
3.运行项目:
from service.client import BertClient
bc = BertClient()
bc.encode(['你好', '成都'])
由于本人没有GPU的前提下测试了这个功能,所以另外分享多一个基于CPU版本的github(没有GPU运行以上可能会报错)
https://github.com/zhangbo2008/bert_wordEmbed
以上就是bert-as-service的应用了
import torch
from pytorch_transformers import BertTokenizer,BertModel
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
from tqdm import tqdm
import fool
tokenizer = BertTokenizer.from_pretrained('./bert_pretrain')
model = BertModel.from_pretrained('./bert_pretrain')
# input_ids = torch.tensor(tokenizer.batch_encode_plus(["凤梨", "菠萝", "苹果", "百香果"], pad_to_max_length=True)["input_ids"])
def get_embedding(bidtokes):
input_ids = torch.tensor(tokenizer.encode(bidtokes)).unsqueeze(0) # Batch size 1
outputs = model(input_ids)
# last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
sequence_output = outputs[0]
pooled_output = outputs[1]
# print(sequence_output)
# print(sequence_output.shape) ## 字向量
# print(pooled_output.shape) ## 句向量
return pooled_output.cpu().detach().numpy()
if __name__ == '__main__':
bidwords = ['输入你的词']
print(bidwords.__len__())
query_word = '外滩'
words, ners = fool.analysis(query_word)
ner_item = ners[0][0][3]
get_your_ = get_embedding(ner_item)
dict_sim = {}
for i in tqdm(bidwords):
emb_i = get_embedding(i)
dict_sim[i] = cosine_similarity(get_your_,emb_i)
dict_sim_ = sorted(dict_sim.items(), key=lambda item: item[1], reverse=True)
print(query_word)
for item in dict_sim_[:10]:
print('和' + item[0] + '的向量相似度:', item[1])