텍스트 분류
텍스트 분류 (Text classification)
텍스트 분류는 텍스트에 라벨이나 클래스를 부여하는 흔한 NLP 작업이에요. 주요 기업들이 생산 환경에서 다양한 실용적인 용도로 텍스트 분류를 돌리고 있죠. 텍스트 분류의 가장 대표적인 형태 중 하나는 감성 분석(sentiment analysis)으로, 텍스트 시퀀스에 🙂 긍정, 🙁 부정, 😐 중립 같은 라벨을 붙이는 작업이에요.
출처: 문서
본문
이 가이드에서는 다음을 배워요:
- IMDb 데이터셋에서 DistilBERT를 파인튜닝해서 영화 리뷰가 긍정인지 부정인지 판별하기.
- 파인튜닝한 모델을 추론(inference)에 사용하기.
이 작업과 호환되는 모든 아키텍처와 체크포인트를 보려면 task-page를 확인하는 걸 추천해요.
시작하기 전에 필요한 라이브러리를 모두 설치했는지 확인해요:
pip install transformers datasets evaluate accelerate
Hugging Face 계정에 로그인해서 모델을 커뮤니티에 업로드하고 공유하는 걸 권장해요. 로그인하라는 메시지가 나오면 토큰을 입력해서 로그인하세요:
>>> from huggingface_hub import notebook_login
>>> notebook_login()
IMDb 데이터셋 로드
먼저 🤗 Datasets 라이브러리에서 IMDb 데이터셋을 로드해요:
>>> from datasets import load_dataset
>>> imdb = load_dataset("stanfordnlp/imdb")
그다음 예시 하나를 살펴봐요:
>>> 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 토크나이저를 로드하는 거예요:
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
text를 토크나이즈하고 시퀀스가 DistilBERT의 최대 입력 길이를 넘지 않도록 자르는 전처리 함수를 만들어요:
>>> def preprocess_function(examples):
... return tokenizer(examples["text"], truncation=True)
전처리 함수를 전체 데이터셋에 적용하려면 🤗 Datasets의 map 함수를 사용해요. batched=True를 설정하면 데이터셋의 여러 요소를 한 번에 처리할 수 있어서 map을 빠르게 할 수 있어요:
tokenized_imdb = imdb.map(preprocess_function, batched=True)
이제 DataCollatorWithPadding을 사용해 예시 배치를 만들어요. 콜레이션(collation) 과정에서 데이터셋 전체를 최대 길이로 패딩하는 것보다 배치 안의 문장들을 가장 긴 길이에 맞춰 동적으로 패딩하는 편이 더 효율적이에요.
>>> from transformers import DataCollatorWithPadding
>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
평가
학습 중에 메트릭을 포함하면 모델의 성능을 평가하는 데 종종 도움이 돼요. 🤗 Evaluate 라이브러리로 평가 방법을 빠르게 로드할 수 있어요. 이 작업에서는 accuracy 메트릭을 로드해요 (메트릭을 로드하고 계산하는 방법은 🤗 Evaluate quick tour를 참고하세요):
>>> import evaluate
>>> accuracy = evaluate.load("accuracy")
그다음 예측값과 라벨을 compute에 넘겨 정확도를 계산하는 함수를 만들어요:
>>> 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 함수를 쓸 준비가 됐어요. 학습을 설정할 때 다시 사용하게 될 거예요.
학습
모델 학습을 시작하기 전에 기대되는 id와 라벨 사이의 매핑을 id2label, label2id로 만들어요:
>>> id2label = {0: "NEGATIVE", 1: "POSITIVE"}
>>> label2id = {"NEGATIVE": 0, "POSITIVE": 1}
Trainer로 모델을 파인튜닝하는 방법에 익숙하지 않다면 여기의 기본 튜토리얼을 확인해 보세요!
이제 모델 학습을 시작할 준비가 됐어요! DistilBERT를 AutoModelForSequenceClassification로 로드하고, 기대되는 라벨 개수와 라벨 매핑을 함께 전달해요:
>>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
>>> model = AutoModelForSequenceClassification.from_pretrained(
... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
... )
이 시점에서 남은 단계는 세 가지뿐이에요:
- TrainingArguments에서 학습 하이퍼파라미터를 정의해요. 유일하게 필수인 파라미터는 모델을 저장할 위치를 지정하는
output_dir이에요.push_to_hub=True로 설정하면 모델을 Hub에 푸시할 수 있어요 (모델을 업로드하려면 Hugging Face에 로그인해야 해요). 각 에폭이 끝날 때마다 Trainer가 정확도를 평가하고 학습 체크포인트를 저장해요. - 학습 인수를 Trainer에 모델, 데이터셋, 토크나이저, 데이터 콜레이터,
compute_metrics함수와 함께 전달해요. - train()을 호출해서 모델을 파인튜닝해요.
>>> 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()
Trainer에 tokenizer를 전달하면 기본적으로 동적 패딩을 적용해요. 이 경우 데이터 콜레이터를 명시적으로 지정할 필요가 없어요.
학습이 완료되면 push_to_hub() 메서드로 모델을 Hub에 공유해서 모두가 쓸 수 있게 해요:
>>> trainer.push_to_hub()
텍스트 분류용으로 모델을 파인튜닝하는 더 심층적인 예시는 해당 PyTorch notebook을 참고하세요.
추론 (Inference)
좋아요, 이제 모델을 파인튜닝했으니 추론에 활용할 수 있어요!
추론을 실행하고 싶은 텍스트를 가져와요:
>>> 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()에서 쓰는 거예요. 모델로 감성 분석용 pipeline을 만들고 텍스트를 전달해요:
>>> from transformers import pipeline
>>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model")
>>> classifier(text)
[{'label': 'POSITIVE', 'score': 0.9994940757751465}]
원한다면 pipeline의 결과를 직접 재현할 수도 있어요:
텍스트를 토크나이즈하고 PyTorch 텐서로 반환해요:
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model")
>>> inputs = tokenizer(text, return_tensors="pt")
입력을 모델에 전달하고 logits를 반환해요:
>>> import torch
>>> from transformers import AutoModelForSequenceClassification
>>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model")
>>> with torch.no_grad():
... logits = model(**inputs).logits
가장 높은 확률을 가진 클래스를 가져오고, 모델의 id2label 매핑을 사용해 텍스트 라벨로 변환해요:
>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
'POSITIVE'