问题描述
当我尝试使用 bio_clinical bert 获取句子的词嵌入时,对于 8 个词的句子,我得到了 11 个标记 id(+开始和结束),因为“嵌入”是词汇外的词/标记,即分为em
、bed
、ding
、s
。
我想知道除了对这些向量求均值之外,是否还有其他有意义的聚合策略。
from transformers import AutoTokenizer,AutoModel
# download and load model
tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
sentences = ['This framework generates embeddings for each input sentence']
#Tokenize sentences
encoded_input = tokenizer(sentences,padding=True,truncation=True,max_length=128,return_tensors='pt')
#Compute token embeddings
with torch.no_grad():
model_output = model(**encoded_input)
print(encoded_input['input_ids'].shape)
输出:
torch.Size([1,13])
for token in encoded_input['input_ids'][0]:
print(tokenizer.decode([token]))
输出:
[CLS]
this
framework
generates
em
##bed
##ding
##s
for
each
input
sentence
[SEP]
解决方法
据我所知,均值聚合是这里最常用的工具,实际上甚至有科学文献,凭经验表明它运作良好: Generalizing Word Embeddings using Bag of Subwords 由 Zhao、Mudgal 和 Liang 撰写。公式 1 也准确描述了您的提议。
理论上您可以采用的一种替代方法是对整个输入进行平均聚合,本质上是对所有单词进行“上下文预测”(可能除了“embeddings
”) ,因此在变压器模型的训练期间模拟类似于 [MASK]
的东西。但这只是我的建议,没有任何科学证据证明它有效(无论好坏)。