[NLP 20] HuggingFace : pipeline 함수

방선생·2025년 2월 5일
0

Natural Language Processing

목록 보기
20/22

HuggingFace 라이브러리 pipeline() 함수

  • pipeline() 함수
    1) transformers 라이브러리의 가장 기본적인 함수
    2) 사전 학습된 모델과 토크나이저를 연결하여 자연어 처리에 관한 작업을 편리하게 할 수 있도록 지원

  • 사용법(예시)
    1) pipeline 함수 실행 : classifier = pipeline(‘text-classification’ ,model ,tokenizer)
    2) 문서 분류 실행 : classifier(sentence)

pipeline task
1. 문서 분류(text-classification)
2. 문서 요약(text summarization)
3. 기계 독해(MRC)
4. 문장 생성(text generation)


transformers.pipeline 파라미터

  • task: 수행할 NLP 작업의 종류 (예: sentiment-analysis, text-generation, translation)
  • model: 사용할 사전 학습된 모델의 이름 또는 경로 (예: 'bert-base-uncased')
  • config: 모델의 설정 파일 또는 PretrainedConfig 객체
  • tokenizer: 텍스트를 토큰으로 변환하기 위한 토크나이저 또는 토크나이저 이름
  • feature_extractor: 이미지나 오디오 데이터에서 특징을 추출하는 모델 또는 객체를 지정
  • image_processor: 이미지를 처리하고 전처리하는 데 사용되는 객체를 지정
  • framework: 사용할 프레임워크 선택 ('pt' for PyTorch, 'tf' for TensorFlow)
  • revision: 모델 저장소의 특정 버전이나 커밋을 지정
  • use_fast: FastTokenizer 사용 여부 (기본값: True)
  • token: 허깅페이스 허브에서 비공개 모델을 다운로드할 때 사용할 인증 토큰 (또는 use_auth_token과 동일한 역할)
  • device: 모델을 실행할 장치 지정 (CPU: 1, GPU: 0)
  • device_map: 모델의 각 레이어를 어느 디바이스(CPU, GPU)에서 실행할지 설정
  • torch_dtype: PyTorch에서 모델을 실행할 때 사용할 데이터 타입(예: torch.float16)
  • trust_remote_code: 모델 저장소에 사용자 정의 Python 코드를 포함할 때 그 코드를 신뢰할지 여부 (True로 설정 시 리모트 코드 실행 허용)
  • model_kwargs: 모델에 전달할 추가 인자들
  • pipeline_class: 파이프라인 클래스를 명시적으로 지정하여 커스텀 파이프라인을 사용할 수 있게 설정



(이 시리즈의 모든 코드는 코랩환경에서 Python으로 작성하였습니다)

# 필요한 함수 임폴트
from transformers import pipeline

text classification Code 1 (영어 예제 텍스트 감성 분석)

# pipeline 함수 호출, 분류 모델 다운로드
classifier = pipeline(task='text-classification')

# test data 생성
test_data = ["The restaurant is awesome", "The restaurant is awful"]
fin_text = ['Stocks rallied and the British pound gained.']
# 감성 분석 실행
result1 = classifier(test_data)
result2 = classifier(fin_text)

# 결과 확인하기
print(result1)
print(result2)

text classification Code 2 (한국어 예제 텍스트 감성 분석)

# 한국어 텍스트 감성 분석

# pipeline 모델 생성
model_name='doya/klue-sentiment-nsmc'
classifier = pipeline(task='text-classification', model=model_name)

# text 생성
text=['음악이 주가 된, 최고의 음악영화', '발연기 도저히 못보겠다 진짜 이렇게 연기를 못할거라곤 상상도 못했네']

# 감성 분석 실행
result = classifier(text)

# 결과 확인하기
print(result)

text classification Code 3 (영어 경제 기사 감성 분석)

# 영어로된 경제 기사의 감성 분석 전문 모델 사용

# pipeline 모델 생성
model_name='ProsusAI/finbert'
finbert = pipeline(task='text-classification', model=model_name)

