PyTorch를 활용한 피드포워드 신경망 챗봇 분류기 구현

영어 대화 의도 분류를 위한 피드포워드 신경망 챗봇을 PyTorch로 구현합니다. 의도 태그, 패턴 문장, 응답 메시지로 구성된 JSON 데이터를 사용합니다.

데이터 구조

{'intents': [
  {'tag': '인사', 'patterns': ['안녕', '반가워', '하이'], 'responses': ['안녕하세요']},
  {'tag': '병원검색', 'patterns': ['병원 찾아줘'], 'responses': ['지역을 알려주세요']}
]}

tag는 의도 카테고리, patterns는 학습용 문장 예시, responses는 응답 메시지를 의미합니다.

신경망 모델

import torch
import torch.nn as nn

class IntentClassifier(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_size, hidden_size),
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(hidden_size, output_size)
        )
    
    def forward(self, x):
        return self.layers(x)

vocab_size = 1000
hidden_units = 128
class_count = 8
model = IntentClassifier(vocab_size, hidden_units, class_count)

의도 예측 파이프라인

from nltk.stem import WordNetLemmatizer
import numpy as np

lemmatizer = WordNetLemmatizer()

def preprocess_text(text):
    tokens = nltk.word_tokenize(text.lower())
    return [lemmatizer.lemmatize(token) for token in tokens]

def create_feature_vector(tokens, vocabulary):
    vector = np.zeros(len(vocabulary))
    for token in tokens:
        if token in vocabulary:
            idx = vocabulary.index(token)
            vector[idx] = 1
    return vector

def predict_intent(model, text, vocab, class_mapping):
    tokens = preprocess_text(text)
    features = create_feature_vector(tokens, vocab)
    tensor_input = torch.FloatTensor(features).unsqueeze(0)
    
    with torch.no_grad():
        outputs = model(tensor_input)
        probs = torch.softmax(outputs, dim=1)
        pred_idx = torch.argmax(probs).item()
    
    return class_mapping[pred_idx]

챗봇 인터페이스

import tkinter as tk

class ChatApp:
    def __init__(self):
        self.window = tk.Tk()
        self.setup_ui()
        
    def setup_ui(self):
        self.window.title("챗봇")
        self.chat_area = tk.Text(self.window, state='disabled')
        self.input_box = tk.Text(self.window, height=3)
        self.send_btn = tk.Button(self.window, text="전송", command=self.process_input)
        
        self.chat_area.pack()
        self.input_box.pack()
        self.send_btn.pack()
    
    def process_input(self):
        user_input = self.input_box.get("1.0", tk.END).strip()
        self.display_message(f"사용자: {user_input}")
        
        intent = predict_intent(model, user_input, vocabulary, class_dict)
        response = select_response(intent, intent_data)
        
        self.display_message(f"챗봇: {response}")
        self.input_box.delete("1.0", tk.END)
    
    def display_message(self, text):
        self.chat_area.config(state='normal')
        self.chat_area.insert(tk.END, text + '\n')
        self.chat_area.config(state='disabled')
    
    def run(self):
        self.window.mainloop()

if __name__ == "__main__":
    app = ChatApp()
    app.run()

동작 과정

  1. 사용자 입력 텍스트를 전처리 및 특징 벡터 변환
  2. 신경망 모델로 의도 클래스 예측
  3. 예측된 의도에 해당하는 응답 메시지 선택
  4. Tkinter GUI를 통해 대화 인터페이스 제공

태그: PyTorch 신경망 챗봇 자연어처리 NLTK

6월 22일 23:36에 게시됨