【NLP】使用bert
# 参考 https://blog.csdn.net/luoyexuge/article/details/84939755 小做改动
需要:
github上下载bert的代码:https://github.com/google-research/bert
下载google训练好的中文语料模型:https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip
使用:
使用bert,其实是使用几个checkpoint(ckpt)文件。上面下载的zip是google训练好的bert,我们可以在那个zip内的ckpt文件基础上继续训练,获得更贴近具体任务的ckpt文件。
如果是直接使用训练好的ckpt文件(就是bert模型),只需如下代码,定义model,获得model的值
from bert import modeling
# 使用数据加载BertModel,获取对应的字embedding
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings
)
# 获取对应的embedding 输入数据[batch_size, seq_length, embedding_size]
embedding = model.get_sequence_output()
这里的bert_config 是之前定义的bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file);输入是input_ids, input_mask, segment_ids三个向量;还有两个设置is_training(False), use_one_hot_embedding(False),这样的设置还有很多,这里只列举这两个。。
关于FLAGS,需要提到TensorFlow的flags,相当于配置运行变量,设置如下:
import tensorflow as tf flags = tf.flags
FLAGS = flags.FLAGS # 预训练的中文model路径和项目路径
bert_path = '/home/xiangbo_wang/xiangbo/NER/chinese_L-12_H-768_A-12/'
root_path = '/home/xiangbo_wang/xiangbo/NER/BERT-BiLSTM-CRF-NER' # 设置bert_config_file
flags.DEFINE_string(
"bert_config_file", os.path.join(bert_path, 'bert_config.json'),
"The config json file corresponding to the pre-trained BERT model."
)
关于输入的三个向量,具体内容可以参照之前的博客https://www.cnblogs.com/rucwxb/p/10277217.html

