【问题标题】:How can I get RoBERTa word embeddings?如何获得 RoBERTa 词嵌入?
【发布时间】:2020-07-04 13:36:52
【问题描述】:

给定一个“Roberta 是 BERT 的高度优化版本”类型的句子,我需要使用 RoBERTa 获取该句子中每个单词的嵌入。我试图在网上查看示例代码,但未能找到明确的答案。

我的看法如下:

tokens = roberta.encode(headline)
all_layers = roberta.extract_features(tokens, return_all_hiddens=True)
embedding = all_layers[0]
n = embedding.size()[1] - 1
embedding = embedding[:,1:n,:]

其中embedding[:,1:n,:] 用于仅提取句子中单词的嵌入,没有开始和结束标记。

对吗?

【问题讨论】:

  • 我假设您为此使用了 huggingface 的库?如果是这样,请相应地更新您的标签(bert 未使用,但您可以使用 huggingface-transformers 代替)。由于有多种实现方式,否则很难确定正确的实现方式并给出正确答案。
  • 我不认为这是正确的。我的理解是embedding = all_layers[-1][-1]

标签: encoding nlp word-embedding


【解决方案1】:
TOKENIZER_PATH = "../input/roberta-transformers-pytorch/roberta-base"
ROBERTA_PATH = "../input/roberta-transformers-pytorch/roberta-base"

text= "How are you? I am good."
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)

##how the words are broken into tokens
print(tokenizer.tokenize(text))

##the format of a encoding
print(tokenizer.batch_encode_plus([text]))

##op wants the input id
print(tokenizer.batch_encode_plus([text])['input_ids'])

##op wants the input id without first and last token
print(tokenizer.batch_encode_plus([text])['input_ids'][0][1:-1])

输出:

['How', 'Ġare', 'Ġyou', '?', 'ĠI', 'Ġam', 'Ġgood', '.']

{'input_ids': [[0, 6179, 32, 47, 116, 38, 524, 205, 4, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}

[[0, 6179, 32,47, 116, 38, 524, 205, 4, 2]]

[6179、32、47、116、38、524、205、4]

不用担心“Ġ”字符。它只是表示单词前面有一个空格。

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多