Datasets documentation

テキストデータを処理する

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v4.8.4).
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