본문 바로가기
Deep Learning

Hugging Face Transformers Pipeline으로 사전 훈련된 모델 간편 실행하기

by ssury94 2025. 2. 20.

 

Hugging Face의 transformers 라이브러리

자연어 처리(NLP) 및 컴퓨터 비전(CV) 분야에서 사전 훈련된 딥러닝 모델을 쉽게 활용할 수 있도록 만든 라이브러리입니다.

BERT, GPT, T5, RoBERTa, Whisper 등 다양한 Transformer 기반 모델을 제공하며, 간단한 코드만으로 강력한 AI 모델을 사용할 수 있습니다.
Text Generation : 텍스트 생성

 

 

🎯 1. Hugging Face Transformers의 주요 기능

사전 훈련된 모델 사용 가능

  • BERT, GPT-2, T5, LLaMA, Falcon 등 최신 AI 모델을 바로 가져와 사용 가능

다양한 AI 작업 지원

  • 자연어 처리(NLP): 텍스트 생성, 감정 분석, 기계 번역, 문서 요약, 질의 응답 등
  • 음성 처리(Audio): 음성 인식, TTS(Text-to-Speech) 등
  • 컴퓨터 비전(CV): 이미지 분류, 객체 탐지 등

PyTorch 및 TensorFlow 모두 지원

  • 동일한 코드로 PyTorch와 TensorFlow에서 모델을 실행 가능

Hugging Face Hub와 연동

  • from_pretrained() 함수를 이용해 최신 모델을 쉽게 다운로드하여 사용 가능

 

🛠 2. 설치 방법

Hugging Face transformers 라이브러리는 아래 명령어로 설치할 수 있습니다.

pip install transformers

PyTorch 또는 TensorFlow도 함께 설치하려면:

pip install torch tensorflow transformers

 

📌 3. 기본 사용법

① 사전 훈련된 모델 로드

from transformers import pipeline

# 감정 분석 모델 로드
classifier = pipeline("sentiment-analysis")

# 테스트 실행
result = classifier("I love using Hugging Face Transformers!")
print(result)

출력:

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

 

No model was supplied, defaulted to distilbert/distilbert-base-uncased-finetuned-sst-2-english and revision 714eb0f (https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english). Using a pipeline without specifying a model name and revision in production is not recommended. Device set to use cpu

 

distilbert/distilbert-base-uncased-finetuned-sst-2-english · Hugging Face

DistilBERT base uncased finetuned SST-2 Table of Contents Model Details Model Description: This model is a fine-tune checkpoint of DistilBERT-base-uncased, fine-tuned on SST-2. This model reaches an accuracy of 91.3 on the dev set (for comparison, Bert ber

huggingface.co

 

모델 설정을 별도로 하지 않을경우 기본값으로 distilbert-base-uncased-finetuned-sst-2-english 모델을 사용

 

 

기존 CPU 기반의 넘파이(행렬)처리방식- 대용량 데이터처리, 병렬처리가 어려움

safetensors 행렬처리의 등장 - GPU 활용, 높은 메모리 안정성, PyTorch와 함께 사용될 때, GPU로 직접 데이터를 로드할 수 있어 딥러닝에서 유리

 

 

 

# 1차원 2차원 고려 하지 않고 넣어도 적용된다. 학습된 모델이기때문에

#He always helps his friends.
#You are not listening carefully.

data=['You are not listening carefully.','He always helps his friends.']

classifier(data)

출력:

[{'label': 'NEGATIVE', 'score': 0.9989287257194519},
 {'label': 'POSITIVE', 'score': 0.9997738003730774}]

 

 

 

② 텍스트 생성 (GPT-2)

from transformers import pipeline

# GPT-2 텍스트 생성 모델
text_generator = pipeline("text-generation", model="gpt2")

# 문장 생성
output = text_generator("Once upon a time", max_length=50)
print(output)

 

No model was supplied, defaulted to openai-community/gpt2 and revision 607a30d (https://huggingface.co/openai-community/gpt2). Using a pipeline without specifying a model name and revision in production is not recommended. Device set to use cpu

 

openai-community/gpt2 · Hugging Face

GPT-2 Test the whole generation capabilities here: https://transformer.huggingface.co/doc/gpt2-large Pretrained model on English language using a causal language modeling (CLM) objective. It was introduced in this paper and first released at this page. Dis

huggingface.co

 

디폴트 모델 gpt2이 설정된다.

# 출력:
[{'generated_text': "Once upon a time in a distant land, you will make your way through a thousand fields to find the greatest treasure in the world. In that moment of despair, you will find the one true God that knows everything and won't let you fall."}]

 

해당 단어로 시작하는 문장을 만들어준다.

 

다른 모델 사용 하고 싶으면, 허깅페이스 text-generation 모델 테스크 에서 원하는 모델을 검색해보자

text_gen=pipeline('text-generation',model='EleutherAI/gpt-neo-1.3B')

 

 

③ 질의 응답 모델 사용

from transformers import pipeline

# 사전 훈련된 BERT 기반 질의 응답 모델
qa_pipeline = pipeline("question-answering")

context = "Hugging Face provides state-of-the-art machine learning models."
question = "Who provides machine learning models?"

result = qa_pipeline(question=question, context=context)
print(result)

출력:

{'score': 0.98, 'start': 0, 'end': 12, 'answer': 'Hugging Face'}

 

 

 

 

④ 번역 모델 사용

from transformers import pipeline


#한국어를 영어로 ko - en
model=pipeline('translation',model='Helsinki-NLP/opus-mt-ko-en')
model('나는 자연어 처리를 배우고 있습니다.')
#출력결과:
[{'translation_text': "I'm learning natural language processing."}]

 

🚀 4. 주요 지원 모델

Hugging Face transformers 라이브러리는 수천 개의 사전 훈련된 모델을 지원합니다.

  • 언어 모델: GPT-2, GPT-3, GPT-4, LLaMA, Falcon
  • 문서 이해: BERT, RoBERTa, ALBERT, DeBERTa
  • 번역 및 요약: T5, BART, mBART
  • 음성 및 비전: Whisper (음성 인식), CLIP (이미지-텍스트 매칭)

전체 모델 목록은 Hugging Face 모델 허브에서 확인할 수 있습니다.

 

 

🔥 5. Hugging Face transformers 라이브러리를 언제 사용할까?

챗봇, 텍스트 요약, 자동 번역, 감정 분석, 질의 응답, 코드 생성 같은 AI 서비스 개발할 때
딥러닝 모델을 직접 학습하지 않고 빠르게 활용하고 싶을 때
최신 대형 언어 모델(LLM, GPT, BERT, T5 등)을 사용하고 싶을 때

 

 

 

🎯 정리

특징 설명

사전 훈련된 모델 BERT, GPT-2, T5, RoBERTa 등 최신 모델 지원
다양한 작업 지원 감정 분석, 번역, 요약, 챗봇, 질의 응답 등
PyTorch & TensorFlow 호환 같은 코드로 PyTorch와 TensorFlow 실행 가능
Hugging Face Hub 연동 from_pretrained() 로 최신 모델 다운로드 가능

💡 결론: Hugging Face transformers는 NLP, 음성, 비전 AI 모델을 간단하게 사용할 수 있는 강력한 라이브러리! 🚀