# トークン分類

Token classificationは、文内の個々のトークンにラベルを割り当てます。Token classificationの最も一般的なタスクの一つは、Named Entity Recognition（NER）です。NERは、人物、場所、組織などのエンティティに対して、文内の各エンティティにラベルを割り当てようとするものです。

このガイドでは、次の方法について説明します：

1. [WNUT 17](https://huggingface.co/datasets/flaitenberger/wnut_17) データセットで[DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased)をファインチューニングして、新しいエンティティを検出します。
2. ファインチューニングしたモデルを推論に使用します。

このタスクと互換性のあるすべてのアーキテクチャとチェックポイントを確認するには、[タスクページ](https://huggingface.co/tasks/token-classification)を参照することをお勧めします。

開始前に、必要なライブラリがすべてインストールされていることを確認してください。

```bash
pip install transformers datasets evaluate seqeval
```

Hugging Face アカウントにログインして、モデルをアップロードし、コミュニティと共有できるようにすることを推奨します。プロンプトが表示されたら、ログイン用のトークンを入力してください:

```py
>>> from huggingface_hub import notebook_login

>>> notebook_login()
```

## WNUT 17 データセットを読み込みます

🤗 Datasets ライブラリから WNUT 17 データセットを読み込むことから始めます:

```py
>>> from datasets import load_dataset

>>> wnut = load_dataset("flaitenberger/wnut_17")
```

次に、例を見てみましょう。

```py
>>> wnut["train"][0]
{'id': '0',
 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0],
 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
}
```

`ner_tags` の各数値はエンティティを表しています。エンティティの内容を確認するには、数値をラベル名に変換します:

```py
>>> label_list = wnut["train"].features[f"ner_tags"].feature.names
>>> label_list
[
    "O",
    "B-corporation",
    "I-corporation",
    "B-creative-work",
    "I-creative-work",
    "B-group",
    "I-group",
    "B-location",
    "I-location",
    "B-person",
    "I-person",
    "B-product",
    "I-product",
]
```

各`ner_tag`の先頭にある文字は、エンティティのトークン位置を示します。

- `B-` はエンティティの開始を示します。
- `I-`は、トークンが同一エンティティの内部に含まれていることを示します（例えば、`State`トークンは`Empire State Building`のようなエンティティの一部です）。
- `0`は、そのトークンがエンティティに対応していないことを示します。

## 前処理

次のステップは、`tokens`フィールドの前処理を行うために DistilBERT のトークナイザーを読み込むことです。

```py
>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
```

上記の例の`tokens`フィールドで見たように、入力はすでにトークン化されているように見えます。しかし実際にはまだトークン化されておらず、単語をサブワードにトークン化するには`is_split_into_words=True`を設定する必要があります。例えば:

```py
>>> example = wnut["train"][0]
>>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
>>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
>>> tokens
['[CLS]', '@', 'paul', '##walk', 'it', "'", 's', 'the', 'view', 'from', 'where', 'i', "'", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]']
```

ただし、これにより特殊トークン`[CLS]`と`[SEP]`が追加され、サブワードトークナイズーションによって入力とラベルの間に不一致が生じます。1つのラベルに対応する1つの単語が、2つのサブワードに分割される可能性があります。トークンとラベルを再整合させるには、次のようにしてください。

1. [word_ids](/docs/transformers/v5.24.0/ja/main_classes/tokenizer#transformers.BatchEncoding.word_ids) メソッドを使用して、すべてのトークンを対応する単語にマッピングします。
2. 特殊トークン`[CLS]`と`[SEP]`にラベル`-100`を割り当て、PyTorchの損失関数によって無視されるようにします([CrossEntropyLoss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)を参照)。
3. `-100` を、指定された単語の最初のトークン以外のサブトークンに割り当てます。

トークンとラベルを再整列し、シーケンスをDistilBERTの最大入力長を超えないように切り詰める関数を作成するには、次のようにします。

```py
>>> def tokenize_and_align_labels(examples):
...     tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)

...     labels = []
...     for i, label in enumerate(examples[f"ner_tags"]):
...         word_ids = tokenized_inputs.word_ids(batch_index=i)  # Map tokens to their respective word.
...         previous_word_idx = None
...         label_ids = []
...         for word_idx in word_ids:  # Set the special tokens to -100.
...             if word_idx is None:
...                 label_ids.append(-100)
...             elif word_idx != previous_word_idx:  # Only label the first token of a given word.
...                 label_ids.append(label[word_idx])
...             else:
...                 label_ids.append(-100)
...             previous_word_idx = word_idx
...         labels.append(label_ids)

...     tokenized_inputs["labels"] = labels
...     return tokenized_inputs
```

データセット全体に前処理関数を適用するには、🤗 Datasets の [map](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset.map) 関数を使用します。`map` 関数に `batched=True` を設定すると、データセットの複数の要素を一度に処理できるため、処理を高速化できます:

```py
>>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)
```

次に、[DataCollatorWithPadding](/docs/transformers/v5.24.0/ja/main_classes/data_collator#transformers.DataCollatorWithPadding)を使用してサンプルのバッチを作成します。データセット全体を最大長にパディングするのではなく、コラレーション時にバッチ内の最も長い長さに合わせて*動的にパディング*する方が効率的です。

```py
>>> from transformers import DataCollatorForTokenClassification

>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
```

## 評価

学習中にメトリクスを含めることは、モデルの性能を評価する上でしばしば役立ちます。🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) ライブラリを使用すると、評価メソッドをすばやく読み込むことができます。このタスクでは、[seqeval](https://huggingface.co/spaces/evaluate-metric/seqeval) フレームワークを読み込みます（メトリクスの読み込みと計算方法の詳細については、🤗 Evaluate の [クイックツアー](https://huggingface.co/docs/evaluate/a_quick_tour) を参照してください）。Seqeval は実際には、precision、recall、F1、accuracy の複数のスコアを出力します。

```py
>>> import evaluate

>>> seqeval = evaluate.load("seqeval")
```

まず NER ラベルを取得し、次に、実際の予測値と実際のラベルを [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) に渡してスコアを計算する関数を作成します:

```py
>>> import numpy as np

>>> labels = [label_list[i] for i in example[f"ner_tags"]]

>>> def compute_metrics(p):
...     predictions, labels = p
...     predictions = np.argmax(predictions, axis=2)

...     true_predictions = [
...         [label_list[p] for (p, l) in zip(prediction, label) if l != -100]
...         for prediction, label in zip(predictions, labels)
...     ]
...     true_labels = [
...         [label_list[l] for (p, l) in zip(prediction, label) if l != -100]
...         for prediction, label in zip(predictions, labels)
...     ]

...     results = seqeval.compute(predictions=true_predictions, references=true_labels)
...     return {
...         "precision": results["overall_precision"],
...         "recall": results["overall_recall"],
...         "f1": results["overall_f1"],
...         "accuracy": results["overall_accuracy"],
...     }
```

`compute_metrics`関数はこれで準備が整いました。学習を設定する際に、この関数に戻ります。

## 学習

モデルの学習を開始する前に、`id2label`と`label2id`を使用して、期待されるIDとラベルの対応表を作成します。

```py
>>> id2label = {
...     0: "O",
...     1: "B-corporation",
...     2: "I-corporation",
...     3: "B-creative-work",
...     4: "I-creative-work",
...     5: "B-group",
...     6: "I-group",
...     7: "B-location",
...     8: "I-location",
...     9: "B-person",
...     10: "I-person",
...     11: "B-product",
...     12: "I-product",
... }
>>> label2id = {
...     "O": 0,
...     "B-corporation": 1,
...     "I-corporation": 2,
...     "B-creative-work": 3,
...     "I-creative-work": 4,
...     "B-group": 5,
...     "I-group": 6,
...     "B-location": 7,
...     "I-location": 8,
...     "B-person": 9,
...     "I-person": 10,
...     "B-product": 11,
...     "I-product": 12,
... }
```

[Trainer](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer)によるモデルのファインチューニングに慣れていない場合は、[こちら](../training)の基本的なチュートリアルをご覧ください!

いよいよモデルの学習を開始できます![AutoModelForTokenClassification](/docs/transformers/v5.24.0/ja/model_doc/auto#transformers.AutoModelForTokenClassification) を使用して DistilBERT を読み込み、期待されるラベル数とラベルのマッピングを指定します:

```py
>>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer

>>> model = AutoModelForTokenClassification.from_pretrained(
...     "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
... )
```

この時点で、残りのステップは3つだけです:

1. [TrainingArguments](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.TrainingArguments) で学習ハイパーパラメータを定義します。必須のパラメータは `output_dir` だけで、モデルの保存先を指定します。`push_to_hub=True` を設定することで、このモデルを Hub にプッシュできます（モデルをアップロードするには Hugging Face にサインインしている必要があります）。各エポックの終了時、[Trainer](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer) は seqeval スコアを評価し、学習チェックポイントを保存します。
2. モデル、データセット、トークナイザー、データコラテーター、`compute_metrics` 関数とともに、学習引数を [Trainer](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer) に渡します。
3. [train()](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer.train)を呼び出して、モデルをファインチューニングします。

```py
>>> training_args = TrainingArguments(
...     output_dir="my_awesome_wnut_model",
...     learning_rate=2e-5,
...     per_device_train_batch_size=16,
...     per_device_eval_batch_size=16,
...     num_train_epochs=2,
...     weight_decay=0.01,
...     eval_strategy="epoch",
...     save_strategy="epoch",
...     load_best_model_at_end=True,
...     push_to_hub=True,
... )

>>> trainer = Trainer(
...     model=model,
...     args=training_args,
...     train_dataset=tokenized_wnut["train"],
...     eval_dataset=tokenized_wnut["test"],
...     processing_class=tokenizer,
...     data_collator=data_collator,
...     compute_metrics=compute_metrics,
... )

>>> trainer.train()
```

トレーニングが完了したら、[push_to_hub()](/docs/transformers/v5.24.0/ja/main_classes/trainer#transformers.Trainer.push_to_hub) メソッドでモデルを Hub に共有し、誰でもそのモデルを利用できるようにしてください。

```py
>>> trainer.push_to_hub()
```

トークン分類用のモデルをファインチューニングする方法をより詳しく知りたい場合は、対応する[PyTorchノートブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)を参照してください。

## 推論

素晴らしい、モデルのファインチューニングが完了したので、推論に使用できます！

推論を実行したいテキストを取得します:

```py
>>> text = "The Golden State Warriors are an American professional basketball team based in San Francisco."
```

ファインチューニングしたモデルで推論を試す最も簡単な方法は、[pipeline()](/docs/transformers/v5.24.0/ja/main_classes/pipelines#transformers.pipeline)でそれを使用することです。あなたのモデルでNER用の`pipeline`をインスタンス化し、テキストを渡します:

```py
>>> from transformers import pipeline

>>> classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model")
>>> classifier(text)
[{'entity': 'B-location',
  'score': 0.42658573,
  'index': 2,
  'word': 'golden',
  'start': 4,
  'end': 10},
 {'entity': 'I-location',
  'score': 0.35856336,
  'index': 3,
  'word': 'state',
  'start': 11,
  'end': 16},
 {'entity': 'B-group',
  'score': 0.3064001,
  'index': 4,
  'word': 'warriors',
  'start': 17,
  'end': 25},
 {'entity': 'B-location',
  'score': 0.65523505,
  'index': 13,
  'word': 'san',
  'start': 80,
  'end': 83},
 {'entity': 'B-location',
  'score': 0.4668663,
  'index': 14,
  'word': 'francisco',
  'start': 84,
  'end': 93}]
```

必要に応じて、`pipeline`の結果を手動で再現することもできます:

テキストをトークン化し、PyTorch テンソルを返します:

```py
>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
>>> inputs = tokenizer(text, return_tensors="pt")
```

入力をモデルに渡し、`logits`を返します:

```py
>>> from transformers import AutoModelForTokenClassification

>>> model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
>>> with torch.no_grad():
...     logits = model(**inputs).logits
```

最も高い確率を持つクラスを取得し、モデルの`id2label`マッピングを使用してテキストラベルに変換します:

```py
>>> predictions = torch.argmax(logits, dim=2)
>>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]
>>> predicted_token_class
['O',
 'O',
 'B-location',
 'I-location',
 'B-group',
 'O',
 'O',
 'O',
 'O',
 'O',
 'O',
 'O',
 'O',
 'B-location',
 'B-location',
 'O',
 'O']
```

