🐍 Python

Hugging Face 파이프라인 사용법 총정리: 감정 분석부터 번역, 이미지 분류까지 한 번에!"

itstory(Booho) 2025. 2. 10. 17:29
728x90

1. pipeline에서 사용 가능한 주요 태스크(Task) 목록

Hugging Face의 pipeline에서 지원하는 주요 태스크들은 미리 정의된 문자열 값으로 사용됩니다.
즉, "sentiment-analysis", "text-generation", "translation", "question-answering" 등은 고정된 태스크 명입니다.

📌 주요 지원 태스크 (정해진 값)

 

태스크 이름 설명 대표적인 모델
"sentiment-analysis" 감정 분석 (긍정/부정) distilbert-base-uncased-finetuned-sst-2-english
"text-generation" 텍스트 생성 (GPT) gpt2, distilgpt2
"zero-shot-classification" 사전 학습 없이 텍스트 분류 facebook/bart-large-mnli
"ner" 개체명 인식 (Named Entity Recognition) dbmdz/bert-large-cased-finetuned-conll03-english
"question-answering" 질의응답 (QA) distilbert-base-cased-distilled-squad
"translation_en_to_fr" 영어 → 프랑스어 번역 t5-small, Helsinki-NLP/opus-mt-en-fr
"summarization" 문서 요약 facebook/bart-large-cnn
"fill-mask" 마스킹된 단어 예측 bert-base-uncased
"text2text-generation" 일반적인 입력-출력 변환 t5-small
"conversational" 대화 (챗봇) facebook/blenderbot-400M-distill
"feature-extraction" 벡터 표현 추출 bert-base-uncased
"text-classification" 일반적인 텍스트 분류 distilbert-base-uncased-finetuned-sst-2-english
"speech-to-text" 음성을 텍스트로 변환 facebook/wav2vec2-base-960h
"text-to-speech" 텍스트를 음성으로 변환 espnet/kan-bayashi_ljspeech
"automatic-speech-recognition" 자동 음성 인식 openai/whisper-small
"image-classification" 이미지 분류 google/vit-base-patch16-224
"object-detection" 객체 탐지 facebook/detr-resnet-50

2. pipeline 사용 예제

각 태스크는 pipeline(task_name) 형식으로 사용되며, Hugging Face의 사전 학습된 모델을 자동으로 불러옵니다.

모델불러오기

✅ 감정 분석 (Sentiment Analysis)

 

📌 출력 예시:


✅ 텍스트 생성 (Text Generation)

# 문장 생성 모델 가져오기 => 디폴트는 openai-community/gpt2
text_generator=pipeline('text-generation')

result=text_generator('Once upon a time ain a ')

 

📌 출력 예시:

[{'generated_text': 'Once upon a time ain a _____-n, it went right to the center, and the heart of that country. 
The King made that whole line of islands, and 
I do believe in them, that he gave them a right as to all'}]

✅ 질의응답 (Question Answering)

qa_pipeline = pipeline("question-answering")
result = qa_pipeline(
    question="What is Hugging Face?",
    context="Hugging Face is a company that develops natural language processing tools."
)
print(result)

 

📌 출력 예시:

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

✅ 문서요약( summarization)

summarizer = pipeline("summarization")

text='''The Transformer model is a deep learning model introduced in 2017 that has revolutionized the field of natural language processing. 
Unlike traditional RNN-based architectures, it relies on a mechanism called self-attention to process words in a sentence in parallel, 
making it more efficient and powerful for various NLP tasks.'''

summarizer(text, max_length = 50, min_length = 20)

 

📌 출력 예시:

[{'summary_text': ' The Transformer model is a deep learning model introduced in 2017 that has revolutionized the field of natural language processing . 
Unlike traditional RNN-based architectures, it relies on a mechanism called self-attention to process words in a sentence'}]

✅ 이미지분류( image-classification )

classifier('/content/drive/MyDrive/data/자전거.jpeg')

 

📌 출력 예시:

[{'label': 'tricycle, trike, velocipede', 'score': 0.5273810625076294},
 {'label': 'bicycle-built-for-two, tandem bicycle, tandem',
  'score': 0.39376407861709595},
 {'label': 'mountain bike, all-terrain bike, off-roader',
  'score': 0.023689456284046173},
 {'label': 'moped', 'score': 0.012169924564659595},
 {'label': 'disk brake, disc brake', 'score': 0.0022162729874253273}]

✅ 번역( opus-mt-ko-en)

 

model("안녕하세요")


✅ 객체 탐지 (object-detection)

 

설치 및 실행을 했을때 컴퓨터의 언어로 나 온다. 

우리가 보기 좋도록 편환 해보자 

 

result 라는 변수로 저장 한 후 사람이 보기 좋은 모습을 변환한다.

 


3. 커스텀 모델 적용 가능

기본적으로 pipeline은 Hugging Face의 사전 학습된 모델을 자동으로 사용하지만, 특정 모델을 지정할 수도 있습니다.

예를 들어, distilbert-base-uncased-finetuned-sst-2-english를 직접 지정할 수 있습니다

 

text_gen2 = pipeline('text-generation',model='facebook/opt-13b')

 

4. 결론

✅ "sentiment-analysis" 같은 태스크 이름은 미리 정해진 값이며, pipeline에서 바로 사용할 수 있습니다.
✅ NLP 외에도 음성 처리(Speech-to-Text), 이미지 분류(Image Classification) 같은 다양한 태스크를 지원합니다.
✅ 기본 모델을 사용하거나, 원하는 모델을 직접 지정하여 사용할 수도 있습니다.

Hugging Face의 pipeline을 활용하면 복잡한 딥러닝 모델도 간단한 코드 한 줄로 쉽게 실행할 수 있습니다! 🚀

 

 

 

728x90