Python 从BERT获取嵌入查找结果
在将令牌传递给BERT之前,我想对它们的嵌入(嵌入查找层的结果)执行一些处理。允许我们使用以下方式访问嵌入查找的输出:Python 从BERT获取嵌入查找结果,python,tensorflow,nlp,huggingface-transformers,bert-language-model,Python,Tensorflow,Nlp,Huggingface Transformers,Bert Language Model,在将令牌传递给BERT之前,我想对它们的嵌入(嵌入查找层的结果)执行一些处理。允许我们使用以下方式访问嵌入查找的输出: import tensorflow as tf from transformers import BertConfig, BertTokenizer, TFBertModel bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') input_ids = tf.constant(bert_tok
import tensorflow as tf
from transformers import BertConfig, BertTokenizer, TFBertModel
bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
input_ids = tf.constant(bert_tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :]
attention_mask = tf.stack([tf.ones(shape=(len(sent),)) for sent in input_ids])
token_type_ids = tf.stack([tf.ones(shape=(len(sent),)) for sent in input_ids])
config = BertConfig.from_pretrained('bert-base-uncased', output_hidden_states=True)
bert_model = TFBertModel.from_pretrained('bert-base-uncased', config=config)
result = bert_model(inputs={'input_ids': input_ids,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids})
inputs_embeds = result[-1][0] # output of embedding lookup
随后,可以处理输入\u嵌入
,然后使用以下方法将其作为输入发送到同一模型:
inputs_embeds = process(inputs_embeds) # some processing on inputs_embeds done here (dimensions kept the same)
result = bert_model(inputs={'inputs_embeds': inputs_embeds,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids})
output = result[0]
其中,
output
现在包含修改输入的BERT输出。但是,这需要两次完全通过。我不想一直运行BERT来执行嵌入查找,我只想得到嵌入查找层的输出这是否可能,如果可能,如何实现?事实上,将第一个输出结果[-1][0]
视为嵌入查找的结果是不正确的。原始嵌入查找由以下公式给出:
embeddings = bert_model.bert.get_input_embeddings()
word_embeddings = embeddings.word_embeddings
inputs_embeds = tf.gather(word_embeddings, input_ids)
而结果[-1][0]
给出了嵌入查找以及位置嵌入和令牌类型嵌入。上述代码不需要完全通过BERT,并且可以在将结果馈送到BERT的其余层之前对其进行处理
编辑:要获得将位置和令牌类型嵌入添加到任意输入的结果,可以使用:
full_embeddings = embeddings(inputs=[None, None, token_type_ids, inputs_embeds])
这里,嵌入
对象的调用
方法接受一个列表,该列表被馈送到\u嵌入
方法中。第一个值是input\u id
,第二个值是position\u id
,第三个值是token\u type\u id
,第四个值是input\u embedded
。(有关更多详细信息,请参阅。)如果一个输入中有多个句子,则可能需要设置位置\u id