python - BertTokenizer - 当编码和解码序列时出现额外的空格

标签 python pytorch tokenize torch bert-language-model

当使用 HuggingFace 的 Transformers 时,我遇到编码和解码方法的问题。

我有以下字符串:

test_string = 'text with percentage%'

然后我运行以下代码:

import torch
from transformers import BertTokenizer

tokenizer = BertTokenizer.from_pretrained('bert-base-cased')

test_string = 'text with percentage%'

# encode Converts a string in a sequence of ids (integer), using the tokenizer and vocabulary.
input_ids = tokenizer.encode(test_string)
output = tokenizer.decode(input_ids)

输出如下所示:

'text with percentage %'

% 之前有一个额外的空格。我尝试过像 clean_up_tokenization_spaces 这样的额外参数,但这是为了不同的东西。

我应该如何在解码和编码中使用什么来获得前后完全相同的文本。对于其他特殊标志也会发生这种情况。

最佳答案

如果您尝试使用 BERT 进行标记分类,以便在原始字符串中查找范围,则一种解决方法是使用 BertTokenizerFast 以及选项 return_offsets_mapping=True.

test_string = 'text with percentage%'

tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased')
tokens = tokenizer(test_string, return_offsets_mapping=True)
input_ids = tokens.data["input_ids"]

span_start_index, span_stop_index = some_model(input_ids)

然后,一旦获得 token 分类结果,您就可以执行类似的操作

predicted_span = test_string[tokens.encodings[0].offsets[span_start_index][0]:tokens.encodings[0].offsets[span_stop_index][1]]

关于python - BertTokenizer - 当编码和解码序列时出现额外的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58979779/

相关文章:

c - 使用 strtok() 在 c 中将字符串标记两次

python - pytorch数据加载器: `Tensors must have same number of dimensions`

python - 如何使用 Python nltk.tokenize 将包含停用词的短语视为单个标记

python - Django/python : loop through a dictionary and add an item to it

python - 在 Python 中访问共享内存的段错误

python - 使用代理解析主机名

python - 使用 python 请求中断流式下载大文件

android - android中U2Net模型的使用

python - 在 for 循环中使用时,pytorch 数据集对象如何知道它是否已到达末尾?

java - 如何将 StringTokenizer 中的分隔符添加到单独的字符串中?