【问题标题】:BertTokenizer - when encoding and decoding sequences extra spaces appearBertTokenizer - 编码和解码序列时出现额外空格
【发布时间】:2019-11-21 16:43:31
【问题描述】:

在使用 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 标记化过程是 100% 可逆的,正如您所注意到的。你为什么需要它?可能还有其他方法可以完成您想要的,例如通过保留原始字符串而不是从标记重构它。
  • 相比之下,像github.com/kovalevfm/SubTokenizer 这样的东西实际上是完全可逆的。我希望 BERT 对此要小心,但对文本分割细节的关注似乎是一个“生产”问题而不是“研究”问题 :(
  • 这只是我脚本中的一个 sn-p 来显示问题。在这之间我正在回答问题,我想要实现的是一个完全可追溯的文本
  • 啊,所以理想情况下你应该有类似github.com/huggingface/transformers/pull/1274 的东西。假设您可以将答案范围捕捉到整个单词,您可以使用 bistring.readthedocs.io/en/latest/Python/Tokenizer.html 之类的东西在跟踪字符串索引的同时拆分成单词,然后只需使用 BertTokenizer 获取子词

标签: python pytorch tokenize torch bert-language-model


【解决方案1】:

如果您尝试使用 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]]

【讨论】:

    【解决方案2】:

    根据https://github.com/huggingface/transformers/pull/1274,他们正在努力。希望下周的某个时候会有解决方案。

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 1970-01-01
      • 2013-10-06
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 2017-08-15
      • 1970-01-01
      相关资源
      最近更新 更多