Transformers documentation

토큰 분류

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

토큰 분류

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

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

  1. WNUT 17 데이터셋에서 DistilBERT를 fine-tuning하여 새로운 엔티티를 감지합니다.
  2. 파인튜닝한 모델을 추론에 사용하세요.

이 작업과 호환되는 모든 아키텍처와 체크포인트를 확인하려면 task-page를 참고하는 것을 권장합니다.

시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:

pip install transformers datasets evaluate seqeval

모델을 업로드하고 커뮤니티와 공유할 수 있도록 Hugging Face 계정에 로그인하는 것을 권장합니다. 프롬프트가 표시되면 로그인할 토큰을 입력하세요:

>>> from huggingface_hub import notebook_login

>>> notebook_login()

WNUT 17 데이터셋 로드

🤗 Datasets 라이브러리에서 WNUT 17 데이터셋을 로드하는 것으로 시작합니다:

>>> from datasets import load_dataset

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

다음은 예시입니다:

>>> 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의 각 숫자는 엔티티를 나타냅니다. 엔티티가 무엇인지 확인하려면 숫자를 라벨 이름으로 변환하세요:

>>> 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 토크나이저를 로드하는 것입니다:

>>> from transformers import AutoTokenizer

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

위 예시의 tokens 필드에서 보았듯이, 입력이 이미 토큰화된 것처럼 보입니다. 하지만 실제로는 입력이 아직 토큰화되지 않았으며, 단어를 서브워드로 토큰화하려면 is_split_into_words=True를 설정해야 합니다. 예를 들어:

>>> 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 메서드를 사용하여 모든 토큰을 해당 단어에 매핑합니다.
  2. 특수 토큰 [CLS]와 [SEP]에 라벨 -100을 할당하여 PyTorch 손실 함수(CrossEntropyLoss 참고)에서 무시되도록 합니다.
  3. 주어진 단어의 첫 번째 토큰만 라벨링합니다. 같은 단어의 다른 서브토큰에는 -100을 할당합니다.

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

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

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

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

>>> from transformers import DataCollatorForTokenClassification

>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)

평가

학습 중에 메트릭을 포함하는 것은 모델의 성능을 평가하는 데 도움이 되는 경우가 많습니다. 🤗 Evaluate 라이브러리를 사용하면 평가 방법을 빠르게 로드할 수 있습니다. 이 작업을 위해 seqeval 프레임워크를 로드합니다(메트릭을 로드하고 계산하는 방법에 대해 자세히 알아보려면 🤗 Evaluate quick tour를 참고하세요). Seqeval은 실제로 precision, recall, F1, accuracy 등 여러 점수를 생성합니다.

>>> import evaluate

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

먼저 NER 라벨을 가져온 다음, 실제 예측값과 실제 라벨을 compute에 전달하여 점수를 계산하는 함수를 만듭니다:

>>> 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와 라벨의 매핑을 생성하세요:

>>> 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를 사용하여 모델을 fine-tuning하는 방법에 대해 잘 모르신다면, 여기의 기본 튜토리얼을 참고하세요!

이제 모델을 학습시킬 준비가 되었습니다! AutoModelForTokenClassification로 DistilBERT를 로드하고, 예상되는 라벨 수와 라벨 매핑을 함께 지정하세요:

>>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer

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

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

  1. TrainingArguments에서 학습 하이퍼파라미터를 정의합니다. 필수 파라미터는 모델 저장 위치를 지정하는 output_dir 하나뿐입니다. push_to_hub=True를 설정하여 모델을 Hub에 업로드할 수 있습니다(모델 업로드를 위해 Hugging Face에 로그인되어 있어야 합니다). 각 epoch가 끝나면 Trainer가 seqeval 점수를 평가하고 학습 체크포인트를 저장합니다.
  2. 모델, 데이터셋, 토크나이저, 데이터 콜레이터, compute_metrics 함수와 함께 학습 인수를 Trainer에 전달합니다.
  3. 모델을 파인튜닝하려면 train()을 호출하세요.
>>> 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() 메서드를 사용하여 모델을 Hub에 공유하여 누구나 모델을 사용할 수 있도록 하세요:

>>> trainer.push_to_hub()

토큰 분류를 위해 모델을 파인튜닝하는 방법에 대한 더 자세한 예제는 해당 PyTorch 노트북을 참고하세요.

추론

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

이 추론을 실행할 텍스트를 준비하세요:

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

파인튜닝한 모델을 추론에 적용해 보는 가장 간단한 방법은 pipeline()에서 사용하는 것입니다. 해당 모델로 NER용 pipeline을 생성한 후, 텍스트를 전달하세요:

>>> 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 텐서를 반환합니다:

>>> from transformers import AutoTokenizer

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

입력을 모델에 전달하고 logits를 반환합니다:

>>> from transformers import AutoModelForTokenClassification

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

가장 높은 확률을 가진 클래스를 가져오고, 모델의 id2label 매핑을 사용해 이를 텍스트 레이블로 변환합니다:

>>> 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']
Update on GitHub