datasets 笔记: 文本数据集的预处理(Tokenization)

  • 将文本分割为单词或子单元(tokens),然后将 tokens 映射为数字

0 加载数据集和分词器

python 复制代码
from transformers import AutoTokenizer
from datasets import load_dataset

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
dataset = load_dataset("rotten_tomatoes", split="train")

1 对单条样本进行分词

python 复制代码
tokenizer(dataset[0]["text"])
'''
{'input_ids': [101, 1996, 2600, 2003, 16036, 2000, 2022, 1996, 7398, 2301, 1005, 1055, 2047, 1000, 16608, 1000, 1998, 2008, 2002, 1005, 1055, 2183, 2000, 2191, 1037, 17624, 2130, 3618, 2084, 7779, 29058, 8625, 13327, 1010, 3744, 1011, 18856, 19513, 3158, 5477, 4168, 2030, 7112, 16562, 2140, 1012, 102], 
'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
'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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
'''

2 对整个数据集进行批量分词

python 复制代码
def tokenization(example):
    return tokenizer(example["text"])

dataset = dataset.map(tokenization, batched=True)
dataset[0].keys()
'''
dict_keys(['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'])
'''

原先的text和label的基础上,多了input_ids,token_type_ids和attention_mask三个key

3 设置数据集格式以适配 PyTorch

python 复制代码
dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "label"])
dataset[0]
'''
{'label': tensor(1),
 'input_ids': tensor([  101,  1996,  2600,  2003, 16036,  2000,  2022,  1996,  7398,  2301,
          1005,  1055,  2047,  1000, 16608,  1000,  1998,  2008,  2002,  1005,
          1055,  2183,  2000,  2191,  1037, 17624,  2130,  3618,  2084,  7779,
         29058,  8625, 13327,  1010,  3744,  1011, 18856, 19513,  3158,  5477,
          4168,  2030,  7112, 16562,  2140,  1012,   102]),
 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])}
'''
相关推荐
datablau国产数据库建模工具5 分钟前
数语科技登陆华为云商店,助力企业释放数据潜能
人工智能·科技·华为云
刘晓倩13 分钟前
扣子Coze中的触发器实现流程自动化-实现每日新闻卡片式推送
人工智能·触发器·coze
徐礼昭|商派软件市场负责人31 分钟前
商派小程序商城(小程序/官网/APP···)的范式跃迁与增长再想象
人工智能·小程序·商城系统·商派oms
大志说编程42 分钟前
LangChain框架入门09:什么是RAG?
人工智能·langchain
做一个优雅的美男子42 分钟前
FPGA设计思想与验证方法学系列学习笔记003
笔记·fpga开发
ezl1fe43 分钟前
RAG 每日一技(十四):化繁为简,统揽全局——用LangChain构建高级RAG流程
人工智能·后端·算法
一碗白开水一1 小时前
【第6话:相机模型2】相机标定在自动驾驶中的作用、相机标定方法详解及代码说明
人工智能·数码相机·自动驾驶
The moon forgets1 小时前
Occ3D: A Large-Scale 3D Occupancy Prediction Benchmark for Autonomous Driving
人工智能·pytorch·深度学习·目标检测·3d
新智元1 小时前
刚刚,马斯克 Grok4 干翻谷歌 Gemini!o3 杀入首届大模型对抗赛决战
人工智能·openai
一叶怎知秋2 小时前
【openlayers框架学习】九:openlayers中的交互类(select和draw)
前端·javascript·笔记·学习·交互