박주니 개발 정리

few shot learning 간단 구현 방법 본문

AI

few shot learning 간단 구현 방법

박주니 2024. 4. 30. 17:29
728x90
반응형


1. 필요한 라이브러리 임포트

import torch
import torch.nn as nn
import torch.optim as optim


`torch`: PyTorch 기본 라이브러리, 텐서 조작 및 기본 연산에 사용.
`torch.nn`: 신경망을 구성하는 데 필요한 모듈과 클래스를 제공.
`torch.optim`: 최적화 알고리즘을 제공, 이 예제에서는 사용되지 않음.

2. 모델 클래스 정의

class TextPrototypicalNetwork(nn.Module):
    def __init__(self, vocab_size, embedding_dim):
        super(TextPrototypicalNetwork, self).__init__()
        self.embedding = nn.Embedding(vocab_size, embedding_dim)
        self.encoder = nn.LSTM(embedding_dim, 64, batch_first=True)
    
    def forward(self, x):
        x = self.embedding(x)
        output, (hidden, _) = self.encoder(x)
        return hidden.squeeze(0)  # LSTM의 마지막 hidden state 반환


- `TextPrototypicalNetwork`: 프로토타입 네트워크를 정의하는 클래스로, 단어 임베딩과 LSTM을 사용하여 텍스트를 인코딩.
`embedding`: 단어를 밀집 벡터로 변환.
`encoder`: LSTM을 사용하여 시퀀스의 특징을 추출.

3. 모델 초기화 및 기준 질문 처리

reference_question = "How can I change my contact details?"
words = set(reference_question.split())
word_to_index = {word: i for i, word in enumerate(words)}
encoded_reference_question = torch.tensor([[word_to_index[word] for word in reference_question.split()]])
model = TextPrototypicalNetwork(vocab_size=len(word_to_index), embedding_dim=100)
reference_embedding = model(encoded_reference_question)


- 기준 질문을 단어 인덱스로 변환하고, 이를 통해 모델을 통해 임베딩 벡터를 생성.

4. 새 질문 처리 및 유사도 계산

def query_new_question(model, new_question):
    encoded_new_question = torch.tensor([[word_to_index.get(word, 0) for word in new_question.split()]])
    new_embedding = model(encoded_new_question)
    similarity = torch.nn.functional.cosine_similarity(new_embedding, reference_embedding)
    return reference_answer if similarity > 0.5 else "Unknown"


- 새로운 질문을 인코딩하고 모델을 통해 임베딩을 생성.
- 기준 질문의 임베딩과 새 질문의 임베딩 간의 코사인 유사도를 계산하여 유사도가 0.5 이상이면 기준 답변을, 그렇지 않으면 "Unknown"을 반환.

5. 예제 실행 및 출력

new_question = "Could you please provide instructions on how to update my contact information?"
predicted_answer = query_new_question(model, new_question)
print(predicted_answer)


- 새로운 질문을 모델에 적용하여 예상 답변을 출력.

전체 코드 

import torch
import torch.nn as nn
import torch.optim as optim

class TextPrototypicalNetwork(nn.Module):
    def __init__(self, vocab_size, embedding_dim):
        super(TextPrototypicalNetwork, self).__init__()
        self.embedding = nn.Embedding(vocab_size, embedding_dim)
        self.encoder = nn.LSTM(embedding_dim, 64, batch_first=True)
    
    def forward(self, x):
        x = self.embedding(x)
        output, (hidden, _) = self.encoder(x)
        return hidden.squeeze(0)  # LSTM의 마지막 hidden state 반환

# 기준 질문 및 답변
reference_question = "How can I change my contact details?"
reference_answer = "MaintainEmployeeDetails"

# 단어 인덱스 생성
words = set(reference_question.split())
word_to_index = {word: i for i, word in enumerate(words)}

# 인코딩
encoded_reference_question = torch.tensor([[word_to_index[word] for word in reference_question.split()]])

# 모델 초기화 및 기준 질문 임베딩
model = TextPrototypicalNetwork(vocab_size=len(word_to_index), embedding_dim=100)
reference_embedding = model(encoded_reference_question)

def query_new_question(model, new_question):
    encoded_new_question = torch.tensor([[word_to_index.get(word, 0) for word in new_question.split()]])
    new_embedding = model(encoded_new_question)
    # Cosine 유사도 계산
    similarity = torch.nn.functional.cosine_similarity(new_embedding, reference_embedding)
    return reference_answer if similarity > 0.5 else "Unknown"

# 새로운 질문 예시
new_question = "Could you please provide instructions on how to update my contact information?"
predicted_answer = query_new_question(model, new_question)
print(predicted_answer)  # 예상 출력: "MaintainEmployeeDetails" (유사성에 따라 다름)

 

실행 방법 

conda 처음 설정하시는 방법을 모르신다면?

https://junhee6773.tistory.com/entry/miniconda-%EC%84%A4%EC%B9%98-%EB%B0%8F-vscode-%EC%97%B0%EA%B2%B0-%EB%B0%A9%EB%B2%95

 

miniconda 설치 및 vscode 연결 방법

1. https://docs.anaconda.com/free/miniconda/miniconda-install/ 에서 환경에 맞게 설치합니다. 저는 window환경이여서 windows graphical installer에서 설치했습니다. <figure id="og_1714454229590" contenteditable="false" data-ke-type="

junhee6773.tistory.com

설치하는 방법을 모르신다면?

https://junhee6773.tistory.com/entry/openai-api-%EC%97%86%EC%9D%B4-gpt2-model-%EC%A0%81%EC%9A%A9-%EB%B0%A9%EB%B2%95

 

openai api 없이 gpt2 model 적용 방법

gpt2 model 적용 코드 설명 1. 필요한 라이브러리와 클래스의 임포트import torchfrom transformers import GPT2LMHeadModel, GPT2Tokenizer, Trainer, TrainingArgumentsfrom torch.utils.data import Datasetfrom torch.optim import AdamW</co..

junhee6773.tistory.com

하단에 실행방법부터 보시면 됩니다. 지금 이 코드는 torch만 설치하시면 됩니다. 

 

few shot learning 실행 후기) 

openai api를 사용하지 않고 유사한 문장을 프롬프트로 적을 시 학습한 내용이 나오는 것을 볼 수 있었습니다.

few shot learning을 알지 못할 때에는 openai api를 이용해서 llm 기반으로 진행했기 때문에 질문할 때마다 사용 비용을 지불했습니다.

그런데 이렇게 간단하게 진행할 때에는 무료로 사용할 수 있다는 것을 알게 되니깐 비즈니스적으로 바라볼때에도 비용절감효과를 볼 수 있었습니다. 

 

728x90
반응형
Comments