识别通过拥抱面部管道填充掩码选择的单词

Identifying the word picked by hugging face pipeline fill-mask

我想使用 hugging face 的 fill-mask 管道来猜测一个被屏蔽的标记,然后只将猜测的标记提取为一个词。这段代码应该这样做:

!pip install -q transformers
model = pipeline('fill-mask')
outcome = model("Kubernetes is a container orchestration <mask>")[0]

#Prints: "Kubernetes is a container orchestration platform" 
print(outcome['sequence']) 

token = outcome['token'] 

#Prints: 1761
print(token)

#Prints: Ġplatform 
print(model.tokenizer.convert_ids_to_tokens(token))

但我发现它给了我 "Ġplatform" 而不是 "platform" - 有谁知道这是为什么或这里会发生什么?

这只是底层模型的一个特性(请参阅 here 以检查这是 distilroberta-base)。
具体来说,蒸馏模型使用与其 "teacher models" 相同的分词器(在本例中为 RoBERTa)。反过来,RoBERTa 有一个分词器,它在没有任何形式的空格的情况下严格工作,另请参见 this thread on OpenAI's GPT-2 model, which is using the same tokenization strategy (see here)。

具体来说,您可以注意到它始终是相同的 unicode 字符 \u0120 表示新单词的开头。相比之下,由多个子词组成的词对于后面的子词没有这样的起始字符。

也就是说,complication 会被分成两个虚构的子词 Ġcompli cation

因此,如果 Ġ 出现在单词中,您可以简单地删除它。

截至 2021 年 8 月 14 日,管道的输出包含您请求的所有信息。请注意 token_str 可能包含空格。

from transformers import pipeline

unmasker = pipeline("fill-mask")

s="Excuse me sir, <mask> you speak English?"

unmasker(s,top_k=5)

[{'score': 0.9028477668762207,
  'sequence': 'Excuse me sir, do you speak English?',
  'token': 109,
  'token_str': ' do'},
 {'score': 0.05048234760761261,
  'sequence': 'Excuse me sir, did you speak English?',
  'token': 222,
  'token_str': ' did'},
 {'score': 0.015572326257824898,
  'sequence': 'Excuse me sir, can you speak English?',
  'token': 64,
  'token_str': ' can'},
 {'score': 0.007022920995950699,
  'sequence': 'Excuse me sir, Do you speak English?',
  'token': 1832,
  'token_str': ' Do'},
 {'score': 0.005521782673895359,
  'sequence': 'Excuse me sir, if you speak English?',
  'token': 114,
  'token_str': ' if'}]