写在前面

本次的需求是:通过预训练好的Bert模型,得到不同语境下,不同句子的句向量。相比于word2vec、glove这种静态词向量,会含有更丰富的语义,并能解决不同场景不同意思的问题。
建议大家先看Bert原论文(看之前最好懂得ELMo,一定要懂transformer),再结合这个博客(墙裂推荐)

开始

本次记录一共分成以下四步:

  1. 安装transformer包
  2. 导入BertTokenizerBertModel
  3. 将要输入的句子修改为Bert要求的输入形式
  4. 输入Bert模型,得到token向量

安装transformer包

pip install transformer

导入BertTokenizer和BertModel

首先,去huggingface下载你要的预训练模型,我选择的是bert-base-chinesem。需要下载的文件包括:模型bin文件、vocab.txt和config.json。

其次,利用以下代码即可导入BertTokenizer和BertModel。

from transformers import BertModel, BertTokenizer, BertConfigtokenizer = BertTokenizer.from_pretrained('./model/dl_model/bert')
model = BertModel.from_pretrained('./model/dl_model/bert',)

注意,传入的参数是包含模型所有文件的目录名。其中vocab文件的文件名必须是vocab.txt文件名,模型文件名必须是pytorch_model.bin,配置文件名必须是config.json,这样导入才不会出错。

修改输入形式

Bert的输入要有三个向量:(1)input_ids (2)token_type_ids (3)attention_mask。这三个向量可以通过一行代码获得:

sentenceA = '等潮水退去,就知道谁没穿裤子'
text_dict = tokenizer.encode_plus(sentenceA, add_special_tokens=True, return_attention_mask=True)

输入Bert模型,得到句向量

配置好输入格式后,就可以输入模型里了。在此之前,由于模型对三个输入向量的维度要求为(batch, seq_len) ,因此要对刚刚得到的text_dict中的三个向量进行升维,之后再输入模型中。

input_ids = torch.tensor(text_dict['input_ids']).unsqueeze(0)
token_type_ids = torch.tensor(text_dict['token_type_ids']).unsqueeze(0)
attention_mask = torch.tensor(text_dict['attention_mask']).unsqueeze(0)res = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)

res是一个包含2个元素的tuple(根据config的不同,返回的元素个数也不同),在这里,一个是sequnce_output(对应下面的last_hidden_state),一个是pooler_output。关于这该函数返回的向量,在源码中有解释:

    Return::obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):Sequence of hidden-states at the output of the last layer of the model.pooler_output (:obj:`torch.FloatTensor`: of shape :obj:`(batch_size, hidden_size)`):Last layer hidden-state of the first token of the sequence (classification token)further processed by a Linear layer and a Tanh activation function. The Linearlayer weights are trained from the next sentence prediction (classification)objective during pre-training.This output is usually *not* a good summaryof the semantic content of the input, you're often better with averaging or poolingthe sequence of hidden-states for the whole input sequence.hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)of shape :obj:`(batch_size, sequence_length, hidden_size)`.Hidden-states of the model at the output of each layer plus the initial embedding outputs.attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.Attentions weights after the attention softmax, used to compute the weighted average in the self-attentionheads.

看过BERT原文,就能知道各个返回值的意思了。另外,这边有一篇博文有介绍这些返回值。

通过res[0].detach().squeeze(0) # (seq_len, embed)即可拿到该句话的每个字的embedding了。对于这个embedding呢,我是这么理解的,bert是对于每个token(中文里就是字)都能拿到一个embedding。给定一个句子(30个字),可以获得每个字在这句话(这个语境下)的embedding,则30个字的embedding的池化代表这个句子的语义信息(上面的源码中也有提到)。若想获取句子中一个词的词向量,则在这个序列的token embedding中的取组成词的字所在的token embedding,经过池化后就是词向量。

