网站名称注册保护,wordpress 插件路径,网站建设销售技巧话术,网站建设中网站制作包括哪些内容BertTokenizerFast类
1、特点 速度快#xff1a;底层使用Rust实现#xff0c;比纯python的BertTokenizer快得多#xff08;尤其是批量处理的时候#xff09;#xff0c;且支持多线程使用。 功能一致#xff1a;与BertTokenizer的API完全兼容#xff0c;可以直接替换使用…BertTokenizerFast类
1、特点 速度快底层使用Rust实现比纯python的BertTokenizer快得多尤其是批量处理的时候且支持多线程使用。 功能一致与BertTokenizer的API完全兼容可以直接替换使用。支持所有的BERT变体。 额外功能提供更丰富的后处理选项如截断、填充的精细控制。支持直接返回token_type_ids、attention_mask等张量。
2、基本用法
from transformers import BertTokenizerFast# 初始化分词器以chinese-bert-wwm模型为例
tokenizer BertTokenizerFast.from_pretrained(chinese-bert-wwm)# 单条文本分词
text ‘你好明天’
encoded_input tokenizer(text, return_tensorspt) # 返回pytorch张量输出结果
{input_ids: tensor([[101, 3209, 1921, 8024, 872, 1962, 8013, 102]]),token_type_ids: tensor([[0, 0, 0, 0, 0, 0, 0, 0]]),attention_mask: tensor([[1, 1, 1, 1, 1, 1, 1, 1]])
}# 批量文本分词
texts [明天你好, 你好明天]
batch_encoded tokenizer(texts, paddingTrue, truncationTrue, return_tensorspt)输出结果
{input_ids: tensor([[101, 3209, 1921, 8024, 872, 1962, 8013, 102], [101, 872, 1962, 8024, 3209, 1921, 8013, 102]]),token_type_ids: tensor([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]),attention_mask: tensor([[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]])
}3、关键参数
参数名作用paddingTrue自动填充到批次中最长序列长度trunctionTrue自动截断到模型最大长度512return_tensorspt返回pytorch张量可选tf为TensorFlow或np为numpymax_length128显式指定最大长度add_special_tokens是否添加[cls]和[sep]默认为Truereturn_offsets_mapping返回每个token在原始文本中的字符集起始和结束位置skip_special_tokens在解码将Token ID转回文本时跳过特殊token如[CLS]、[SEP]、[PAD]等默认值为False设为True后输出更干净的文本 4、自定义tokens
tokenizer.add_tokens([亚马逊, 速卖通]) # 添加新的token
model.resize_token_embeddings(len(tokenizer)) # 调整模型嵌入层
5、偏移量映射用于命名实体识别任务
encoded_input tokenizer(text, return_offsets_mappingTrue)
print(encoded_input[offset_mapping]) # 输出每个token在原文中的位置
6、快速解码
decoded_text tokenizer.decode(encoded_input[input_ids][0], skip_special_tokensTrue)