0 引言

BERT作为当今NLP中性能一流的模型,其应用广泛。bert_serving是便捷的获取句向量或词向量的工具。
本文将详细介绍bert_serving的安装、使用、参数。
因为bert_serving依赖于tensorflow,但是tensorflow2.0以后不支持bert_serving,而且python3.9以上的版本也安装不了tensorflow1.0版本,所以需要从源头上来解决这个问题。

1 安装

1.1 版本要求

因为引言中提到的问题,所以如果想安装和使用顺利,按着以下的版本来配置才会万无一失。ps:tensorflow的版本问题真的很让人头疼!
(1)Python = 3.5
(2)Tensorflow = 1.10
(3)numpy = 1.18.5
(4)不支持Python2!!!
(5)不支持tensorflow2.0!!!

1.2 汉语模型准备

bert训练好的模型chinese_L-12_H-768_A-12:
点击下载

1.3 Anaconda创建python3.5的虚拟环境并激活

创建python3.5环境

conda create -n python35 python3.5

激活

activate python35

1.4 安装tesorflow1.10

在python3.5的环境下安装tensorflow1.10

conda install tensorflow=1.10

1.5 安装bert-serving

pip install bert-serving-server  # server
pip install bert-serving-client  # client, independent of `bert-serving-server`

1.6 检查环境中的numpy版本

检查numpy版本是否是1.18.5,版本不对的话调用bert-serving时会报错。

2 使用

2.1 命令启动方式

1.cd到bert-serving-start.exe路径下
2.

bert-serving-start -pooling_strategy NONE -model_dir /Users/bj.develop.intern4/chinese_L-12_H-768_A-12 -max_seq_len 60

2.2 脚本启动方式

from bert_serving.server.helper import get_args_parser
from bert_serving.server import BertServer
args = get_args_parser().parse_args(['-model_dir', '/Users/bj.develop.intern4/chinese_L-12_H-768_A-12',
                                     '-pooling_strategy', 'NONE',
                                     '-max_seq_len','60'])

server = BertServer(args)
server.start()

2.3 调用

from bert_serving.client import BertClient
bc = BertClient(ip='localhost')
test=bc.encode(['你好','bert'])

3 参数详解

参数说明
-model_dir预训练模型的路径
-num_worker线程数,表示同时可以处理多少个并发请求
-pooling_strategy默认是句向量;-pooling_strategy NONE是词向量
-max_seq_len句子最大长度
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