[파이썬] nltk 의도 및 요청 인식 (Intent Recognition)

인공지능 (AI) 및 자연어 처리 분야에서 의도 및 요청 인식은 매우 중요한 작업입니다. 이를 통해 컴퓨터가 사람의 말을 이해하고, 사용자의 의도를 파악하여 적절한 응답을 제공할 수 있습니다. Natural Language Toolkit (NLTK)는 파이썬에서 자연어 처리 작업을 수행하기 위한 라이브러리로, 의도 및 요청 인식을 구현하는 데 사용할 수 있습니다.

nltk 설치하기

먼저, nltk를 설치하기 위해 다음 명령어를 사용합니다:

pip install nltk

단어 토큰화 (Word Tokenization)

문장을 단어로 분리하는 첫 번째 단계는 단어 토큰화입니다. 이를 위해 nltk의 word_tokenize() 함수를 사용할 수 있습니다. 아래는 단어 토큰화의 예시입니다:

import nltk
from nltk.tokenize import word_tokenize

sentence = "How are you doing today?"
tokens = word_tokenize(sentence)
print(tokens)

출력:

['How', 'are', 'you', 'doing', 'today', '?']

의도 분류 (Intent Classification)

다음 단계는 의도 분류입니다. 즉, 입력 문장의 의도를 파악하는 것입니다. 이를 위해 텍스트 분류 알고리즘 중 하나인 나이브 베이즈 분류기를 사용할 수 있습니다. 아래는 의도 분류의 예시입니다:

import nltk
from nltk.tokenize import word_tokenize
from nltk.classify import NaiveBayesClassifier

# 학습 데이터
training_data = [("How are you doing today?", "greeting"),
                ("What are your plans for the weekend?", "plans"),
                ("Can you help me with this problem?", "help")]

# 피처 추출 함수
def extract_features(sentence):
    words = word_tokenize(sentence.lower())
    return {word: True for word in words}

# 필요한 피처 추출
training_set = [(extract_features(sentence), intent) for sentence, intent in training_data]

# 나이브 베이즈 분류기 훈련
classifier = NaiveBayesClassifier.train(training_set)

# 새로운 문장 테스트
sentence = "How are you?"
features = extract_features(sentence)
intent = classifier.classify(features)

print(intent)

출력:

greeting

요청 인식 (Entity Recognition)

의도를 파악한 후, 다음으로 수행할 작업은 입력 문장에서 중요한 정보, 즉 요청된 개체 (Entities)를 인식하는 것입니다. 이를 위해 정규 표현식을 사용할 수 있습니다. 아래는 요청 인식의 예시입니다:

import re

# 입력 문장
sentence = "Can you book a table for 4 people at 7 PM?"

# 요청된 개체 인식
table_pattern = re.compile(r'table')
people_pattern = re.compile(r'(\d+) people')
time_pattern = re.compile(r'(\d+) PM')

table_match = table_pattern.search(sentence)
people_match = people_pattern.search(sentence)
time_match = time_pattern.search(sentence)

if table_match:
    print("Table booking requested")
if people_match:
    num_of_people = people_match.group(1)
    print(f"Number of people: {num_of_people}")
if time_match:
    time = time_match.group(1)
    print(f"Booking time: {time} PM")

출력:

Table booking requested
Number of people: 4
Booking time: 7 PM

NLTK를 사용하여 의도 및 요청 인식을 구현할 수 있습니다. 이를 통해 자연어 처리 기능을 추가하여 더 유연하고 인간과 대화하는 AI 시스템을 개발할 수 있습니다.