# text 생성
fin_text = ['Stocks rallied and the British pound gained.']

# 감성 분석 실행
result = finbert(fin_text)

# 결과 확인하기
print(result)
  • Hugging Face - finbert
    • 경제 기사 데이터 기반 Text Classification
    • 주로 주식매매에 사용됨

text classification Code 4 (한국어 경제 기사 감성 분석)

# 한글로된 경제 기사의 감성 분석 전문 모델 사용

# pipeline 모델 생성
model_name='snunlp/KR-FinBert-SC'
ko_finbert = pipeline(task='text-classification', model=model_name)

# text 생성
text = ["쇼핑몰 '알렛츠'도 갑자기 영업종료…'제2의 티메프 사태 우려'"]

# 감성 분석 실행
result = ko_finbert(text)

# 결과 확인하기
print(result)

text classification Code 5 (질병 분류 모델 사용)

# 증상 --> 질병 분류를 해주는 모델

# pipeline 모델 생성
model_name='achDev/medicalBert'
medical_bert = pipeline(task='text-classification', model=model_name)

# text 생성
text=["Round nodules or lumps are observed in the lungs, and metastasis to surrounding lymph nodes or other organs is identified.",
      "As a result of increased thirst, individuals with diabetes may need to urinate more often"]

# 감성 분석 실행
result = medical_bert(text)

# 결과 확인하기
print(result)



여기서 학습 시켰던 모델을 활용하여 진행합니다

text classification Code 6 (필요한 함수 임폴트)

# 파인 튜닝 모델 사용 --> 한국어 텍스트 감성 분석

# 필요한 함수 임폴트
from transformers import pipeline
from transformers import AutoTokenizer
from transformers import TFBertForSequenceClassification, TFElectraForSequenceClassification

text classification Code 7 (파인 튜닝된 BERT 다국어 모델 사용)

# 토크나이저 생성(다운로드)
tokenizer_mul = AutoTokenizer.from_pretrained('google-bert/bert-base-multilingual-cased')

# BERT 한국어 텍스트 분류 모델 다운로드(파인 튜닝한 모델 연결)
mul_path = '/content/drive/MyDrive/NLP/tf_mul'
model_mul = TFBertForSequenceClassification.from_pretrained(mul_path)

# BERT 한국어 텍스트 분류 모델 생성
classifier_mul = pipeline(task='text-classification', model=model_mul, tokenizer=tokenizer_mul)

# text 생성
text=['음악이 주가 된, 최고의 음악영화', '발연기 도저히 못보겠다 진짜 이렇게 연기를 못할거라곤 상상도 못했네']

# 감성 분석 실행
result1 = classifier_mul(text)
# 결과 확인하기
print(f'파인 튜닝한 BEERT 한국어 텍스트 분류 모델을 이용한 텍스트 감성 분석 : \n{result1}')

text classification Code 8 (파인 튜닝된 BERT 한국어 모델 사용)

# 토크나이저 생성(다운로드)
tokenizer_klue = AutoTokenizer.from_pretrained('klue/bert-base')

# BERT 한국어 텍스트 분류 모델 다운로드(파인 튜닝한 모델 연결)
klue_path = '/content/drive/MyDrive/NLP/tf_ko'
model_klue = TFBertForSequenceClassification.from_pretrained(klue_path)

# BERT 한국어 텍스트 분류 모델 생성
classifier_klue = pipeline(task='text-classification', model=model_klue, tokenizer=tokenizer_klue)

# text 생성
text=['음악이 주가 된, 최고의 음악영화', '발연기 도저히 못보겠다 진짜 이렇게 연기를 못할거라곤 상상도 못했네']

# 감성 분석 실행
result2 = classifier_klue(text)
# 결과 확인하기
print(f'파인 튜닝한 BEERT 한국어 텍스트 분류 모델을 이용한 텍스트 감성 분석 : \n{result2}')
  • BERT > roBERT > Electra으로 발전됨

text classification Code 9 (파인 튜닝된 Electra 한국어 모델 사용)

