sta*_*010 8 machine-learning pytorch bert-language-model huggingface-transformers
我正在使用 HuggingFace Transformers BERT 模型,我想使用 ormean函数计算句子中标记的摘要向量(也称为嵌入) max。复杂的是,有些标记是[PAD],所以我想在计算平均值或最大值时忽略这些标记的向量。
这是一个例子。我最初实例化 aBertTokenizer和 a BertModel:
import torch
import transformers
from transformers import AutoTokenizer, AutoModel
transformer_name = 'bert-base-uncased'
tokenizer = AutoTokenizer.from_pretrained(transformer_name, use_fast=True)
model = AutoModel.from_pretrained(transformer_name)
Run Code Online (Sandbox Code Playgroud)
然后,我将一些句子输入到分词器中,然后input_ids退出attention_mask。值得注意的是,attention_mask值 0 意味着该令牌是[PAD]我可以忽略的。
sentences = ['Deep learning is difficult yet very rewarding.',
'Deep learning is not easy.',
'But is rewarding if done right.']
tokenizer_result = tokenizer(sentences, max_length=32, padding=True, return_attention_mask=True, return_tensors='pt')
input_ids = tokenizer_result.input_ids
attention_mask = tokenizer_result.attention_mask
print(input_ids.shape) # torch.Size([3, 11])
print(input_ids)
# tensor([[ 101, 2784, 4083, 2003, 3697, 2664, 2200, 10377, 2075, 1012, 102],
# [ 101, 2784, 4083, 2003, 2025, 3733, 1012, 102, 0, 0, 0],
# [ 101, 2021, 2003, 10377, 2075, 2065, 2589, 2157, 1012, 102, 0]])
print(attention_mask.shape) # torch.Size([3, 11])
print(attention_mask)
# tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
# [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
现在,我调用 BERT 模型来获取 768-D 令牌嵌入(顶层隐藏状态)。
model_result = model(input_ids, attention_mask=attention_mask, return_dict=True)
token_embeddings = model_result.last_hidden_state
print(token_embeddings.shape) # torch.Size([3, 11, 768])
Run Code Online (Sandbox Code Playgroud)
所以此时,我有:
[PAD]。如何计算有效的非标记向量上的mean/ ?max[PAD]
我尝试使用注意蒙版作为蒙版,然后调用torch.max(),但我没有得到正确的尺寸:
masked_token_embeddings = token_embeddings[attention_mask==1]
print(masked_token_embeddings.shape) # torch.Size([29, 768] <-- WRONG. SHOULD BE [3, 11, 768]
pooled = torch.max(masked_token_embeddings, 1)
print(pooled.values.shape) # torch.Size([29]) <-- WRONG. SHOULD BE [3, 768]
Run Code Online (Sandbox Code Playgroud)
我真正想要的是形状为 [3, 768] 的张量。也就是说,这 3 个句子中的每一个都有一个 768-D 向量。
对于max,您可以乘以attention_mask:
pooled = torch.max((token_embeddings * attention_mask.unsqueeze(-1)), axis=1)
Run Code Online (Sandbox Code Playgroud)
对于mean,您可以沿轴求和并attention_mask沿该轴除:
mean_pooled = token_embeddings.sum(axis=1) / attention_mask.sum(axis=-1).unsqueeze(-1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4998 次 |
| 最近记录: |