transformers-tokenizer备忘

对transformers库不常用记录,方便回溯。

知识点

1. fast的含义

比如BertTokenizerFast,use_fast, 示例如下:

1
AutoTokenizer.from_pretrained('hfl/chinese-electra-180g-small-discriminator', use_fast=True)

它的含义是使用rust加速速度。

嘿嘿,rust现在要进入linux内核了,恭喜恭喜。

2. tokenizer

比如常见的convert_ids_to_tokensencode, encode_plus等等,下面记录一种对句子对的使用方式.

完整例子可参考ne_bert_mrc.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- coding: utf8 -*-
#

from transformers import AutoTokenizer, BertTokenizerFast

tokenizer = AutoTokenizer.from_pretrained('hfl/chinese-electra-180g-small-discriminator', use_fast=True)
question = '南京天气怎么样' # 7
context = '我今天早上站在阳台看天空,今天南京天气很好!' # 22

tokenized_examples = tokenizer(
question, # 问题文本
context, # 篇章文本
truncation="only_second", # 截断只发生在第二部分,即篇章
max_length=20, # 设定最大长度为384
# stride=5, # 设定篇章切片步长为128
return_overflowing_tokens=True, # 返回超出最大长度的标记,将篇章切成多片
return_offsets_mapping=True, # 返回偏置信息,用于对齐答案位置
padding="max_length", # 按最大长度进行补齐
)

print(tokenized_examples)
input_ids = tokenized_examples['input_ids']
token_type_ids = tokenized_examples['token_type_ids']
attention_masks = tokenized_examples['attention_mask']
offset_mappings = tokenized_examples['offset_mapping']
overflow_to_sample_mapping = tokenized_examples['overflow_to_sample_mapping']
for index, _input_ids in enumerate(input_ids):
print('input_ids -> ', tokenizer.convert_ids_to_tokens(_input_ids))
print('token_type_ids -> ', token_type_ids[index])
print('attention_masks -> ', attention_masks[index])
print('offset_mappings -> ', offset_mappings[index])
print('overflow_to_sample_mapping -> ', overflow_to_sample_mapping[index])

可以自行改动这个例子,其中stride默认注释掉了,默认为0。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值