# 토크나이저 생성(다운로드)
tokenizer_ele = AutoTokenizer.from_pretrained('beomi/KcELECTRA-base-v2022')

# BERT 한국어 텍스트 분류 모델 다운로드(파인 튜닝한 모델 연결)
ele_path = '/content/drive/MyDrive/NLP/tf_ele'
model_ele = TFBertForSequenceClassification.from_pretrained(ele_path)

# BERT 한국어 텍스트 분류 모델 생성
classifier_ele = pipeline(task='text-classification', model=model_ele, tokenizer=tokenizer_ele)

# text 생성
text=['음악이 주가 된, 최고의 음악영화', '발연기 도저히 못보겠다 진짜 이렇게 연기를 못할거라곤 상상도 못했네']

# 감성 분석 실행
result2 = classifier_ele(text)
# 결과 확인하기
print(f'파인 튜닝한 BEERT 한국어 텍스트 분류 모델을 이용한 텍스트 감성 분석 : \n{result2}')

summarization Code 1 (기본 요약 모델 사용)

# 기본 모델 생성
summarizer = pipeline(task='summarization')

# 문서 요약에 사용할 텍스트 데이터 생성
text = '''The tower is 324 meters (1,063 ft) tall, about the same height as
an 81-storey building, and the tallest structure in Paris. Its base is square,
measuring 125 meters (410 ft) on each side. During its construction, the Eiffel
Tower surpassed the Washington Monument to become the tallest man-made structure
in the world, a title it held for 41 years until the Chrysler Building in New York
City was finished in 1930. It was the first structure to reach a height of 300 meters.
Due to the addition of a broadcasting aerial at the top of the tower in 1957, it is
now taller than the Chrysler Building by 5.2 meters (17 ft). Excluding transmitters,
the Eiffel Tower is the second tallest free-standing structure in France
after the Millau Viaduct.'''
# 기본 모델을 이용한 문서 요약 실행
result = summarizer(text)

# 결과 확인하기
print(result)
  • textrank - 문서 요약
    • 생성형 Ai가 제일 잘하는 분야
    • LG의 EXAONE - Hugging Face에서 사용 가능(30GB)
    • 창의적인 요약의 가능 유무가 중요함

summarization Code 2 (한국어 텍스트 요약 모델 사용)

# 한국어 텍스트 문서 요약 모델 생성
model_name='eenzeenee/t5-base-korean-summarization'

kor_summarizer = pipeline(task='summarization', model=model_name)

# 한글 텍스트 생성
text_sample = '''신용점수는 개인의 신용 상태를 평가하여 점수로 나타낸 것입니다. 현재 연체 및 과거 채무 상환 이력, 대출 및 보증채무 부담 정도, 신용 거래 기간, 체크카드 및 신용카드 이용 정보, 비금융정보 등을 종합적으로 판단하여 계산합니다. 예를 들어, 과거에 연체 없이 채무 상환을 잘 한 사람은 앞으로도 채무 상환을 잘해 나갈 것이라는 신뢰 정도를 점수로 표기한 것입니다.
신용점수 제도는 신용등급제의 문제를 보완하여 2021년에 처음 도입되었습니다. 기존에는 1~10등급으로 신용등급을 나눠 평가했는데, 이는 실제 점수가 1점밖에 차이나지 않아도 등급이 갈리며 카드 발급, 대출이 거절되며 지속적인 불만이 제기었습니다. 이에 2021년 신용등급제를 폐지하고 1~1,000점까지 1점 단위로 개인의 신용을 평가하는 점수제가 도입되었습니다.
그렇다면 개인의 신용점수는 어떻게 결정되는 걸까요? 신용점수는 금융기관이 아니라, 개인신용평가사에서 결정합니다. 공식적인 개인신용평가사는 2곳으로 나이스평가정보와 코리아크레딧뷰로가 있습니다. 두 신용평가사에서는 자체적으로 신용점수를 산출하는 항목과 비중을 정해 신용점수를 평가하기 때문에 평가사에 따라 신용점수는 상이할 수 있습니다. 세부적인 평가 기준 및 반영 비율이 궁금하다면 각 개인신용평가회사 홈페이지에서 확인할 수 있습니다.
'''
# 한글 문서 요약 실행
result = kor_summarizer(text_sample)