Pytorch中使用Bert预训练模型,并给定句子得到对应的向量相关推荐

  1. Pytorch:NLP 迁移学习、NLP中的标准数据集、NLP中的常用预训练模型、加载和使用预训练模型、huggingface的transfomers微调脚本文件

    日萌社 人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新) run_glue.py微调脚本代码 python命令执行run ...

  2. 使用Bert预训练模型进行中文文本分类(基于pytorch)

    前言 最近在做一个关于图书系统的项目,需要先对图书进行分类,想到Bert模型是有中文文本分类功能的,于是打算使用Bert模型进行预训练和实现下游文本分类任务 数据预处理 2.1 输入介绍 在选择数据集 ...

  3. Pytorch——BERT 预训练模型及文本分类(情感分类)

    BERT 预训练模型及文本分类 介绍 如果你关注自然语言处理技术的发展,那你一定听说过 BERT,它的诞生对自然语言处理领域具有着里程碑式的意义.本次试验将介绍 BERT 的模型结构,以及将其应用于文 ...

  4. 刷新中文阅读理解水平,哈工大讯飞联合发布基于全词覆盖中文BERT预训练模型...

    作者 | HFL 来源 | 哈工大讯飞联合实验室(ID:rgznai100) 为了进一步促进中文自然语言处理的研究发展,哈工大讯飞联合实验室发布基于全词覆盖(Whole Word Masking)的中 ...

  5. word2vec模型评估_干货 | NLP中的十个预训练模型

    Word2vec, Fasttext, Glove, Elmo, Bert, Flair pre-train Word Embedding源码+数据Github网址:https://github.co ...

  6. resnet预训练模型_干货 | NLP中的十个预训练模型

    Word2vec Fasttext ULMFit Glove Cove ELMO GPT1.0 GPT2.0 BERT Flair Embedding 一.Word2vec 1.word2vec种语言 ...

  7. BERT预训练模型的使用

    当下NLP中流行的预训练模型 BERT GPT GPT-2 Transformer-XL XLNet XLM RoBERTa DistilBERT ALBERT T5 XLM-RoBERTa BERT ...

  8. 如何下载和在本地使用Bert预训练模型

    bert 预训练模型的下载有许多方式,比如从github官网上下载(官网下载的是tensorflow版本的),还可以从源码中找到下载链接,然后手动下载,最后还可以从huggingface中下载. 关于 ...

  9. 金融领域首个开源中文BERT预训练模型,熵简科技推出FinBERT 1.0

    出品 | AI科技大本营 头图 | CSDN付费下载于东方IC 为了促进自然语言处理技术在金融科技领域的应用和发展,熵简科技 AI Lab 近期开源了基于 BERT 架构的金融领域预训练语言模型 Fi ...

最新文章

  1. 【UVALive 4642】Malfatti Circles(圆,二分)
  2. ABAP ALV检查单元格更新数据
  3. Android 5.0+高级动画开发 矢量图动画 轨迹动画 路径变换
  4. Boost:不受约束的集合bimap的测试程序
  5. 【Tools】vim YouCompleteMe自动补全配置与使用
  6. mugen4g补丁如何使用_《守望先锋联赛》宣布采用英雄池机制及游戏补丁更新方式详解...
  7. java 开源论坛框架/java web 论坛框架
  8. 服务器appcrash的问题怎么修复,ghost win7出现appcrash的问题怎么修复
  9. Codesys电子凸轮功能的设计与可视化仿真
  10. 最简单的 UE 4 C++ 教程 —— 扫描多线轨迹【十六】
  11. iPhone 电池容量怎么算?
  12. chrome浏览器 在线打开预览pdf文件,而不是下载文件。
  13. 使用opencv和python实现图像的智能处理pdf_机器学习:基于OpenCV和Python的智能图像处理...
  14. 万年历 java程序_用Java编程输出万年历的功能实现
  15. 数据分析实战之数据可视化
  16. oracle分页查询中的page,用简单的例子解释Oracle分页查询
  17. Android获取视频缩略图
  18. [533]python获取微信好友头像生成点阵图片
  19. LeetCode||有效的字母异位词(排列)--给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词
  20. 英国工人手机上网欠巨债 收到2.7万英镑帐单

热门文章

  1. 香烟(烟屁股可以做烟)
  2. 黑客常用入侵方式(12种)
  3. hdu 1172(java版本)
  4. 一文了解 Nginx 反向代理与 conf 原理「技术干货分享」
  5. Pytorch lstm中batch_first 参数理解使用
  6. OVER(PARTITION BY)高级查询
  7. ShowMore – 免费易用的在线录屏工具(可实时添加标注)
  8. Python 防止分母为零
  9. 国际商业美术设计师阿里云开发首页
  10. 微信小程序授权登录获取用户名和昵称