input_ids, segment_ids 分别是 token embedding, segment embedding
position embedding会自动生成
input_mask 是input中需要mask的位置,本来是随机取一部分,这里的做法是把全部输入位置都mask住。
获得输入的这三个向量的方式如下:
# 获得三个向量的函数
def inputs(vectors,maxlen=10):
length=len(vectors)
if length>=maxlen:
return vectors[0:maxlen],[1]*maxlen,[0]*maxlen
else:
input=vectors+[0]*(maxlen-length)
mask=[1]*length+[0]*(maxlen-length)
segment=[0]*maxlen
return input,mask,segment # 测试的句子
text = request.args.get('text')
vectors = [di.get("[CLS]")] + [di.get(i) if i in di else di.get("[UNK]") for i in list(text)] + [di.get("[SEP]")] # 转成1*maxlen的向量
input, mask, segment = inputs(vectors)
input_ids = np.reshape(np.array(input), [1, -1])
input_mask = np.reshape(np.array(mask), [1, -1])
segment_ids = np.reshape(np.array(segment), [1, -1])
最后是将变量输入模型获得最终的bert向量:
# 定义输入向量形状
input_ids_p=tf.placeholder(shape=[None,None],dtype=tf.int32,name="input_ids_p")
input_mask_p=tf.placeholder(shape=[None,None],dtype=tf.int32,name="input_mask_p")
segment_ids_p=tf.placeholder(shape=[None,None],dtype=tf.int32,name="segment_ids_p") model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids_p,
input_mask=input_mask_p,
token_type_ids=segment_ids_p,
use_one_hot_embeddings=use_one_hot_embeddings
) # 载入预训练模型
restore_saver = tf.train.Saver()
restore_saver.restore(sess, init_checkpoint) # 一个[batch_size, seq_length, embedding_size]大小的向量
embedding = tf.squeeze(model.get_sequence_output())
# 运行结果
ret=sess.run(embedding,feed_dict={"input_ids_p:0":input_ids,"input_mask_p:0":input_mask,"segment_ids_p:0":segment_ids})
完整可运行代码如下:
import tensorflow as tf
from bert import modeling
import collections
import os
import numpy as np
import json flags = tf.flags
FLAGS = flags.FLAGS
bert_path = '/home/xiangbo_wang/xiangbo/NER/chinese_L-12_H-768_A-12/' flags.DEFINE_string(
'bert_config_file', os.path.join(bert_path, 'bert_config.json'),
'config json file corresponding to the pre-trained BERT model.'
)
flags.DEFINE_string(
'bert_vocab_file', os.path.join(bert_path,'vocab.txt'),
'the config vocab file',
)
flags.DEFINE_string(
'init_checkpoint', os.path.join(bert_path,'bert_model.ckpt'),
'from a pre-trained BERT get an initial checkpoint',
)
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") def convert2Uni(text):
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8','ignore')
else:
print(type(text))
print('####################wrong################') def load_vocab(vocab_file):
vocab = collections.OrderedDict()
vocab.setdefault('blank', 2)
index = 0
with open(vocab_file) as reader:
# with tf.gfile.GFile(vocab_file, 'r') as reader:
while True:
tmp = reader.readline()
if not tmp:
break
token = convert2Uni(tmp)
token = token.strip()
vocab[token] = index
index+=1
return vocab def inputs(vectors, maxlen = 50):
length = len(vectors)
if length > maxlen:
return vectors[0:maxlen], [1]*maxlen, [0]*maxlen
else:
input = vectors+[0]*(maxlen-length)
mask = [1]*length + [0]*(maxlen-length)
segment = [0]*maxlen
return input, mask, segment def response_request(text):
vectors = [dictionary.get('[CLS]')] + [dictionary.get(i) if i in dictionary else dictionary.get('[UNK]') for i in list(text)] + [dictionary.get('[SEP]')]
input, mask, segment = inputs(vectors) input_ids = np.reshape(np.array(input), [1, -1])
input_mask = np.reshape(np.array(mask), [1, -1])
segment_ids = np.reshape(np.array(segment), [1, -1]) embedding = tf.squeeze(model.get_sequence_output())
rst = sess.run(embedding, feed_dict={'input_ids_p:0':input_ids, 'input_mask_p:0':input_mask, 'segment_ids_p:0':segment_ids}) return json.dumps(rst.tolist(), ensure_ascii=False) dictionary = load_vocab(FLAGS.bert_vocab_file)
init_checkpoint = FLAGS.init_checkpoint sess = tf.Session()
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) input_ids_p = tf.placeholder(shape=[None, None], dtype = tf.int32, name='input_ids_p')
input_mask_p = tf.placeholder(shape=[None, None], dtype = tf.int32, name='input_mask_p')
segment_ids_p = tf.placeholder(shape=[None, None], dtype = tf.int32, name='segment_ids_p') model = modeling.BertModel(
config = bert_config,
is_training = FLAGS.use_tpu,
input_ids = input_ids_p,
input_mask = input_mask_p,
token_type_ids = segment_ids_p,
use_one_hot_embeddings = FLAGS.use_tpu,
)
print('####################################')
restore_saver = tf.train.Saver()
restore_saver.restore(sess, init_checkpoint) print(response_request('我叫水奈樾。'))
【NLP】使用bert的更多相关文章
- NLP新秀 - Bert
目录 什么是Bert Bert能干什么? Bert和TensorFlow的关系 BERT的原理 Bert相关工具和服务 Bert的局限性和对应的解决方案 沉舟侧畔千帆过, 病树前头万木春. 今天介绍的 ...
- 最强NLP模型-BERT
简介: BERT,全称Bidirectional Encoder Representations from Transformers,是一个预训练的语言模型,可以通过它得到文本表示,然后用于下游任务, ...
- NLP采用Bert进行简单文本情感分类
参照当Bert遇上Kerashttps://spaces.ac.cn/archives/6736此示例准确率达到95.5%+ https://github.com/CyberZHG/keras-ber ...
- 语言模型预训练方法(ELMo、GPT和BERT)——自然语言处理(NLP)
1. 引言 在介绍论文之前,我将先简单介绍一些相关背景知识.首先是语言模型(Language Model),语言模型简单来说就是一串词序列的概率分布.具体来说,语言模型的作用是为一个长度为m的文本确定 ...
- 自然语言处理中的语言模型预训练方法(ELMo、GPT和BERT)
自然语言处理中的语言模型预训练方法(ELMo.GPT和BERT) 最近,在自然语言处理(NLP)领域中,使用语言模型预训练方法在多项NLP任务上都获得了不错的提升,广泛受到了各界的关注.就此,我将最近 ...
- Paper: 《Bert》
Bert: Bidirectional Encoder Representations from Transformers. 主要创新点:Masked LM 和 Next sentence predi ...
- BERT的几个可能的应用
BERT是谷歌公司于2018年11月发布的一款新模型,它一种预训练语言表示的方法,在大量文本语料(维基百科)上训练了一个通用的"语言理解"模型,然后用这个模型去执行想做的NLP ...
- 基于Bert的文本情感分类
详细代码已上传到github: click me Abstract: Sentiment classification is the process of analyzing and reaso ...
- 学习AI之NLP后对预训练语言模型——心得体会总结
一.学习NLP背景介绍: 从2019年4月份开始跟着华为云ModelArts实战营同学们一起进行了6期关于图像深度学习的学习,初步了解了关于图像标注.图像分类.物体检测,图像都目标物体检测等 ...
- 知识图谱辅助金融领域NLP任务
从人工智能学科诞生之初起,自然语言处理(NLP)就是人工智能核心的研究问题之一.NLP的重要性是毋庸置疑的,它能够实现以自然语言交流为特征的高级人机交互,使机器能“阅读”所有以文字形式记录的人类知识, ...
随机推荐
- Hive学习之路 (十七)Hive分析窗口函数(五) GROUPING SETS、GROUPING__ID、CUBE和ROLLUP
概述 GROUPING SETS,GROUPING__ID,CUBE,ROLLUP 这几个分析函数通常用于OLAP中,不能累加,而且需要根据不同维度上钻和下钻的指标统计,比如,分小时.天.月的UV数. ...
- [翻译]怎么写一个React组件库(一)
本文同步发布于知乎专栏 https://zhuanlan.zhihu.com/p/27401329,喜欢本文的就去知乎点个赞支持下吧- 引言 该系列文章将通过创建一个组件库来引导你学习如何构建自己的组 ...
- java web开发环境配置系列(一)安装JDK
在今天,读书有时是件“麻烦”事.它需要你付出时间,付出精力,还要付出一份心境.--仅以<java web开发环境配置系列>来祭奠那逝去的…… 1.下载JDK文件(http://www.or ...
- c++ 浅拷贝和深拷贝 指针和引用的区别 malloc(free)和new(delete)的区别 重载重写重定义
4.malloc(free)和new(delete)的区别 malloc()函数: 1.1 malloc的全称是memory allocation,中文叫动态内存分配. 原型:extern void ...
- Google 地图切片URL地址解析
一.Google地图切片的投影方式及瓦片索引机制 1.地图投影 Google地图采用的是Web墨卡托投影(如下图),为了方便忽略了两极变形较大的地区,把世界地图做成了一个边长等于赤道周长的正方形(赤道 ...
- 学习笔记——并行编程Parallel
Parallel 并行运算 参考资料:http://www.cnblogs.com/woxpp/p/3925094.html 1.并行运算 使用Parallel并行运算时,跟task很像,相当于tas ...
- CommonJS、AMD、CMD、NodeJs、RequireJS到底有什么联系?
JS中的模块规范(CommonJS,AMD,CMD),如果你听过js模块化这个东西,那么你就应该听过或CommonJS或AMD甚至是CMD这些规范,本文包括这三个规范的来源及对应的产物的原理. 一.C ...
- Linux基础命令之文件过滤及内容编辑处理(一)
. cat 功能是连接多个文件并且打印到屏幕输出,或重定向到指定的文件 五大功能: 1.查看文件内容 cat file.txt 2.合并文件内容 cat file1 file2>newfile3 ...
- PHP+MySQL实现海量数据导入导出的总结:is_numbric函数的坑
前段时间有个需求:将生产环境的部分数据转移到测试服务器进行测试.由于只需要导入特定账号的数据,我就想着将写个脚本,将数据组装成sql语句导出为sql文件,然后转移到测试服务器,导入到MySQL中.想象 ...
- 一个简单python爬虫的实现——爬取电影信息
最近在学习网络爬虫,完成了一个比较简单的python网络爬虫.首先为什么要用爬虫爬取信息呢,当然是因为要比人去收集更高效. 网络爬虫,可以理解为自动帮你在网络上收集数据的机器人. 网络爬虫简单可以大致 ...