測試代碼
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}")
運行結(jié)果:
1. 總結(jié)
三個方法的輸入都是字符串: "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
轉(zhuǎn)化為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’:區(qū)分兩個句子的編碼(上句全為0,下句全為1)
‘a(chǎn)ttention_mask’:指定對哪些詞進行self-Attention操作
offset_mapping:記錄了 每個拆分出來 的內(nèi)容(token)都 對應(yīng)著原來的句子的位置
2.區(qū)別
2.1 tokenizer.tokenize() 和 tokenizer.encode() 區(qū)別
tokenizer.tokenize() 返回詞列表 默認首尾不加 [CLS]
[SEP]
okenizer.encode() 返回詞id列表 默認首尾加 [CLS]
[SEP]
對應(yīng)的詞id
2.2 tokenizer.encode() 和 tokenizer.encode_plus() 區(qū)別
返回類型不同
tokenizer.encode() 返回 詞id列表
tokenizer.encode_plus() 返回 dict類型 其中input_ids 就是 tokenizer.encode() 的返回值, 還有用于分句和掩碼的其他兩個id文章來源:http://www.zghlxwxcb.cn/news/detail-423911.html
參考博客: https://blog.csdn.net/qq_25850819/article/details/115355858文章來源地址http://www.zghlxwxcb.cn/news/detail-423911.html
到了這里,關(guān)于tokenizer.tokenize(), tokenizer.encode() , tokenizer.encode_plus() 方法介紹及其區(qū)別的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!