word-embedding - 如何使用transformers.BertTokenizer对多个句子进行编码?
问题描述
我想通过使用 transform.BertTokenizer 对多个句子进行编码来创建一个小批量。它似乎适用于一个句子。如何使它适用于几个句子?
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# tokenize a single sentence seems working
tokenizer.encode('this is the first sentence')
>>> [2023, 2003, 1996, 2034, 6251]
# tokenize two sentences
tokenizer.encode(['this is the first sentence', 'another sentence'])
>>> [100, 100] # expecting 7 tokens
解决方案
transformers >= 4.0.0:tokenizer
的
使用__call__
方法。它将为每个输入句子生成一个包含,和as 列表的字典:input_ids
token_type_ids
attention_mask
tokenizer(['this is the first sentence', 'another setence'])
输出:
{'input_ids': [[101, 2023, 2003, 1996, 2034, 6251, 102], [101, 2178, 2275, 10127, 102]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]}
变压器 < 4.0.0:
使用tokenizer.batch_encode_plus
(文档)。它将为每个输入句子生成一个包含input_ids
,token_type_ids
和as 列表的字典:attention_mask
tokenizer.batch_encode_plus(['this is the first sentence', 'another setence'])
输出:
{'input_ids': [[101, 2023, 2003, 1996, 2034, 6251, 102], [101, 2178, 2275, 10127, 102]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]}
适用于call和 batch_encode_plus:
如果您只想生成 input_ids,则必须将return_token_type_ids
ans设置return_attention_mask
为 False:
tokenizer.batch_encode_plus(['this is the first sentence', 'another setence'], return_token_type_ids=False, return_attention_mask=False)
输出:
{'input_ids': [[101, 2023, 2003, 1996, 2034, 6251, 102], [101, 2178, 2275, 10127, 102]]}
推荐阅读
- python - 如何在循环中对数组中的值求和
- math - 如何计算循环边界?
- json - 合并包含 JSON 数组的 json 文件列表
- c++ - SFML 我的移动功能无法正常工作
- reactjs - fastAPI中的异步心跳
- php - 如何获取两个日期之间的持续时间?(php)
- c - 为 CHECK_FUNCTION_EXIST 添加链接器标志
- python-3.x - 是否可以设置 Pypandoc 以使用与本机 Word 文件相同的纸张大小、对齐方式、表格、颜色等来转换文件?
- c# - Entity Framework 复数 where 条件
- android - 首先在 RecyclerView 外滚动