Colab으로 하루에 하나씩 딥러닝

NLP_허깅페이스 트랜스포머 본문

딥러닝_개념

NLP_허깅페이스 트랜스포머

Elleik 2023. 2. 8. 23:22
728x90

트랜스포머(Transformer)

  • 순환을 모두 없애고 셀프 어텐션 방식을 사용(신경망의 같은 층에 있는 모든 상태에 대해서 어텐션을 작동)
  • 인코더와 디코더 각각에 셀프 어텐션이 있으며, 출력은 포워드 신경망에 주입됨
  • 전이 학습을 통해서 트랜스포머가 정교화되며 발전됨

허깅페이스 트랜스포머

  • 다양한 트랜스포머 모델과 표준화된 인터페이스를 제공
  • 작업에 맞는 헤드를 제공하여 미세튜닝이 용이함
  • 여러 모델을 훈련하고 테스트하는 시간을 단축함

허깅페이스 트랜스포머 실습

### 라이브러리 설치

!pip install transformers

!pip install sentencepiece

### 데이터 설정

text = """Dear Amazon, last week I ordered an Optimus Prime action figure from your online store in Germany. 
        Unfortunately, when I opened the package, I discovered to my horror that I had been sent an action figure of Megatron instead!
        As a lifelong enemy of the Deceptions, I hope you can understand my dilemma.
        To resolve the issue, I demand an exchange of Megatron for the Optimus Prime figure I ordered.
        Enclosed are copies of my records concerning this purchase.
        I expect to hear from you soon.
        Sincerely, Bumblebee"""

1. 텍스트 분류

### 파이프라인 호출

from transformers import pipeline

classifier = pipeline("text-classification")

파이프라인 호출 완료


### 파이프라인을 통한 예측 리스트 

import pandas as pd

outputs = classifier(text)
pd.DataFrame(outputs)

모델은 텍스트가 부정적이라고 예측함


2. 개체명 인식(Named Entity Recoginition, NER) 

 

### 파이프라인 호출 후 NER 적용

ner_tagger = pipeline("ner", aggregation_strategy="simple")
outputs = ner_tagger(text)
pd.DataFrame(outputs)

개체명 인식 후 카테고리에 할당 완료


3. 질문 답변

### 파이프라인 호출 후 질문 답변 적용

reader = pipeline("question-answering")
question = "What does the customer want?"
outputs = reader(question=question, context=text)
pd.DataFrame([outputs])

텍스트에서 답변을 추출한 추출적 질문 답변 확인


4. 요약

### 파이프라인 호출 후 요약 적용

summarizer = pipeline("summarization")
outputs = summarizer(text, max_length=60, clean_up_tokenization_spaces=True)
print(outputs[0]['summary_text'])

매개변수 max_length와 clean_up_tokenization_spaces를 사용하여 요약


5. 텍스트 생성

### 파이프라인 호출 후 텍스트 생성 적용

generator = pipeline("text-generation")
response = "Dear Bumblebee, I am sorry to hear that your order was mixed up."
prompt = text + "\n\nCustomer service response:\n" + response
outputs = generator(prompt, max_length=200)
print(outputs[0]['generated_text'])

API를 통하여 텍스트 생성 완료

 

참고: 루이스 턴스톨, 『트랜스포머를 활용한 자연어 처리』, 한빛미디어(2023)

'딥러닝_개념' 카테고리의 다른 글

생성모델_3.GAN  (1) 2023.02.07
생성모델_2.변형 오토인코더  (0) 2023.02.06
생성모델_1.오토인코더  (0) 2023.02.03
클러스터링_3.자기 조직화 지도  (0) 2023.01.31
클러스터링_2.가우시안 혼합 모델  (0) 2023.01.30