본문 바로가기

02. 딥러닝

00012. [AI 쉽게 이해하기 시리즈] Hugging Face Transformers로 직접 써보자! (입문자를 위한 실습 가이드)

반응형

안녕하세요! 😄 오늘은 BERT, GPT, T5 같은 트랜스포머 기반 모델들을 실제로 사용할 수 있게 도와주는 오픈소스 라이브러리, Hugging Face Transformers를 소개해드릴게요.

코딩 초보자도 따라할 수 있도록 아주 쉽게 설명드릴게요!


1. Hugging Face Transformers란?

  • 다양한 트랜스포머 모델들을 한 줄 코드로 쓸 수 있게 해주는 라이브러리입니다.
  • BERT, GPT, T5, RoBERTa, DistilBERT 등 인기 모델들이 모두 포함돼 있어요.
  • 텍스트 분류, 번역, 요약, 질문응답 등 다양한 작업을 쉽게 해볼 수 있어요.

2. 설치 방법

pip install transformers
pip install torch

추가로 Jupyter Notebook에서 실습할 거면:

pip install notebook

3. 기본 사용 예시 – 문장 분류 with BERT

from transformers import pipeline

classifier = pipeline("sentiment-analysis")
result = classifier("I love this movie!")
print(result)

출력 예:

[{'label': 'POSITIVE', 'score': 0.9998}]

✔️ 단 한 줄로 감정 분석 끝! 모델, 토크나이저, 전처리, 후처리까지 자동으로 처리해줘요.


4. 텍스트 요약 with T5

summarizer = pipeline("summarization")
text = """
In a shocking finding, scientists discovered a herd of unicorns living in a remote,
previously unexplored valley, in the Andes Mountains. Even more surprising to the
researchers was the fact that the unicorns spoke perfect English.
"""
summary = summarizer(text)
print(summary[0]['summary_text'])

5. 텍스트 생성 with GPT-2

generator = pipeline("text-generation", model="gpt2")
result = generator("Once upon a time", max_length=50, num_return_sequences=1)
print(result[0]['generated_text'])

6. 질문 응답 with BERT 기반 모델

qa = pipeline("question-answering")
context = "Albert Einstein was a German-born theoretical physicist who developed the theory of relativity."
question = "Who developed the theory of relativity?"
answer = qa(question=question, context=context)
print(answer['answer'])

7. 모델 바꾸기 / 한국어 모델 사용하기

from transformers import pipeline
classifier = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
print(classifier("이 영화 정말 재밌어요!"))

Hugging Face 허브(huggingface.co/models)에서 다양한 한국어 모델도 찾을 수 있어요!


8. 핵심 요약 🧠

  • Hugging Face는 AI 실습의 끝판왕입니다.
  • 코드 한두 줄로 강력한 NLP 모델을 써볼 수 있어요.
  • 감정 분석, 생성, 요약, 번역, 질문응답까지 전부 가능!

9. 다음 편 예고

다음 포스팅에서는 이 모델들을 조금 더 커스터마이징해서 나만의 데이터로 파인튜닝(Fine-tuning) 하는 방법을 소개해드릴게요!

감사합니다 😊

반응형