问题描述
最近,我一直在构建一个简单的聊天机器人来回答FAQ,以了解NLP。我使用相同的nltk库。我设法使机器人对已知问题做出了回应,然后将其馈入名为intents.json的文件,该文件存储了有关意图的所有详细信息以及意图匹配后要选择的响应。
但是,当用户根据他提供的输入指定要执行的操作时,我遇到了问题。例如,如果用户要搜索特定人的会员ID,他会提及该ID,而机器人应获取该ID并执行必要的操作。我提供了用于获取用户输入并给出响应的代码段。
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from keras.models import load_model
model = load_model('chatbot_model.h5')
import json
import random
intents = json.loads(open('intents.json').read())
words = pickle.load(open('words.pkl','rb'))
classes = pickle.load(open('classes.pkl','rb'))
def clean_up_sentence(sentence):
# tokenize the pattern - splitting words into array
sentence_words = nltk.word_tokenize(sentence)
# stemming every word - reducing to base form
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
return sentence_words
# return bag of words array: 0 or 1 for words that exist in sentence
def bag_of_words(sentence,words,show_details=True):
# tokenizing patterns
sentence_words = clean_up_sentence(sentence)
# bag of words - vocabulary matrix
bag = [0]*len(words)
for s in sentence_words:
for i,word in enumerate(words):
if word == s:
# assign 1 if current word is in the vocabulary position
bag[i] = 1
if show_details:
print ("found in bag: %s" % word)
return(np.array(bag))
def predict_class(sentence):
# filter below threshold predictions
p = bag_of_words(sentence,show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
# sorting strength probability
results.sort(key=lambda x: x[1],reverse=True)
return_list = []
for r in results:
return_list.append({"intent": classes[r[0]],"probability": str(r[1])})
return return_list
def getResponse(ints,intents_json):
tag = ints[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if(i['tag']== tag):
result = random.choice(i['responses'])
break
return result
我想到了一些可能的解决方法,一种是当单词被标记并根据出现次数分配编号时,用户提供的输入将出现0次。因此,我们可以构建对话并确保我们检测到的单词肯定是用户输入。但是,这不适用于可能有多个输入的情况。例如,如果用户要说,请在下午4点预定约会。星期一,这将是2个输入,而我建议的方法不会区分这两个输入。
此问题还有其他可能的解决方法吗?
预先感谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)