본문 바로가기
  • 컴공생의 공부 일기
  • 공부보단 일기에 가까운 것 같은
  • 블로그
🤖 AI/AI

🔬트랜스포머 모델을 다루기 위한 허깅페이스 트랜스포머 라이브러리 3

by 정람지 2025. 1. 7.

LLM을 활용한 실전 AI 애플리케이션 개발

- 허정준


🔬모델 추론하기

학습 시 제공하는 trainer api 처럼

모델 활용을 쉽게 제공하는 파이프라인이 있다.

 

 

💧파이프라인을 활용한 추론

# 예제 3.30. 학습한 모델을 불러와 pipeline을 활용해 추론하기
# 실습을 새롭게 시작하는 경우 데이터셋 다시 불러오기 실행
# import torch
# import torch.nn.functional as F
# from datasets import load_dataset

# dataset = load_dataset("klue", "ynat", split="validation")
from transformers import pipeline

model_id = "본인의 아이디 입력/roberta-base-klue-ynat-classification"

model_pipeline = pipeline("text-classification", model=model_id)

model_pipeline(dataset["title"][:5])

토크나이저와 모델을 결합해 데이터의 전후차이와 모델 추론을 간단하게 수행하는 pipeline

작업 종류, 모델, 설정 등을 인자로 넘겨받음

 

💧직접 추론

#예제 3.31. 커스텀 파이프라인 구현
import torch
from torch.nn.functional import softmax
from transformers import AutoModelForSequenceClassification, AutoTokenizer

class CustomPipeline:
    def __init__(self, model_id):
        self.model = AutoModelForSequenceClassification.from_pretrained(model_id)
        self.tokenizer = AutoTokenizer.from_pretrained(model_id)
        self.model.eval()

    def __call__(self, texts):
        tokenized = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True)

        with torch.no_grad():
            outputs = self.model(**tokenized)
            logits = outputs.logits

        probabilities = softmax(logits, dim=-1)
        scores, labels = torch.max(probabilities, dim=-1)
        labels_str = [self.model.config.id2label[label_idx] for label_idx in labels.tolist()]

        return [{"label": label, "score": score.item()} for label, score in zip(labels_str, scores)]

custom_pipeline = CustomPipeline(model_id)
custom_pipeline(dataset['title'][:5])

- tokenizer를 통해 토큰을 수행

- 모델 추론 수행 

- 가장 큰 예측 확률을 갖는 클래스를 추출

결과 반환


 

 

 

Goldchea/roberta-base-klue-ynat-classification · Hugging Face

results This model is a fine-tuned version of klue/roberta-base on an unknown dataset. It achieves the following results on the evaluation set: Loss: 0.4743 Accuracy: 0.852 Model description More information needed Intended uses & limitations More informat

huggingface.co

 

 

결과값!!

[{'label': 'LABEL_1', 'score': 0.9703058004379272},
{'label': 'LABEL_2', 'score': 0.8553245067596436},
{'label': 'LABEL_0', 'score': 0.9539018273353577},
{'label': 'LABEL_1', 'score': 0.974513590335846},
{'label': 'LABEL_2', 'score': 0.9472144842147827}]

score 값

모델이 해당 텍스트를 특정 레이블로 분류할 확률 또는 확신도