BERT本质上是一个两段式的NLP模型。第一个阶段叫做:Pre-training,跟WordEmbedding类似,利用现有无标记的语料训练一个语言模型。第二个阶段叫做:Fine-tuning,利用预训练好的语言模型,完成具体的NLP下游任务。
Google已经投入了大规模的语料和昂贵的机器帮我们完成了Pre-training过程 bert中文模型链接:https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip
这里分两步介绍bert的使用:第一怎么使用bert的词向量,第二如何fine-tuning做其他任务。
传统的句向量采用词向量的方式求加权平均,无法解决一词多义对句子的影响,bert向量由于包含了上下文信息,从理论来看要比传统方法好。
1.下载bert项目 下载地址:https://github.com/google-research/bert
其中extract_features.py文件为bert句向量生成文件
image.png
2.下载中文预训练模型 下载地址:https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip 3.直接进行句向量特征提取 传入参数
--input_file="./data/input.txt"
--output_file="./data/output.jsonl"
--vocab_file="./chinese_L-12_H-768_A-12/vocab.txt"
--bert_config_file="./chinese_L-12_H-768_A-12/bert_config.json"
--init_checkpoint="./chinese_L-12_H-768_A-12/bert_model.ckpt"
--layers=-2
--max_seq_length=128
--batch_size=8
layers: 是输出那些层的参数,-1就是最后一层,-2是倒数第二层,一次类推
max_seq_length: 是最大句子长度,根据自己的任务配置。如果你的GPU内存比较小,可以减小这个值,节省存储
输出结果如下:
{"linex_index": 1, "features": [{"token": "[CLS]", "layers": [{"index": -1, "values": [-0.2844, 0.450896, 0.285645, 0.421341, 0.411053, ...
详细介绍文章:https://zhuanlan.zhihu.com/p/50582974 github地址:https://github.com/hanxiao/bert-as-service 1.安装bert-as-service
pip install bert-serving-server # server
pip install bert-serving-client # client, independent of `bert-serving-server`
2.下载中文预训练模型,前面提到过 3.开启服务
bert-serving-start -model_dir D:/数据/实体链接/bert相识度匹配/chinese_L-12_H-768_A-12 -num_worker=1
4.直接加载词向量
from bert_serving.client import BertClient
bc = BertClient()
bc.encode(["今天天气真好","我感冒了"])
输出:
array([[ 0.43153867, -0.22524145, 0.02924719, ..., -0.12929817,
0.3106631 , -0.1888775 ],
[ 0.6095807 , -0.2103941 , -0.20782037, ..., -0.24075384,
-0.25313932, -0.45011818]], dtype=float32)
地址:https://github.com/terrifyzhao/bert-utils
代码如下:
from bert.extrac_feature import BertVector
bv = BertVector()
bv.encode(['今天天气不错'])
输出:
[[ 1.21984698e-01 7.84057677e-02 -1.06496774e-01 -3.25891018e-01
4.94978607e-01 -4.69692767e-01 2.54333645e-01 -8.82656407e-03...
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有