Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

チャットボットの実装

Last updated at Posted at 2017-04-27

チャットボットの実装

チャットボットとは?

チャットボット(会話ボット / Chatbot)とは、ユーザーの問いかけに対してプログラムが応答をするプログラムのことです。
マイクロソフトのりんななどがチャットボットに当たります。
チャットボットは単にユーザーと雑談を行なうことが目的のものもあれば、タスク指向型のシステムであれば
カスタマーサービスやテクニカルサポートで役立って現在使われています。
一見チャトボットは知能を持っていて、考えて会話をしているように感じますが、多くはキーワードを拾い、
データベースとのマッチングによってそれらしい応答を返しているだけが多いです。

大別すると「機械学習型」と「ルール型」に大別できます。

■ 機械学習型
・大量の対話データから機械が自動で学ぶ
・汎用的な会話に対応可能
・予期せぬ返答をしてしまう恐れがある。

■ ルール型(人工無脳)
・事前に登録したルールを元に、回答が行われる
・汎用的な会話は出来ない。
・ルール以外の発話をすることはない。

Eliza
http://www.masswerk.at/elizabot/

「機械学習」と「人工無脳」の使い分け

ここでは、「機械学習」と「人工無脳」をどう使い分けるかを考えて見ます。

あらゆる質問に対してまず機械学習型チャットボットが対応し、その内容に応じて振り分けをする。そして、より専門的な人工無脳がルールベースで返答するのが1つの理想だとしている。

人工無脳は将来の機械学習チャットボットへの移行にも有効という。
「AIによる応答の精度は今度も上がっていくと思う。しかし、その学習に必要となるビッグデータ(会話ログ)をまだ持っていない企業も多いはず」とし、「まず人工無脳によってデータを集めておき、将来的に機械学習AIへ反映させる方法たりする」

・もし会話ログのデータを持っていない人や企業は、
人工無能でデータを集め、将来的には機械学習型のチャットボットにする。

ルール型(人工無能)
FAQ専門 / 接客専門

機械学習型(人工知能)
ユーザーの意図を解釈し、適切なチャットボットに振る

チャットボットを実装する

チャットボットを実装するために、モデルを作ります。

ここで作るチャットボットは、まずLSTMを使いモデルを作りそのモデルを学習します。
学習済みモデルを使い、ターミナルで動作するチャットボットを作ります。

ローカルで動作する場合には、Keras + TensorFlowの環境はもちろん、
gensimとpickle、scipyをインストールする必要があります。

pip install gensim pickle scipy

では、まずはモデルを学習する__training.py__を作ります。

training.py
import os
import pickle
import numpy as np
import gensim
from keras.models import Sequential
from keras.layers.recurrent import LSTM
from sklearn.model_selection import train_test_split

# ファイルの読み込み
# with open('conv.json') as f:
#    vec_x, vec_y = pickle.load(f)

vec_x=np.array(vec_x,dtype=np.float64)
vec_y=np.array(vec_y,dtype=np.float64)    

x_train,x_test, y_train,y_test = train_test_split(vec_x, vec_y, test_size=0.2, random_state=1)
   


"""
モデルの構築
"""
def build_model(): 
	model=Sequential()

	"""
	init='glorot_normal'
	inner_init='glorot_normal'
	activation='sigmoid'
	"""
	model.add(LSTM(output_dim=300,input_shape=x_train.shape[1:],return_sequences=True, init='glorot_normal', inner_init='glorot_normal', activation='sigmoid'))
	model.add(LSTM(output_dim=300,input_shape=x_train.shape[1:],return_sequences=True, init='glorot_normal', inner_init='glorot_normal', activation='sigmoid'))
	model.add(LSTM(output_dim=300,input_shape=x_train.shape[1:],return_sequences=True, init='glorot_normal', inner_init='glorot_normal', activation='sigmoid'))
	model.add(LSTM(output_dim=300,input_shape=x_train.shape[1:],return_sequences=True, init='glorot_normal', inner_init='glorot_normal', activation='sigmoid'))
	# 予測と正解間のコサイン類似度の負の平均
	# https://keras.io/ja/objectives/
	"""
	コサイン類似度
	コサイン類似度とは、ベクトル空間モデルにおいて、文書同士を比較する際に用いられる類似度計算手法。
	http://www.cse.kyoto-su.ac.jp/~g0846020/keywords/cosinSimilarity.html
	"""
	model.compile(loss='cosine_proximity', optimizer='adam', metrics=['accuracy'])
	return model

if __name__ == "__main__":
	model = build_model()
	model.fit(x_train, y_train, nb_epoch=500,validation_data=(x_test, y_test))
	model.save('LSTM5000.h5');          
	predictions=model.predict(x_test) 
	# mod = gensim.models.Word2Vec.load('word2vec.bin') 
	# [mod.most_similar([predictions[10][i]])[0] for i in range(15)]

学習済みモデルを使ってChatBotを実装する

use_model.py

import os,re,json,random
from scipy import spatial
import numpy as np
import gensim
import nltk
# nltk.download()
# http://stackoverflow.com/questions/4867197/failed-loading-english-pickle-with-nltk-data-load
from keras.models import load_model

# https://drive.google.com/drive/folders/0B2P-tOw32QIWZnYyY3J3OVNLYzg
model=load_model('LSTM5000.h5')

# word2vec.bin download link
# https://ibm.ent.box.com/s/77etivy69jmga0x0u6vs2n47ul8baks4
mod = gensim.models.Word2Vec.load('word2vec.bin')
while(True):
    x=input("You: Enter the message:")
    # 人工無能(ルール型)
    if x == "こんにちは":
        output = "こんにちは!!"
        print("AI: ", output)
    elif x == "こんばんは":
        output = "こんばんは!!"
        print("AI: ", output)
    else:
        # 機械学習型(LSTM)
        sen=np.ones((300,),dtype=np.float32) 
        sent=nltk.word_tokenize(x.lower())

        sentvec = [mod[w] for w in sent if w in mod.wv.vocab]
        sentvec.append(sen)
        
        if len(sentvec)<15:
            for i in range(15-len(sentvec)):
                sentvec.append(sen) 
        sentvec=np.array([sentvec])

        
        # predictでモデルを使う
        predictions = model.predict(sentvec)

        # most_similar 単語どうしの「類似度」
        outputlist = [mod.wv.most_similar([predictions[0][i]])[0][0] for i in range(15)]
        """
        次のようなリストが返ってくる
        ['how', 'are', 'you', 'doing', '?']
        """

        # 上記のリストを半角スペースで結語する
        output=' '.join(outputlist) # how are you doing ?
        
        """
        kleiserとkarluahという文字列をスペースで置換する
        """
        output = output.replace("kleiser", " ")
        output = output.replace("karluah", " ")
        print("AI: ", output)

チャットボットに関連した記事

■ グルメQ&Aアプリ「ペコッター」の裏側を大公開!なぜチャット形式は満足度が高いのか?
https://gaiax-socialmedialab.jp/post-48560/

■ 「チャットボット=全自動化」ではない! 企業もユーザーも幸せになるチャットボットの活用方法とは?
https://gaiax-socialmedialab.jp/post-48544/

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?