본문 바로가기
딥러닝

[딥러닝] 언어모델 이해 (2) Transformer _ 20241105

by 황오독 2024. 11. 5.

1. NLP란? (Natural Language Processing : 자연어 처리)

   - 컴퓨터가 인간의 언어(자연어)를 이해하고 해석하며, 생성할 수 있도록 하는 기술

   - 단일 단어를 개별적으로 이해하는 것 뿐만 아니라, 해당 단어의 맥락을 이해 하는 것

 

 1) 일반적인 NLP 작업

문장분류
(리뷰 감정파악, 이메일 스팸 여부 감지 등)
개체 명
(사람, 위치, 조직 등) 인식
문장 생성 질문에 대한 답변 텍스트 번역, 요약

 

   - 기존의 NLP : RNN 기반

   - 단점 : 병렬 처리 어려움, 장기 의존성 문제, 확장성 제한

   * 장기 의존성이란?

예시 : "그녀는 고양이를 사랑한다. 그것은 항상 그녀의 곁에 있다."
여기서 "그녀"라는 주어가 문장 앞부분에서 등장하고, "그것"이라는 대명사가 문장 뒷부분에서 "고양이"를 가리킴.
즉, "그녀"와 "고양이" 간의 관계를 이해하기 위해서는 문장의 처음부터 끝까지 내용을 파악해야 함. 
NLP는 문장이 길수록 해당 장기 의존성이 떨어짐

 

2. Transformer의 등장

 - RNN 모델의 단점을 극복하였으며, 언어 모델의 Game Changer

 - Transformer 덕분에 LLM이 발전하게 됨.

 

 1)  Transformer의 특징

    * Attention

      - 이전 문장들을 잘 기억하고, 문맥상 집중해야 할 단어를 잘 캐치

 

2) Transformer 사용하기

 ① pipiline 함수 : transformer 기반 LLM 모델을 손쉽게 사용할 수 있게 해주는 함수

  - 복잡한 언어 모델 처리 (NLP) 과정을 감추고, 다음 과정이 물흐르듯 흘러가게 해줌

 

 ② 코드

from transformers import pipeline
classifier = pipeline(task='sentiment-analysis', model='bert-base-multilingual-cased')
# task : 어떤 모델 ? 감성분석 모델!
# bert, GPT의 T는 transformer의 T임
더보기

Pipeline으로 사용 가능한 언어 관련 task

- sentiment-analysis (감정 분석)

- zero-shot-classfication (특정한 클래스를 학습하지 않고도 그 클래스를 인식하고 분류)

- summarization (요약)

- translation (번역)

- text-generation (생성)

 

 3) Task 별로 코드 사용하기

  * 환경설정

# colab에서는 이미 설치되어 있지만, 버전을 맞추기 위해서 수정
!pip install transformers==4.37.1

from transformers import pipeline # 파이프라인 함수 불러오기

 

  (1) Sentiment analysis : 주어진 문장에 대해 긍정, 부정 분류

# 방법1
classifier = pipeline(task = "sentiment-analysis", model = 'bert-base-multilingual-cased') # LLM 모델을 다운받는것

# 방법2
# sentiment-analysis 모델 파이프라인 생성
# 기본값 : distilbert-base-uncased-finetuned-sst-2-english
# distil 붙으면 보통 경량화를 시킨다는 말
# bert 모델을 경량화 시킴
classifier = pipeline("sentiment-analysis")

 

# 모델 사용
text = ["I've been waiting for a HuggingFace course my whole life.",
        "I hate this so much!",
        "I have a dream.",
        "She was so happy."]

classifier(text)

각 label에 긍정/부정이 표시되고 표시된 긍정/부정의 확률을 score에 표시

 

 (2) Zero-shot classification

