当前位置: 移动技术网 > IT编程>脚本编程>Python > Pytorch中使用Bert预训练模型,并给定句子得到对应的向量

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

2020年07月20日  | 移动技术网IT编程  | 我要评论

写在前面

本次的需求是:通过预训练好的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, BertConfig

tokenizer = 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 Linear
            layer weights are trained from the next sentence prediction (classification)
            objective during pre-training.

            This output is usually *not* a good summary
            of the semantic content of the input, you're often better with averaging or pooling
            the 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-attention
            heads.

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

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

本文地址:https://blog.csdn.net/qq_33812659/article/details/107437373

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网