Datasets documentation

处理文本数据

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

处理文本数据

本指南介绍了处理文本数据集的具体方法。学习如何:

  • 使用 map() 对数据集进行分词。
  • 将 NLI 数据集的标签与标签 ID 对齐。

有关如何处理任意类型数据集的指南,请参阅通用处理指南。

映射

map() 函数支持一次性处理一批示例,从而加快分词速度。

从 🤗 Transformers 加载分词器:

>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

在 map() 函数中将 batched 参数设置为 True,即可将分词器应用于示例批次:

>>> dataset = dataset.map(lambda examples: tokenizer(examples["text"]), batched=True)
>>> dataset[0]
{'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 
 'label': 1, 
 '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]}

map() 函数会将返回的值转换为 PyArrow 支持的格式。但显式地将张量作为 NumPy 数组返回速度更快,因为这是 PyArrow 原生支持的格式。在对文本进行分词时,请设置 return_tensors="np":

>>> dataset = dataset.map(lambda examples: tokenizer(examples["text"], return_tensors="np"), batched=True)

对齐

align_labels_with_mapping() 函数用于将数据集的标签 id 与标签名称对齐。并非所有 🤗 Transformers 模型都遵循原始数据集规定的标签映射,尤其是对于 NLI 数据集。例如,MNLI 数据集使用以下标签映射:

>>> label2id = {"entailment": 0, "neutral": 1, "contradiction": 2}

为了使数据集的标签映射与模型使用的映射保持一致,请创建一个包含标签名称和 id 的字典,以便进行对齐:

>>> label2id = {"contradiction": 0, "neutral": 1, "entailment": 2}

将标签映射字典传递给 align_labels_with_mapping() 函数,并指定要对齐的列:

>>> from datasets import load_dataset

>>> mnli = load_dataset("nyu-mll/glue", "mnli", split="train")
>>> mnli_aligned = mnli.align_labels_with_mapping(label2id, "label")

您还可以使用此函数将标签到 id 的自定义映射分配给

Update on GitHub