Datasets 文件
處理文字資料
加入 Hugging Face 社群
並獲得增強的文件體驗
開始使用
處理文字資料
本指南展示了處理文字資料集的具體方法。您將學習如何
- 使用 map() 對資料集進行分詞。
- 對於自然語言推理 (NLI) 資料集,將資料集標籤與標籤 ID 對齊。
有關如何處理任何型別資料集的指南,請參閱通用處理指南。
Map
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
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 對映。
< > 在 GitHub 上更新