一、簡要說明
Bert火遍了2019,不少修行者躍躍欲試,然而訓練bert模型是一次很昂貴的過程,想簡單地先享受一下成果變得有些困難。幸而google已發布了一些預訓練好的模型,修行者可以通過一些捷徑輕松的使用bert模型構建自己的NLP應用,詳細可參考
https://github.com/google-research/bert#pre-trained-models
https://github.com/hanxiao/bert-as-service
本文將對文本句子進行向量編碼,通過文本相似度計算來說明其使用過程.
二、使用方式
bert-as-service的總體架構如下:
1、bert模型部署,是為服務端
2、bert請求調用服務,是為客戶端
使用方式如下:
1、環境準備
pip install bert-serving-server
pip install bert-serving-client
2、預訓練的模型下載
前往https://github.com/google-research/bert#pre-trained-models選擇模型(本文選擇中文模型)下載并解壓.
3、啟動bert-serving-server
命令行輸入
bert-serving-start -model_dir 模型解壓路徑
4、客戶端代碼使用
# 導入bert客戶端
from bert_serving.client import BertClient
import numpy as np
class SimilarModel:
def __init__(self):
# ip默認為本地模式,如果bert服務部署在其他服務器上,修改為對應ip
self.bert_client = BertClient(ip='192.168.x.x')
def close_bert(self):
self.bert_client .close()
def get_sentence_vec(self,sentence):
'''
根據bert獲取句子向量
:param sentence:
:return:
'''
return self.bert_client .encode([sentence])[0]
def cos_similar(self,sen_a_vec, sen_b_vec):
'''
計算兩個句子的余弦相似度
:param sen_a_vec:
:param sen_b_vec:
:return:
'''
vector_a = np.mat(sen_a_vec)
vector_b = np.mat(sen_b_vec)
num = float(vector_a * vector_b.T)
denom = np.linalg.norm(vector_a) * np.linalg.norm(vector_b)
cos = num / denom
return cos
if __name__=='__main__':
# 從候選集condinates 中選出與sentence_a 最相近的句子
condinates = ['為什么天空是蔚藍色的','太空為什么是黑的?','天空怎么是藍色的','明天去爬山如何']
sentence_a = '天空為什么是藍色的'
bert_client = SimilarModel()
max_cos_similar = 0
most_similar_sentence = ''
for sentence_b in condinates:
sentence_a_vec = bert_client .get_sentence_vec(sentence_a)
sentence_b_vec = bert_client .get_sentence_vec(sentence_b)
cos_similar = bert_client .cos_similar(sentence_a_vec,sentence_b_vec)
if cos_similar > max_cos_similar:
max_cos_similar = cos_similar
most_similar_sentence = sentence_b
print('最相似的句子:',most_similar_sentence)
bert_client .close_bert()
# 為什么天空是蔚藍色的