일하는/AI, ML

Rasa NLU Tutorial

김논리 2021. 1. 21. 13:20

Rasa

Rasa is the essential platform for creating great AI assistants. With Rasa, all teams can create better text- and voice-based assistants. Rasa provides infrastructure & tools necessary for high-performing, resilient, proprietary AI assistants - that actually help your customers.

Python, Tensorflow로 만들어진 오픈소스 머신러닝 프레임워크. 대화형 데이터를 학습하기 위한 기계 학습 기반 접근 방식을 사용한다.

 

대화형 챗봇을 위한 머신러닝 출로, 다음과 같이 2개의 프레임워크로 구성된다.

  • Rasa NLU
    의도 분석과 엔티티 추출 기능을 가진 자연어 이해를 위한 라이브러리로 챗봇이 사용자가 어떤 말을 하고 있는지 이해하는 데 사용된다.
  • Rasa Core
    머신러닝 기반의 대화 관리 챗봇 프레임워크로 NLU의 인풋, 대화 히스토리, 그리고 훈련 데이터에 기반하여 최선의 다음 액션을 예측하는 데 사용된다.

Rasa NLU

Rasa NLU(Natural Language Understanding)대화 의도 분류(intent classification)개체 추출(entity extraction)을 위한 오픈소스 자연어 처리 도구이다. Rasa NLU에서는 자연어 처리의 과정을 파이프라인이라 부르며, 이러한 과정을 개발자가 직접 설계할 수 있는 구조를 갖고 있다.

Rasa NLU에서는 다양한 파이프라인을 지원하는데, 그 중 대표적인 파이프라인으로는 pretrained_embeddings_spacysupervised_embeddings 이 있다.

Install

아래 명령어를 사용하여 Rasa를 설치한다. (Ubuntu18.04 + Python 3.6.9 환경)

# rasa nlu를 설치하는 경우
$ pip install rasa_nlu

# ---> pipeline 에 dependency를 주어 설치할 수도 있다.
# 1. pretrained embeddings from spaCy
$ pip install rasa_nlu[spacy]
# 2. Tensorflow
$ pip install rasa_nlu[tensorflow]


[Optional]
# rasa core를 설치하는 경우
$ pip install rasa_core

# rasa stack 전체를 설치하는 경우 (rasa_nlu와 rasa_core가 함께 설치된다)
$ pip install rasa

# pipeline dependency 없이 설치할 경우, 아래와 같이 필요한 모듈들을 추가 설치해야 한다.
# Tensorflow
$ pip install tensorflow==1.12.0    # 호환되는 버전으로 설치가 되어야 함
# sklearn_crfsuite
$ pip install sklearn_crfsuite
...

rasa_nlu[tensorflow] 로 설치하여 진행...

설치에 오류가 발생하는 경우, pip install --upgrade pip setuptools wheel 수행한뒤 다시 설치해 보자.

 

Tutorial

레스토랑 검색을 위한 챗봇을 만들어 보자. 사용자가 말하는 내용이 다음 intent 중 하나로 분류 된다고 가정해 보자.

  • greet
  • restaurant_search
  • thankyou

물론 사용자의 입력은 매우 다양할 것이다.

  • greet
    • Hi!
    • Hey there!
    • Hello again :)
  • restaurant_search
    • Do you know any good pizza places?
    • I’m in the North of town and I want chinese food
    • I’m hungry

Rasa NLU에서 가장 먼저 해야할 일은 위와같이 주어진 다양한 문장들을 intent category로 분류하는 것이다. 두번째로는 "chinese" 와 "North" 같을 단어를 cuisine 그리고 location 과 같은 entity로 표시하는 것이다. (entity에 관련해서는 다음에...)

 

1. Prepare NLU Training Data

Training Data의 데이터는 Markdown 형식으로 작성하며, 각 intent category에 따라 입력으로 사용될 수 있듣 메세지 목록을 갖는다. nlu.md 파일을 생성하여 아래 내용을 작성한다.

## intent:greet
- hey
- hello
- hi
- good morning
- good evening
- hey there

## intent:restaurant_search
- i'm looking for a place to eat
- I want to grab lunch
- I am searching for a dinner spot
- i'm looking for a place in the [north](location) of town
- show me [chinese](cuisine) restaurants
- show me a [mexican](cuisine) place in the [centre](location)
- i am looking for an [indian](cuisine) spot
- search for restaurants
- anywhere in the [west](location)
- anywhere near [18328](location)
- I am looking for [asian fusion](cuisine) food
- I am looking a restaurant in [29432](location)

## intent:thankyou
- thanks!
- thank you
- thx
- thanks very much

2. Define Machine Learning Model

Rasa NLU에서 제공되는 다양한 파이프라인을 사용할 수 있으나, 본 예제에서는 기 정의된 supervised_embeddings 파이프라인을 사용한다. nlu_config.yml 파일을 생성하여 아래 내용을 작성한다.

language: en
pipeline: supervised_embeddings

3. Train Machine Learning NLU Model

모델을 학습하기 위해서는 rasa_nlu.train 명령을 사용하여 설정값과 training data값을 전달하면 된다.

$ python -m rasa_nlu.train \
  -c nlu_config.yml \
  --data nlu.md \
  -o models \
  --fixed_model_name nlu \
  --project current \
  --verbose

학습이 완료되면, 디렉토리 내 model/current/nlu 경로에 학습된 모델이 저장된다.

4. Try it out!

Rasa에서 제공하는 NLU HTTP 서버를 실행하여 HTTP API로 사용할 수 있으며, 또는 Python 코드에서 Interpreter 객체를 만들어 직접 사용할 수도 있다.

from rasa_nlu.model import Interpreter
import json


interpreter = Interpreter.load("./models/current/nlu")
message = "let's see some italian restaurants"
result = interpreter.parse(message)
print(json.dumps(result, indent=2))

위 코드를 실행시키면 다음과 같은 결과값이 출력된다.

{
  "intent": {
    "name": "restaurant_search",
    "confidence": 0.8676950335502625
  },
  "entities": [],
  "intent_ranking": [
    {
      "name": "restaurant_search",
      "confidence": 0.8676950335502625
    },
    {
      "name": "greet",
      "confidence": 0.24667112529277802
    },
    {
      "name": "thankyou",
      "confidence": 0.12102118879556656
    }
  ],
  "text": "let's see some italian restaurants"
}

'일하는 > AI, ML' 카테고리의 다른 글

FastText to spaCy  (0) 2021.05.25
spaCy  (0) 2021.05.25
GTTS (Google Text to Speech)  (0) 2021.02.03
NLTK Tutorial  (0) 2021.01.21