# 텍스트 분류

Text classification은 텍스트에 라벨 또는 클래스를 할당하는 일반적인 NLP 작업입니다. 가장 큰 기업 중 일부는 다양한 실용적인 애플리케이션을 위해 Text classification을 프로덕션 환경에서 실행하고 있습니다. Text classification의 가장 인기 있는 형태 중 하나는 Sentiment analysis로, 텍스트 시퀀스에 🙂 positive, 🙁 negative, 또는 😐 neutral와 같은 라벨을 할당합니다.

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

1. [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased)를 [IMDb](https://huggingface.co/datasets/stanfordnlp/imdb) 데이터셋으로 fine-tuning하여 영화 리뷰가 긍정인지 부정인지를 판별합니다.
2. 파인튜닝한 모델을 추론에 사용하세요.

이 작업과 호환되는 모든 아키텍처와 체크포인트를 확인하려면 [task-page](https://huggingface.co/tasks/text-classification)를 참고하는 것을 권장합니다.

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

```bash
pip install transformers datasets evaluate accelerate
```

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

```py
>>> from huggingface_hub import notebook_login

>>> notebook_login()
```

## IMDb 데이터셋 로드

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

```py
>>> from datasets import load_dataset

>>> imdb = load_dataset("stanfordnlp/imdb")
```

다음은 예시입니다:

```py
>>> imdb["test"][0]
{
    "label": 0,
    "text": "I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, under-appreciated and misunderstood. I tried to like this, I really did, but it is to good TV sci-fi as Babylon 5 is to Star Trek (the original). Silly prosthetics, cheap cardboard sets, stilted dialogues, CG that doesn't match the background, and painfully one-dimensional characters cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi TV. It's not. It's clichéd and uninspiring.) While US viewers might like emotion and character development, sci-fi is a genre that does not take itself seriously (cf. Star Trek). It may treat important issues, yet not as a serious philosophy. It's really difficult to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions are wooden and predictable, often painful to watch. The makers of Earth KNOW it's rubbish as they have to always say \"Gene Roddenberry's Earth...\" otherwise people would not continue watching. Roddenberry's ashes must be turning in their orbit as this dull, cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space. Spoiler. So, kill off a main character. And then bring him back as another actor. Jeeez! Dallas all over again.",
}
```

이 데이터셋에는 두 개의 필드가 있습니다:

- `text`: 영화 리뷰 텍스트.
- `label`: 부정적인 리뷰인 경우 `0`, 긍정적인 리뷰인 경우 `1`인 값

## 전처리

다음 단계는 `text` 필드를 전처리하기 위해 DistilBERT 토크나이저를 로드하는 것입니다:

```py
>>> from transformers import AutoTokenizer

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

`text`를 토큰화하고 시퀀스를 DistilBERT의 최대 입력 길이를 초과하지 않도록 잘라내는 전처리 함수를 만듭니다:

```py
>>> def preprocess_function(examples):
...     return tokenizer(examples["text"], truncation=True)
```

전체 데이터셋에 전처리 함수를 적용하려면 🤗 Datasets의 [map](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset.map) 함수를 사용합니다. `batched=True`를 설정하여 데이터셋의 여러 요소를 한 번에 처리하면 `map`의 속도를 높일 수 있습니다:

```py
tokenized_imdb = imdb.map(preprocess_function, batched=True)
```

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

```py
>>> from transformers import DataCollatorWithPadding

>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
```

## 평가

학습 중에 메트릭을 포함하는 것은 모델 성능을 평가하는 데 도움이 되는 경우가 많습니다. 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리를 사용하면 평가 방법을 빠르게 로드할 수 있습니다. 이 작업에서는 [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) 메트릭을 로드합니다(메트릭을 로드하고 계산하는 방법에 대해 자세히 알아보려면 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour)를 참고하세요):

```py
>>> import evaluate

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

이후 예측값과 라벨을 [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute)에 전달하여 정확도를 계산하는 함수를 만듭니다:

```py
>>> import numpy as np

>>> def compute_metrics(eval_pred):
...     predictions, labels = eval_pred
...     predictions = np.argmax(predictions, axis=1)
...     return accuracy.compute(predictions=predictions, references=labels)
```

`compute_metrics` 함수가 이제 준비되었습니다. 학습을 설정할 때 다시 이 함수를 사용하게 됩니다.

## 학습

모델을 학습하기 전에 `id2label`과 `label2id`를 사용하여 예상 id와 라벨의 매핑을 생성하세요:

```py
>>> id2label = {0: "NEGATIVE", 1: "POSITIVE"}
>>> label2id = {"NEGATIVE": 0, "POSITIVE": 1}
```

[Trainer](/docs/transformers/v5.23.0/ko/main_classes/trainer#transformers.Trainer)를 사용하여 모델을 fine-tuning하는 방법에 익숙하지 않다면, [여기](../training)의 기본 튜토리얼을 참고하세요!

이제 모델을 학습할 준비가 되었습니다! [AutoModelForSequenceClassification](/docs/transformers/v5.23.0/ko/model_doc/auto#transformers.AutoModelForSequenceClassification)로 DistilBERT를 로드하고, 예상되는 라벨 수와 라벨 매핑을 지정하세요:

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

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

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

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

```py
>>> training_args = TrainingArguments(
...     output_dir="my_awesome_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_imdb["train"],
...     eval_dataset=tokenized_imdb["test"],
...     processing_class=tokenizer,
...     data_collator=data_collator,
...     compute_metrics=compute_metrics,
... )

>>> trainer.train()
```

`tokenizer`를 [Trainer](/docs/transformers/v5.23.0/ko/main_classes/trainer#transformers.Trainer)에 전달하면 기본적으로 동적 패딩이 적용됩니다. 이 경우 데이터 콜레이터를 명시적으로 지정할 필요가 없습니다.

학습이 완료되면 [push_to_hub()](/docs/transformers/v5.23.0/ko/main_classes/trainer#transformers.Trainer.push_to_hub) 메서드를 사용하여 모델을 Hub에 공유하여 누구나 모델을 사용할 수 있도록 하세요:

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

텍스트 분류를 위해 모델을 fine-tune하는 방법에 대한 더 자세한 예제는 해당 [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)을 참고하세요.

## 추론

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

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

```py
>>> text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three."
```

파인튜닝한 모델을 추론에 적용해 보는 가장 간단한 방법은 [pipeline()](/docs/transformers/v5.23.0/ko/main_classes/pipelines#transformers.pipeline)을 사용하는 것입니다. 해당 모델로 감성 분석용 `pipeline`을 생성한 후, 텍스트를 전달하세요:

```py
>>> from transformers import pipeline

>>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model")
>>> classifier(text)
[{'label': 'POSITIVE', 'score': 0.9994940757751465}]
```

원하시는 경우 `pipeline`의 결과를 수동으로 재현할 수도 있습니다:

텍스트를 토큰화하고 PyTorch 텐서를 반환합니다:

```py
>>> from transformers import AutoTokenizer

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

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

```py
>>> import torch
>>> from transformers import AutoModelForSequenceClassification

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

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

```py
>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
'POSITIVE'
```

