tokenizer.tokenize(), tokenizer.encode() , tokenizer.encode_plus() 方法介绍及其区别

测试代码

from transformers import BertTokenizer
# BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')  # bert分词器

sentence = "i am overheat"
encode_ids = tokenizer.encode(sentence) # encode 默认为True 加[CLS][SEP]
encode_words = tokenizer.convert_ids_to_tokens(tokenizer.encode(sentence))   # encode 默认为True 加[CLS][SEP]


print(f"word_list   : {sentence.split()}")                 # 单词列表 (不进行分词)
print(f"tokenize    : {tokenizer.tokenize(sentence) }")    # 单词列表 (进行分词)
print(f"encode_words: {encode_words}")                     # 单词列表 (进行分词) [CLS]+sentence+[SEP]
print(f"encode_ids  : {tokenizer.encode(sentence)}")       # 词id列表 进行分词   101 + ids + 102
print(f"encode_plus : {tokenizer.encode_plus(sentence)}")  # dict 类型 三个key:value, {input_ids:词id列表(进行分词) token_type_ids:分句列表0(分句) attention_mask:掩码列表1(掩码)}
print("=" * 100)

encode_words_true =  tokenizer.encode(sentence, add_special_tokens=True)    # encode 默认为True 加[CLS][SEP]
encode_words_false = tokenizer.encode(sentence, add_special_tokens=False)  # encode False    不加[CLS][SEP]
print(f"encode_words_true : {encode_words_true}")
print(f"encode_words_false: {encode_words_false}")

运行结果:
在这里插入图片描述

1. 总结

三个方法的输入都是字符串: "i am overheat"

1.1 tokenizer.tokenize() 方法

输入: str 字符串
输出: str_list 词列表(进行了wordpiece分词的)

['i', 'am', 'over', '##hea', '##t']  

1.2 tokenizer.encode() 方法

输入: str 字符串
输出: int_list id列表 开始和末尾分别添加了[CLS] [SEP]的词id 101, 102

[101, 1045, 2572, 2058, 20192, 2102, 102]

可以通过tokenizer.convert_ids_to_tokens转化为token列表 str_list

['[CLS]', 'i', 'am', 'over', '##hea', '##t', '[SEP]']

add_special_tokens=True 默认为True 表示加不加[CLS][SEP]这两个词id

1.3 tokenizer.encode_plus() 方法

输入: str 字符串
输出: 字典 input_ids就是encode的返回值, token_type_ids用于分句, attention_mask 用于掩码

{'input_ids': [101, 1045, 2572, 2058, 20192, 2102, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1]}

’input_ids: 是单词在词典中的编码
‘token_type_ids’:区分两个句子的编码(上句全为0,下句全为1)
‘attention_mask’:指定对哪些词进行self-Attention操作
offset_mapping:记录了 每个拆分出来 的内容(token)都 对应着原来的句子的位置

2.区别

2.1 tokenizer.tokenize() 和 tokenizer.encode() 区别

tokenizer.tokenize() 返回词列表 默认首尾不加 [CLS] [SEP]
okenizer.encode() 返回词id列表 默认首尾加 [CLS] [SEP]对应的词id

2.2 tokenizer.encode() 和 tokenizer.encode_plus() 区别

返回类型不同
tokenizer.encode() 返回 词id列表
tokenizer.encode_plus() 返回 dict类型 其中input_ids 就是 tokenizer.encode() 的返回值, 还有用于分句和掩码的其他两个id

参考博客: https://blog.csdn.net/qq_25850819/article/details/115355858

  • 19
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值