首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取RoBERTa word嵌入?

如何获取RoBERTa word嵌入?
EN

Stack Overflow用户
提问于 2020-03-24 11:33:11
回答 1查看 1.3K关注 0票数 4

给定一个句子“RoBERTa是BERT的一个高度优化的版本。”,我需要用RoBERTa获得这个句子中每个单词的嵌入。我试着在网上查看示例代码,但没有找到明确的答案。

我的观点如下:

代码语言:javascript
复制
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,:]用于仅提取句子中单词的嵌入,而不提取开始和结束标记。

这是正确的吗?

EN

回答 1

Stack Overflow用户

发布于 2021-07-26 20:00:22

代码语言:javascript
复制
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])

输出:

{'input_ids':[0,6179,32,47,116,38,524,205,4,2],'attention_mask':[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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60824589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档