# Zero-shot 분류 파이프라인 생성
classifier = pipeline(task = "zero-shot-classification", model="facebook/bart-large-mnli"

# 후보 레이블 지정
candidate_labels = ["tech", "politics", "business", "finance"]

# 분류하고자 하는 텍스트
text = "This is a tutorial about using transformers in natural language processing."

# 분류 수행
result = classifier(text, candidate_labels)

# 결과 출력
print(f"Labels: {result['labels']}")
print(f"Scores: {result['scores']}")

지정한 후보 레이블에서 각각 단어일 확률을 나타냄. 여기선 tech가 가장 높게 나옴!

 

 (3) Translation

# 한국어에서 영어로 번역하는 파이프라인 생성
translator_ko_to_en = pipeline(task = "translation", model="halee9/translation_en_ko")

# 번역하고자 하는 한국어 텍스트
text_ko = "안녕하세요, 오늘 미세먼지가 무척 심하네요."

# 번역 수행
translated_text_en = translator_ko_to_en(text_ko, max_length=60)

# 번역된 영어 텍스트 출력
print(f"Translated Text (KO to EN): {translated_text_en[0]['translation_text']}")

 

 (4) Summariazation

# 텍스트 요약 파이프라인 생성, 여기서는 BART 모델을 사용
summarizer = pipeline(task = "summarization", model="facebook/bart-large-cnn")

# 요약하고자 하는 여러 문장이나 긴 텍스트
text = """
The global economy is facing unprecedented challenges due to the impact of the COVID-19 pandemic. Many countries are experiencing significant downturns,
with industries such as travel, hospitality, and retail particularly affected. Governments around the world are implementing various fiscal and monetary policies
in an attempt to mitigate the economic fallout. This includes measures such as lowering interest rates, providing financial assistance to businesses and individuals,
and introducing stimulus packages aimed at boosting economic activity. Despite these efforts, the path to recovery is expected to be long and uncertain,
with many experts predicting a slow return to pre-pandemic levels of economic growth.
"""

# 텍스트 요약 수행
summary = summarizer(text, max_length=80, min_length=30, do_sample=False)
# 최소 30, 최대 80글자 내로 요약
# do_sample=False: 예측 가능한 결과 (가장 높은 확률의 단어 선택) => 보통 이걸 씀.
# do_sample=True: 다양한 결과 (확률 분포에 따라 랜덤 선택

# 요약된 텍스트 출력
print(f"Summary: {summary[0]['summary_text']}")
더보기

출력 결과

Summary: The global economy is facing unprecedented challenges due to the impact of the COVID-19 pandemic. Many countries are experiencing significant downturns, with industries such as travel, hospitality, and retail particularly affected. Governments around the world are implementing various fiscal and monetary policies.

** 한국어 ver

# 텍스트 요약 파이프라인 생성, 여기서는 BART 모델을 사용
summarizer = pipeline("summarization", model="ainize/kobart-news")

# 소설 상록수 중에서...
input_text = '''
가을 학기가 되자, ○○일보사에서 주최하는 학생계몽운동에 참가하였던 대원들이 돌아왔다. 오늘 저녁은 각처에서 모여든 대원들을 위로하는 다과회가 그 신문사 누상에서 열린 것이다.
오륙백 명이나 수용할 수 있는 대강당에는 전 조선의 방방곡곡으로 흩어져서 한여름 동안 땀을 흘려 가며 활동한 남녀 대원들로 빈틈없이 들어찼다.
폭양에 그을은 그들의 시커먼 얼굴! 큰 박덩이만큼씩 한 전등이 드문드문하게 달린 천장에서 내리비치는 불빛이 휘황할수록, 흰 벽을 등지고 앉은 그네들의 얼굴은 더한층 검어 보인다.
만호 장안의 별처럼 깔린 등불이 한눈에 내려다보이도록 사방의 유리창을 활짝 열어제쳤건만, 건장한 청년들의 코와 몸에서 풍기는 훈김이 우거진 콩밭 속에를 들어간 것만치나 후끈후끈 끼친다.
정각이 되자 P학당의 취주악대는 코넷, 트럼본 같은 번쩍거리는 악기를 들고 연단 앞줄에 가 벌려 선다. 지휘자가 손을 내젓는 대로 힘차게 연주하는 것은 유명한 독일 사람의 작곡인 쌍두취 행진곡(雙頭鷲行進曲)이다. 그 활발하고 장쾌한 멜로디는 여러 사람의 심장까지 울리면서 장내의 공기를 진동시킨다.
'''

# 텍스트 요약 수행
summary = summarizer(input_text)

# 요약된 텍스트 출력
print(f"Summary: {summary[0]['summary_text']}")

 

더보기

출력결과

Summary: 2계절이 되자, ○○일보사에서 주최하는 학생계몽운동에 참가하였던 대원들이 돌아와 오늘 저녁은 각처에서 모여든 대원들을 위로하는 다과회가 그 신문사 누상에서 열린 것이다. 오륙백 명이나 수용할 수 있는 대강당에는 전 조선의 방방곡곡으로 흩어져서 한여름 동안 땀을 흘려 가며 활동한 남녀 대원들로 빈틈없이 들어찼다.

 

 (5) text-generation (몇글자만 적으면, 이어서 문장을 생성해줌)

# 영문 생성 모델 다운로드
generator = pipeline("text-generation", model="distilgpt2") # distil 경량화

# 문장 생성 실행
generator("In this course, we will teach you how to",
          max_length=30,                    # 생성할 최대 토큰 수
          num_return_sequences=3)           # 생성할 문장
더보기

출력결과 (3개의 문장이 생성)

[{'generated_text': 'Yesterday, I was trying to find my way to The Wall Street Journal. I’d made it to the Wall Street Journal to tell it it'},
 {'generated_text': 'Yesterday, I was shocked to learn that a couple of weeks ago, on behalf of the government, the National Security Agency took down a popular Twitter account'},
 {'generated_text': 'Yesterday, I was given the opportunity to use that space to talk about things. You can see why I was given the opportunity to use that space to'}]

 

3. Hugging Fanse

http://huggingface.co/

 

Hugging Face – The AI community building the future.

The Home of Machine Learning Create, discover and collaborate on ML better. We provide paid Compute and Enterprise solutions. We are building the foundation of ML tooling with the community.

huggingface.co

 1) 허깅페이스

   : 자연어 처리(NLP) 및 인공지능(AI) 분야에서 가장 인기 있는 오픈 소리 라이브러리와 모델을 제공하는 플랫폼

    - 위에 summarization, Translation 등 모델들을 모두 여기서 따옴!