目录
#做(中文与英文的)分类任务,Bert模型比较合适,用cls向下游任务传输数据,做分类任务
#Bert模型要求一般传一个句子对(两句话)
1 加载预训练模型对应的分词器
from transformers import AutoTokenizer
#use_fast=True 表示使用RUST语言写的分词器,速度比python写的快
tokenizer = AutoTokenizer.from_pretrained('../data/model/distilbert-base-uncased/', use_fast=True)
tokenizer
DistilBertTokenizerFast(name_or_path='../data/model/distilbert-base-uncased/', vocab_size=30522, model_max_length=512, is_fast=True, padding_side='right', truncation_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'}, clean_up_tokenization_spaces=False),
#编码试算
tokenizer.batch_encode_plus(['hello, everyone, today is a good day',
'how are you, fine thank you, and you?'])
#编码返回的是'input_ids' 和 'attention_mask'
{'input_ids': [[101, 7592, 1010, 3071, 1010, 2651, 2003, 1037, 2204, 2154, 102], [101, 2129, 2024, 2017, 1010, 2986, 4067, 2017, 1010, 1998, 2017, 1029, 102]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}
2 加载数据集
from datasets import load_dataset
dataset = load_dataset('../data/datasets/cola/', trust_remote_code=True)
dataset
DatasetDict({ train: Dataset({ features: ['text', 'label'], num_rows: 8551 }) test: Dataset({ features: ['text', 'label'], num_rows: 527 }) })
dataset['train'][0]
{'text': "Our friends won't buy this analysis, let alone the next one we propose.", 'label': 1}
3 数据预处理
def f(examples, tokenizer):
"""只对传输数据集的句子文本'text'进行编码分词"""
return tokenizer.batch_encode_plus(examples['text'], truncation=True)
dataset = dataset.map(f,
batched=True,
batch_size=1000, #一批有1000个数据
#num_proc=1 更快 , 数据量不多的时候, 创建进程也是需要时间开销
num_proc=1, #8个进程同时处理,cpu是8核
remove_columns=['text'], #原数据集中的['text']不要了,转化成['input_ids']
fn_kwargs={'tokenizer': tokenizer})
print(dataset['train'][0])
{'label': 1, 'input_ids': [101, 2256, 2814, 2180, 1005, 1056, 4965, 2023, 4106, 1010, 2292, 2894, 1996, 2279, 2028, 2057, 16599, 1012, 102], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}