Transformer入门-Huggingface的基础03-tokenizer的使用

一.Tokenizer的简介

Tokenizer 简介

tokenizer简而言之就是对一段文本的词语或者单词进行分词操作,将一句话分解为机器可以识别的语义信息。
以往的数据预处理
step1 分词: 使用分词器(Jieba分词器)对文本数据进行分词(字、字词) ;
Step2 构建词典:根据整个数据集分词统计的结果,构建词典的一一映射关系(如果采用预训练词向量,词典映射要根据词向量文件进行处理) ;
Step3 数据转换:根据构建好的词典,将分词处理后的数据做映射,将文本序列转换为数字序列;
Step4 数据填充与截断: 在以batch输入到模型的方式中,需要对过短的数据进行填充,过长的数据进行截断保证数据长度符合模型能接受的范围,同时batch内的数据维度大小一致。

二.toikenzier的基本使用

1.加载保存 (from_pretrained / save_pretrained)

t5_base_question_generation = AutoTokenizer.from_pretrained("ZhangCheng/T5-Base-finetuned-for-Question-Generation")
# 将下载的预训练处理的单词,进行存储
t5_base_question_generation.save_pretrained('./model/t5_base_question_generation')
model_t5_base_question_generation = AutoModelForSeq2SeqLM.from_pretrained("ZhangCheng/T5-Base-finetuned-for-Question-Generation")
# 将下载的预处理模型参数存储到指定的部分
model_t5_base_question_generation.save_pretrained('./model/t5_base_question_generation')

2.句子分词 (tokenize)

sentence = 'I am a student and I will to go shcool'
tokens = tokenizer.tokenize(sentence)

3.查看词典和特殊字符 (vocab)
print(tokenizer.vocab)
print(tokenizer.special_tokens)
4.索引转换 (convert tokens to ids / convert ids to tokens)

token_ids = tokenizer.convert_tokens_to_ids(tokens)
tokenizer.convert_ids_to_tokens(token_ids)
tokenizer.convert_tokens_to_string(tokens)
tokenizer.encode(sentence)
tokenizer.decode(token_ids,skip_special_tokens=False)

5.填充截断 (padding / truncation)

#填充操作
tokenizer.encode(sentence,padding="max_length",max_length=15)
#截断操作
tokenizer.encode(sentence,truncation=True,max_length=15)

6.其他输入 (attention mask / token type ids)

#掩码操作mask
inputs = tokenizer.encode_plus(sentence,padding="max_length",max_length=15)
sentences = [
    "I am a student.",
    "I will to go school.",
    "How much the clothes prices?"
]
tokenizer(sentences)

三.总结

关于tokenizer主要被用于文本数据的预处理,实在原始分词的基础上对其进行的改进。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Algorithm_Engineer_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值