1. API

- 클라이언트 프로그램과 서버 사이의 데이터 전달자
- 클라이언트 프로그램은 API를 통하여 요청을 하고, 서버는 API를 통하여 결과 데이터 전달
- 소프트웨어 간에 데이터를 교환하고 통신할 수 있도록 하는 인터페이스 제공
- Request
- API 주소 + API 키
- Request 형식 : 요청 양식
- Response
1-1. ChatGPT API 발급
- OpenAI 접속 -> 로그인 -> API 선택 -> API Keys -> 이름 입력 후 키 생성
- API 키를 복사하여 따로 보관해야 함(잊어버릴 시 재발급)
- 인터넷 상에 API 키가 노출 될 경우 API 키가 소멸
1-2. ChatGPT API를 활용한 질문하기
import pandas as pd
import numpy as np
import os
import openai
from openai import OpenAI
api_key = '~~~~~~'
os.environ['OPENAI_API_KEY'] = api_key
openai.api_key = os.getenv('OPENAI_API_KEY')
def ask_chatgpt1(question):
client = OpenAI()
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": question},
]
)
return response.choices[0].message.content
question = "한국에서 제일 높은 산이 뭔가요?"
response = ask_chatgpt1(question)
print(response)
2. NLP(Natural Language Processing)
- 컴퓨터가 인간의 언어를 이해시키기 위한 처리 방법
- 단어의 개별적 이해 뿐만 아니라 해당 단어의 맥락을 이해해야 함
- 문장의 감정 파악, 이메일 스팸 여부 감지, 질문에 대한 답변, 번역 등
2-1. 기존 NLP(RNN 기반)의 단점
- 병렬 처리의 어려움
- 장기 의존성 문제
- 확장성 제한
- RNN 모델의 단점 극복
- Transformer를 통하여 LLM이 발전
3-1. 특징
- 이전 문장들을 기억
- 문맥상 집중해야하는 단어를 잘 선택함
- 문장이나 단어 사이의 문맥을 파악하는 데 탁월한 능력
- Attention
3-2. pipeline 함수를 통한 쉬운 구현
- pipeline 함수를 사용하여 transformer 기반 LLM 모델을 손쉽게 사용
from transformers import pipeline
classifier = pipeline(task = 'sentiment-analysis', model = 'bert-base-multilingual-cased')
- pipeline으로 사용 가능한 언어 관련 task
- sentiment-analysis
- 감성 분석
- 주어진 문장에 대해 긍정, 부정 분류
- zero-shot-classification
- 학습 과정에서 본 적 없는 클래스에 대해 분류
- 학습 되지 않은 데이터라도 유사성을 비교하여 가장 유사한 곳으로 분류
- summarization
- translation
- text-generation
- 몇 글자를 적어서 입력하면, 이어서 문장 생성
- feature-extraction
- fill-mask
- ner
- question-answering
3-3. pipeline 함수로 NLP 구현
!pip install transformers==4.37.1
from transformers import pipeline
3-3-1. 감성 분석
classifier = pipeline(task = "sentiment-analysis", model = 'bert-base-multilingual-cased')
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)

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)

3-3-2. Zero-shot classification
classifier = pipeline(task = "zero-shot-classification", model="facebook/bart-large-mnli")
candidate_labels = ["tech", "politics", "game", "food"]
text = '''Pacle the bottom bun in the dish. put the tomato on the bun. put the patty on the tomato.
put the lettuce on the patty. put the onion on the lettuce. put the cheese on the onion. put the top bun to finish'''
result = classifier(text, candidate_labels)
print(f"Labels: {result['labels']}")
print(f"Scores: {result['scores']}")

3-3-3. 번역
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']}")