# 결과 확인하기
print(result)

QuestionAnwsering Code 1 (기본 QA 모델 사용)

# 기본 모델 생성
qa = pipeline(task='question-answering')
# QA에 사용할 텍스트 데이터 생성

# 질문 생성
question = "Which name is also used to describe the Amazon rainforest in English?"

# 지문 생성
context = """The Amazon rainforest (Portuguese: Floresta Amazônica or Amazônia; Spanish: Selva Amazónica, Amazonía or usually Amazonia; French: Forêt amazonienne;
Dutch:Amazoneregenwoud), also known in English as Amazonia or the Amazon Jungle, is a moist broadleaf forest that covers most of the Amazon basin of South America.
This basin encompasses 7,000,000 square kilometres (2,700,000 sq mi), of which 5,500,000 square kilometres (2,100,000 sq mi) are covered by the rainforest.
This region includes territory belonging to nine nations. The majority of the forest is contained within Brazil, with 60% of the rainforest,
followed by Peru with 13%, Colombia with 10%, and with minor amounts in Venezuela, Ecuador, Bolivia, Guyana, Suriname and French Guiana.
States or departments in four nations contain "Amazonas" in their names. The Amazon represents over half of the planet's remaining rainforests,
and comprises the largest and most biodiverse tract of tropical rainforest in the world, with an estimated 390 billion individual trees divided into 16,000 species."""
# QA 실행
result = qa(question=question, context=context)

# 결과 확인하기
print(result)
  • QuestionAnswering - 질의 응답
    • QuestionAnswering은 question, context입력값으로 넣음
    • question의 질문을 context안에서 찾음
    • QuestionAnswering의 결과
      • score : 모델이 예측한 답변의 신뢰도(정확도) 0과 1사이의 확률값으로 표현됨
      • start, end : context안에서 답변이 시작되는 위치와 끝나는 위치를 나타냄
  • QuestionAnswering 모델은 생성형ai & 챗봇의 등장으로 안쓰이게됨

QuestionAnwsering Code 2 (QA 모델 지정 후 사용)

# qa 모델 지정, pipeline 함수 호출, 모델 생성

# 필요한 함수 임폴트
from transformers import pipeline

model_name='deepset/roberta-base-squad2'
qa_advanced = pipeline(task='question-answering', model=model_name)
# QA 실행
result = qa_advanced(
    question=question,
    context=context
)

# 결과 확인하기
print(result['answer'])

text generation Code (gpt2 모델 사용)

# 기본 모델 생성
generator = pipeline(task='text-generation', model='gpt2')
# 문장 생성

# 필요한 함수 임폴트
from transformers import set_seed

# seed 설정
set_seed(42)

# 문장 생성
sentences = generator(
    "Hello, I'm a language model,",
    max_length=30,
    num_return_sequences=3
)

# 결과 확인하기
for data in sentences:
   sentence = data['generated_text']
   print(f'생성된 문장 : \n{sentence}')
   print('-'*80)
  • text generation
    • GPT2 (generator)의 파라미터
      • 텍스트의 앞부
      • max_length : 토큰의 최대 길이 (너무 길면 같은 말 반복함)
      • num_return_sequences : 생성할 문장의 개수
    • huggingface의 최신 generator모델을 활용하면 현재 생성형ai 급의 성능이 나오긴함(영어만 가능)








참고자료

[NLP 19] BERT 3 : 네이버 영화 리뷰 감성분석 (Text Classification)

pandas.DataFrame.dropna 공식문서

Hugging Face 한국어 FinBert 문서

Hugging Face 한국어 FinBert 문서

Hugging Face LG EXAONE 문서

Hugging Face textrank 문서

Hugging Face 한국어 textrank 문서

Hugging Face GPT2 문서


+ transformers.pipeline의 task 목록

HuggingFace pipeline().task 공식 문서

profile
AI & Robotics

0개의 댓글