자연어 처리(Natural Language Processing, NLP)는 언어학(linguistics)과 machine learning의 한 분야로, human language와 관련된 모든 것을 이해하는 데 중점을 둔다.
NLP task의 목표는 개별 단어만을 이해하는 것이 아니라 그 단어들의 맥락까지도 이해하는 것이다.
일반적인 NLP 작업과 예시
컴퓨터는 인간과 같은 방식으로 정보를 처리하지 않는다.
예를 들어, 인간은 "나는 배고프다"라는 문장을 읽으면 그 의미를 쉽게 이해할 수 있다. 또한 "나는 배고프다"와 "나는 슬프다"라는 두 문장을 주면 그 유사성을 쉽게 판단할 수 있다.
그러나 machine learning(ML) 모델에게 이러한 작업은 어렵다. 따라서 텍스트는 모델이 학습할 수 있도록 처리되어야 한다.
Transformer 모델의 활용 방법과 Transformers 라이브러리의 pipeline() 함수
Transformer 모델은 다양한 NLP 작업을 해결하는 데 사용된다.
Transformers 라이브러리는 다양한 사전 학습된 모델을 제공한다. 이 모델들은 누구나 다운로드하고 사용할 수 있다. 또한 사용자는 자신만의 모델을 업로드할 수도 있다.
pipeline() 사용Transformers 라이브러리에서 가장 기본적인 객체는 pipeline() 함수이다.
이 함수는 모델과 필요한 전처리 및 후처리 단계를 연결하여, 텍스트를 직접 입력하고 이해할 수 있게 한다.
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
result = classifier("I've been waiting for a HuggingFace course my whole life.")
print(result)
# [{'label': 'POSITIVE', 'score': 0.9598047137260437}]
감정 분석 예제이다.
results = classifier(
["I've been waiting for a HuggingFace course my whole life.", "I hate this so much!"]
)
print(results)
# [{'label': 'POSITIVE', 'score': 0.9598047137260437},
# {'label': 'NEGATIVE', 'score': 0.9994558095932007}]
여러 문장을 처리한 예제이다.
feature-extraction (텍스트의 벡터 표현 얻기)fill-mask (빈칸 채우기)ner (명명된 개체 인식)question-answering (질문 답변)sentiment-analysis (감정 분석)summarization (요약)text-generation (텍스트 생성)translation (번역)zero-shot-classification (제로샷 분류)from transformers import pipeline
classifier = pipeline("zero-shot-classification")
result = classifier(
"This is a course about the Transformers library",
candidate_labels=["education", "politics", "business"],
)
print(result)
# {'sequence': 'This is a course about the Transformers library',
# 'labels': ['education', 'business', 'politics'],
# 'scores': [0.8445963859558105, 0.111976258456707, 0.043427448719739914]}
zero-shot classification 예시이다. label이 없는 text를 분류한다.
from transformers import pipeline
generator = pipeline("text-generation")
result = generator("In this course, we will teach you how to")
print(result)
# [{'generated_text': 'In this course, we will teach you how to understand and use '
# 'data flow and data interchange when handling user data. We '
# 'will be working with one or more of the most commonly used '
# 'data flows — data flows of various types, as seen by the '
# 'HTTP'}]
텍스트 생성 예시이다.
텍스트 생성 pipeline을 사용하여 prompt를 자동완성한다.
distilgpt2 모델을 선택한다.distilgpt2 모델을 사용하여 텍스트 생성 파이프라인을 설정한다.from transformers import pipeline
generator = pipeline("text-generation", model="distilgpt2")
distilgpt2 모델을 사용하여text-generator 파이프라인을 설정한다.
results = generator(
"In this course, we will teach you how to",
max_length=30,
num_return_sequences=2,
)
max_length는 생성될 텍스트의 최대 length를 설정한다.num_return_sequences는 생성할 텍스트 sequence의 수를 설정한다.for result in results:
print(result['generated_text'])
생성된 텍스트를 출력한다.
In this course, we will teach you how to manipulate the world and move your mental and physical capabilities to your advantage.
In this course, we will teach you how to become an expert and practice realtime, and with a hands on experience on both real time and real
from transformers import pipeline
unmasker = pipeline("fill-mask")
result = unmasker("This course will teach you all about <mask> models.", top_k=2)
print(result)
마스크 채우기 파이프라인을 사용하여 빈칸을 채운다.
[{'sequence': 'This course will teach you all about mathematical models.',
'score': 0.19619831442832947,
'token': 30412,
'token_str': ' mathematical'},
{'sequence': 'This course will teach you all about computational models.',
'score': 0.04052725434303284,
'token': 38163,
'token_str': ' computational'}]
from transformers import pipeline
ner = pipeline("ner", grouped_entities=True)
result = ner("My name is Sylvain and I work at Hugging Face in Brooklyn.")
print(result)
명명된 객체 인식 (NER) 파이프라인을 사용하여 텍스트의 개체를 인식한다.
[{'entity_group': 'PER', 'score': 0.99816, 'word': 'Sylvain', 'start': 11, 'end': 18},
{'entity_group': 'ORG', 'score': 0.97960, 'word': 'Hugging Face', 'start': 33, 'end': 45},
{'entity_group': 'LOC', 'score': 0.99321, 'word': 'Brooklyn', 'start': 49, 'end': 57}]
from transformers import pipeline
question_answerer = pipeline("question-answering")
result = question_answerer(
question="Where do I work?",
context="My name is Sylvain and I work at Hugging Face in Brooklyn",
)
print(result)
질문 답변 파이프라인을 사용하여 주어진 문맥에서 답변을 추출한다.
{'score': 0.6385916471481323, 'start': 33, 'end': 45, 'answer': 'Hugging Face'}
from transformers import pipeline
summarizer = pipeline("summarization")
result = summarizer(
"""
America has changed dramatically during recent years. Not only has the number of
graduates in traditional engineering disciplines such as mechanical, civil,
electrical, chemical, and aeronautical engineering declined, but in most of
the premier American universities engineering curricula now concentrate on
and encourage largely the study of engineering science. As a result, there
are declining offerings in engineering subjects dealing with infrastructure,
the environment, and related issues, and greater concentration on high
technology subjects, largely supporting increasingly complex scientific
developments. While the latter is important, it should not be at the expense
of more traditional engineering.
Rapidly developing economies such as China and India, as well as other
industrial countries in Europe and Asia, continue to encourage and advance
the teaching of engineering. Both China and India, respectively, graduate
six and eight times as many traditional engineers as does the United States.
Other industrial countries at minimum maintain their output, while America
suffers an increasingly serious decline in the number of engineering graduates
and a lack of well-educated engineers.
"""
)
print(result)
텍스트를 요약하는 파이프라인을 사용한다.
[{'summary_text': ' America has changed dramatically during recent years . The '
'number of engineering graduates in the U.S. has declined in '
'traditional engineering disciplines such as mechanical, civil '
', electrical, chemical, and aeronautical engineering . Rapidly '
'developing economies such as China and India, as well as other '
'industrial countries in Europe and Asia, continue to encourage '
'and advance engineering .'}]
from transformers import pipeline
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en")
result = translator("Ce cours est produit par Hugging Face.")
print(result)
프랑스어를 영어로 번역하는 파이프라인을 사용한다.
[{'translation_text': 'This course is produced by Hugging Face.'}]
- GPT-유형 (Auto-regressive Transformer 모델)
- BERT-유형 (Auto-encoding Transformer 모델)
- BART/T5-유형 (Sequence-to-sequence Transformer 모델)
Transformer 모델은 언어 모델로 훈련되었다. 이는 대량의 원시 텍스트를 사용하여 self-supervised learning 방식으로 훈련되었다는 의미이다. self-supervised learning은 모델 입력에서 자동으로 목표가 계산되는 훈련 유형으로, 데이터 레이블링에 인간이 필요없다.
이 모델은 훈련된 언어에 대한 통계적 이해를 발전시키지만, 특정 실용적인 작업에는 그다지 유용하지 않다. 따라서 일반적인 사전 학습된 모델은 전이 학습(transfer learning) 과정을 거친다. 이 과정에서는 모델이 주어진 작업에 대해 인간이 주석을 단 레이블을 사용하여 감독된 방식으로 미세 조정된다.
Transformer 모델의 일반적인 전략은 모델의 크기와 사전 학습에 사용되는 데이터 양을 증가시켜 더 나은 성능을 달성하는 것이다. DistilBERT와 같은 몇몇 예외를 제외하고 대부분의 모델은 크기가 커지고 있다.
Transformer 모델은 주로 두 개의 블록으로 구성된다.
- Encoder: 입력을 받아 표현을 만든다.
- Decoder: 인코더의 표현과 다른 입력을 사용하여 목표 시퀀스를 생성한다.
인코더 전용 모델: 문장 분류, 명명된 개체 인식 등 입력 이해가 필요한 작업에 적합하다.
디코더 전용 모델: 텍스트 생성과 같은 생성 작업에 적합하다.
인코더-디코더 모델 (시퀀스-투-시퀀스 모델): 번역, 요약 등 입력이 필요한 생성 작업에 적합하다.
Transformer 모델의 핵심 기능이다. 어텐션 레이어는 모델이 특정 단어에 주의를 집중하게 한다. 예를 들어, 영어에서 프랑스어로 번역할 때 "You like this course"라는 문장을 번역하려면 "like"의 적절한 번역을 위해 "You"와 같은 인접 단어에 주의를 기울여야 한다.
원래 번역을 위해 설계되었다. 훈련 중 인코더는 특정 언어로 된 입력 문장을 받고, 디코더는 목표 언어로 된 같은 문장을 받는다.
인코더의 Attention Layer는 문장의 모든 단어를 사용할 수 있다.
디코더는 순차적으로 작동하며, 현재 생성 중인 단어 이전의 단어들에만 주의를 기울일 수 있다.
인코더 모델은 Transformer 모델의 인코더 부분만 사용하는 모델이다. 각 단계에서 어텐션 레이어는 초기 문장의 모든 단어에 접근할 수 있습니다. 이러한 모델들은 종종 "양방향 어텐션(bi-directional attention)"을 특징으로 하며, 자동 인코딩(auto-encoding) 모델이라고도 불린다.
이 모델들의 사전 훈련은 주로 주어진 문장을 어떤 방식으로든 손상시키고(예를 들어, 무작위로 단어를 마스킹하는 방식) 모델에게 초기 문장을 찾아내거나 재구성하도록 하는 작업을 중심으로 이루어진다.
인코더 모델은 전체 문장의 이해가 필요한 작업에 적합하다.
예시:
디코더 모델은 Transformer 모델의 디코더 부분만 사용하는 모델이다. 각 단계에서 주어진 단어에 대해 어텐션 레이어는 문장에서 그 단어 이전에 위치한 단어들만 접근할 수 있다. 이러한 모델들은 종종 "자동 회귀(auto-regressive)" 모델이라고 불린다.
디코더 모델의 사전 훈련은 주로 문장에서 다음 단어를 예측하는 작업을 중심으로 이루어진다. 모델은 현재까지 생성된 단어들을 기반으로 다음에 올 단어를 예측한다.
디코더 모델은 텍스트 생성을 포함한 작업에 가장 적합하다.
예시:
인코더-디코더 모델, 또는 시퀀스-투-시퀀스(sequence-to-sequence) 모델은 Transformer 아키텍처의 인코더와 디코더 두 부분을 모두 사용하는 모델이다. 각 단계에서 인코더의 어텐션 레이어는 초기 문장의 모든 단어에 접근할 수 있지만, 디코더의 어텐션 레이어는 주어진 단어 이전에 위치한 단어들만 접근할 수 있다.
이 모델들의 사전 훈련은 인코더나 디코더 모델의 목표를 사용할 수 있지만, 일반적으로 더 복잡한 목표를 포함한다. 예를 들어, T5는 텍스트의 랜덤 부분을 단일 마스크 특수 단어로 대체하고, 목표는 이 마스크 단어가 대체하는 텍스트를 예측하는 것이다.
시퀀스-투-시퀀스 모델은 주어진 입력에 따라 새로운 문장을 생성하는 작업에 가장 적합하다.
예시:
가장 큰 한계 중 하나는 대규모 데이터에 대한 사전 학습을 가능하게 하기 위해 가능한 모든 콘텐츠를 긁어모으기 때문에, 좋은 것뿐만 아니라 나쁜 것도 포함된다는 점이다.
예시: BERT 모델의 Fill-Mask 파이프라인
from transformers import pipeline
unmasker = pipeline("fill-mask", model="bert-base-uncased")
result = unmasker("This man works as a [MASK].")
print([r["token_str"] for r in result])
result = unmasker("This woman works as a [MASK].")
print([r["token_str"] for r in result])
['lawyer', 'carpenter', 'doctor', 'waiter', 'mechanic']
['nurse', 'waitress', 'teacher', 'maid', 'prostitute']
모델은 두 문장의 빈칸을 채우는 작업에서 성별 중립적인 답변을 하나만 제공한다.(웨이터/웨이트리스). 나머지 직업은 특정 성별과 관련이 있는 경우가 많으며, "prostitute"도 모델이 "여성"과 "일"에 연관시키는 상위 5가지 가능성 중 하나로 나타난다.
사용 중인 원래 모델이 성차별적, 인종차별적 또는 동성애 혐오적 콘텐츠를 매우 쉽게 생성할 수 있다는 점을 항상 염두에 두어야 한다. 모델을 자신의 데이터에 미세 조정한다고 해도 이러한 내재된 편향성이 사라지지는 않는다.
이번 챕터1에서는 Transformers 라이브러리의 고수준 pipeline() 함수를 사용하여 다양한 NLP 작업을 접근하는 방법을 배웠다.
| 모델 | 예시 | 작업 |
|---|---|---|
| 인코더 | ALBERT, BERT, DistilBERT, ELECTRA, RoBERTa | 문장 분류, 명명된 개체 인식, 추출적 질문 응답 |
| 디코더 | CTRL, GPT, GPT-2, Transformer XL | 텍스트 생성 |
| 인코더-디코더 | BART, T5, Marian, mBART | 요약, 번역, 생성적 질문 응답 |
pipeline() 함수를 사용하여 다양한 NLP 작업을 쉽게 수행할 수 있다.