3-3-4. 요약
3-3-4-1. 영문 텍스트 요약
summarizer = pipeline(task = "summarization", model="facebook/bart-large-cnn")
text = """
Hong Gil-dong is a famous character from Korean folklore, often described as a hero similar to Robin Hood.
Born as the illegitimate son of a nobleman, he faced discrimination and hardships in society.
Despite this, he possessed extraordinary talents in martial arts and intelligence.
Determined to fight against corruption and social injustice, Gil-dong became a leader of a band of outlaws, using his skills to help the poor and oppressed.
His story symbolizes the pursuit of justice and equality, making him one of Korea’s most beloved folk heroes.
"""
summary = summarizer(text, max_length=80, min_length=30, do_sample=False)
print(f"Summary: {summary[0]['summary_text']}")
'''
Summary: Hong Gil-dong is a famous character from Korean folklore,
often described as a hero similar to Robin Hood. Born as the illegitimate
son of a nobleman, he faced discrimination and hardships in society.
Despite this, he possessed extraordinary talents in martial arts
and intelligence.
'''
3-3-4-2. 한글 텍스트 요약
summarizer = pipeline("summarization", model="ainize/kobart-news")
input_text = '''
홍길동은 한국 고전 소설 『홍길동전』의 주인공으로, 조선시대의 전설적인 인물입니다.
그는 서자 출신으로 태어나 사회적 차별을 받지만, 뛰어난 능력과 용기 덕분에 자신의 운명을 개척합니다.
홍길동은 도적이 되어 불의를 처치하고, 억압받는 사람들을 돕는 영웅적인 역할을 합니다.
결국 그는 자신의 이상을 실현하기 위해 새로운 나라를 세우고, 정의와 평화를 추구하는 인물로 그려집니다.
이 작품은 사회적 불평등과 정의, 인간의 삶의 의미에 대한 깊은 성찰을 담고 있습니다.
'''
summary = summarizer(input_text)
print(f"Summary: {summary[0]['summary_text']}")
'''
Your max_length is set to 128, but your input_length is only 108. Since this is a summarization task, where outputs shorter than the input are typically wanted, you might consider decreasing max_length manually, e.g. summarizer('...', max_length=54)
Summary: 홍 고전 소설 『홍길동전』의 주인공이자 조선시대의 전설적인 인물인 홍길동은 자신의 이상을 실현하기 위해 새로운 나라를 세우고, 정의와 평화를 추구하는 인물로 그려집니다.
'''
3-3-5. 문장 생성
generator = pipeline("text-generation", model="distilgpt2")
generator("Wake up in the morning",
max_length=30,
num_return_sequences=3)
'''
Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
[{'generated_text': "Wake up in the morning, you don't see me on the roof of your tent in any other way. That's what I've said."},
{'generated_text': 'Wake up in the morning, not out of curiosity and the good news.\nWhile looking inside, the two kids started laughing, and now they'},
{'generated_text': "Wake up in the morning. Don't ever get up late, or your friend is dead."}]
'''
4. Hugging Face
- 자연어 처리(NLP) 및 인공 지능(AI) 분야에서 가장 인기 있는 오픈 소스 라이브러리와 모델을 제공하는 플랫폼
- transformers 라이브러리 제공
- 사전 훈련된 다양한 Transformer 기반 LLM모델(BERT, GPT 등) 쉽게 사용
4-1. Hugging Face 사용
https://huggingface.co/

- 모델 선택 시

- 모든 모델이 예제 코드를 제공하지 않음
4-2. 코드
from transformers import PreTrainedTokenizerFast, BartForConditionalGeneration
tokenizer = PreTrainedTokenizerFast.from_pretrained("ainize/kobart-news")
model = BartForConditionalGeneration.from_pretrained("ainize/kobart-news")
input_text = '''
국내 전반적인 경기침체로 상가 건물주의 수익도 전국적인 감소세를 보이고 있는 것으로 나타났다.
수익형 부동산 연구개발기업 상가정보연구소는 한국감정원 통계를 분석한 결과 전국 중대형 상가
순영업소득(부동산에서 발생하는 임대수입, 기타수입에서 제반 경비를 공제한 순소득)이 1분기 ㎡당
3만4200원에서 3분기 2만5800원으로 감소했다고 17일 밝혔다.
수도권, 세종시, 지방광역시에서 순영업소득이 가장 많이 감소한 지역은 3분기 1만3100원을 기록한 울산으로, 1분기 1만9100원 대비 31.4% 감소했다.
이어 대구(-27.7%), 서울(-26.9%), 광주(-24.9%), 부산(-23.5%), 세종(-23.4%), 대전(-21%), 경기(-19.2%), 인천(-18.5%) 순으로 감소했다.
지방 도시의 경우도 비슷했다.
경남의 3분기 순영업소득은 1만2800원으로 1분기 1만7400원 대비 26.4% 감소했으며
제주(-25.1%), 경북(-24.1%), 충남(-20.9%), 강원(-20.9%), 전남(-20.1%), 전북(-17%), 충북(-15.3%) 등도 감소세를 보였다.
조현택 상가정보연구소 연구원은 "올해 내수 경기의 침체된 분위기가 유지되며
상가, 오피스 등을 비롯한 수익형 부동산 시장의 분위기도 경직된 모습을 보였고
오피스텔, 지식산업센터 등의 수익형 부동산 공급도 증가해 공실의 위험도 늘었다"며
"실제 올 3분기 전국 중대형 상가 공실률은 11.5%를 기록하며 1분기 11.3% 대비 0.2% 포인트 증가했다"고 말했다.
그는 "최근 소셜커머스(SNS를 통한 전자상거래), 음식 배달 중개 애플리케이션, 중고 물품 거래 애플리케이션 등의
사용 증가로 오프라인 매장에 영향을 미쳤다"며 "향후 지역, 콘텐츠에 따른 상권 양극화 현상은 심화될 것으로 보인다"고 덧붙였다.
'''
input_ids = tokenizer.encode(input_text, return_tensors="pt")
summary_text_ids = model.generate(
input_ids=input_ids,
bos_token_id=model.config.bos_token_id,
eos_token_id=model.config.eos_token_id,
length_penalty=2.0,
max_length=142,
min_length=56,
num_beams=4,
)
)
print(tokenizer.decode(summary_text_ids[0], skip_special_tokens=True))
5. 언어 모델 이해

5-1. 언어 모델링 절차
- 데이터 전처리
- Tokenize
- 문장을 의미 있는 단위로 쪼갬
- 사람이 결정해야하는 부분
- 문자 단위, 단어 단위, 형태소 단위(한국어는 형태소 단위가 일반적)
- 해당 단위에 번호를 붙임(vocab)
- 모델 사용
- Embedding Vector
- 토큰을 머신이 파악할 수 있는 수치로 변환
- 문서, 문장 내에서 단어의 의미와 문맥을 담음
- Transformer
- 문맥 파악
- 동음이의어는 여기서 문맥 파악으로 판단
- 결과 후처리