# 토큰 분류

Token classification은 문장 내 개별 token에 라벨을 할당합니다. 가장 일반적인 token classification 작업 중 하나는 Named Entity Recognition(NER)입니다. NER은 사람, 위치, 조직과 같은 문장 내 각 entity에 라벨을 할당하는 것을 목표로 합니다.

이 가이드에서는 다음 내용을 보여 드립니다:

1. [WNUT 17](https://huggingface.co/datasets/flaitenberger/wnut_17) 데이터셋에서 [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased)를 fine-tuning하여 새로운 엔티티를 감지합니다.
2. 파인튜닝한 모델을 추론에 사용하세요.

이 작업과 호환되는 모든 아키텍처와 체크포인트를 확인하려면 [task-page](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. [word_ids](/docs/transformers/v5.24.0/ko/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`을 할당합니다.

…의 최대 입력 길이를 초과하지 않도록 토큰과 라벨을 재정렬하고 시퀀스를 잘라내는 함수를 만드는 방법은 다음과 같습니다:

```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) 함수를 사용합니다. `batched=True`를 설정하여 데이터셋의 여러 요소를 한 번에 처리하면 `map` 함수의 속도를 높일 수 있습니다:

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

이제 [DataCollatorWithPadding](/docs/transformers/v5.24.0/ko/main_classes/data_collator#transformers.DataCollatorWithPadding)을 사용하여 예시 배치(batch)를 생성합니다. 데이터셋 전체를 최대 길이에 맞게 패딩하는 대신, collation 단계에서 배치 내 가장 긴 길이에 맞춰 문장을 *동적으로 패딩*하는 것이 더 효율적입니다.

```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 [quick tour](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/ko/main_classes/trainer#transformers.Trainer)를 사용하여 모델을 fine-tuning하는 방법에 익숙하지 않다면, [여기](../training)의 기본 튜토리얼을 참고하세요!

이제 모델을 학습할 준비가 되었습니다! [AutoModelForTokenClassification](/docs/transformers/v5.24.0/ko/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
... )
```

이 시점에서 남은 단계는 단 세 가지입니다:

1. [TrainingArguments](/docs/transformers/v5.24.0/ko/main_classes/trainer#transformers.TrainingArguments)에서 학습 하이퍼파라미터를 정의합니다. 필수 파라미터는 모델 저장 위치를 지정하는 `output_dir` 하나뿐입니다. `push_to_hub=True`를 설정하여 이 모델을 Hub에 업로드할 수 있습니다(모델 업로드를 위해 Hugging Face에 로그인되어 있어야 합니다). 각 에포크가 끝날 때마다 [Trainer](/docs/transformers/v5.24.0/ko/main_classes/trainer#transformers.Trainer)는 seqeval 점수를 평가하고 학습 체크포인트를 저장합니다.
2. 모델, 데이터셋, 토크나이저, 데이터 콜레이터, `compute_metrics` 함수와 함께 학습 인수를 [Trainer](/docs/transformers/v5.24.0/ko/main_classes/trainer#transformers.Trainer)에 전달합니다.
3. 모델을 파인튜닝하려면 [train()](/docs/transformers/v5.24.0/ko/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/ko/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)을 참고하세요.

## 추론

좋습니다. 이제 모델을 fine-tuning 했으므로 추론에 사용할 수 있습니다!

inference를 실행할 텍스트를 준비하세요:

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

파인튜닝한 모델을 추론에 적용해 보는 가장 간단한 방법은 [pipeline()](/docs/transformers/v5.24.0/ko/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']
```

