Viv*_*ian 5 python nlp tensorflow bert-language-model huggingface-transformers
在通过 BERT 传递我的代币之前,我想对它们的嵌入(嵌入查找层的结果)执行一些处理。HuggingFace BERT TensorFlow 实现允许我们使用以下方式访问嵌入查找的输出:
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
Run Code Online (Sandbox Code Playgroud)
随后,可以inputs_embeds使用以下方法处理并将其作为输入发送到同一模型:
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]
Run Code Online (Sandbox Code Playgroud)
其中output现在包含修改输入的 BERT 输出。然而,这需要两次完整地通过 BERT。我不想一直运行 BERT 来执行嵌入查找,而是只想获取嵌入查找层的输出。这可能吗?如果可能的话,如何实现?
事实上,将第一个输出result[-1][0]视为嵌入查找的结果是不正确的。原始嵌入查找由下式给出:
embeddings = bert_model.bert.get_input_embeddings()
word_embeddings = embeddings.word_embeddings
inputs_embeds = tf.gather(word_embeddings, input_ids)
Run Code Online (Sandbox Code Playgroud)
whileresult[-1][0]给出嵌入查找以及位置嵌入和令牌类型嵌入。上述代码不需要完全通过 BERT,并且可以在将结果输入到 BERT 的其余层之前对其进行处理。
编辑:要获得将位置和令牌类型嵌入添加到任意位置的结果inputs_embeds,可以使用:
full_embeddings = embeddings(inputs=[None, None, token_type_ids, inputs_embeds])
Run Code Online (Sandbox Code Playgroud)
这里,对象call的方法embeddings接受一个输入到该方法中的列表_embeddings。第一个值是input_ids,第二个position_ids,第三个token_type_ids,第四个inputs_embeds。(请参阅此处了解更多详细信息。)如果一次输入中有多个句子,则可能需要设置position_ids.
| 归档时间: |
|
| 查看次数: |
2503 次 |
| 最近记录: |