​快来!建立你的第一个Python聊天机器人项目

全文共7900字,预计学习时长

23分钟

​快来!建立你的第一个Python聊天机器人项目


利用Python,我们可以实现很多目标,比如说建立一个你专属的聊天机器人程序。

聊天机器人程序不光满足个人需求,它对商业组织和客户都非常有帮助。大多数人喜欢直接通过聊天室交谈,而不是打电话给服务中心。


Facebook发布的数据证明了机器人的价值。每月有超过20亿条信息在人和公司之间发送。HubSpot的研究显示,71%的人希望从信息应用程序获得客户支持。这是解决问题的快速方法,因此聊天机器人在组织中有着光明的未来。


今天要做的是在Chatbot上建立一个令人兴奋的项目。,从零开始完成一个聊天机器人,它将能够理解用户正在谈论的内容并给出适当的回应。


先决条件


为了实现聊天机器人,将使用一个深度学习库Keras,一个自然语言处理工具包NLTK,以及一些有用的库。运行以下命令以确保安装了所有库:


<code>pip installtensorflow keras pickle nltk/<code>


聊天机器人是如何工作的?


聊天机器人只是一个智能软件,可以像人类一样与人互动和交流。很有趣,不是吗?现在来看看它们是如何工作的。


所有聊天机器人都基于自然语言处理(NLP)概念。NLP由两部分组成:


· NLU(自然语言理解):机器理解人类语言(如英语)的能力。


· NLG(自然语言生成):机器生成类似于人类书面句子的文本的能力。


想象一个用户问聊天机器人一个问题:“嘿,今天有什么新闻?”


该聊天机器人就会将用户语句分解为两个部分:意图和实体。这句话的目的可能是获取新闻,因为它指的是用户希望执行的操作。实体告诉了关于意图的具体细节,所以“今天”将是实体。因此,这里使用机器学习模型来识别聊天的意图和实体。


​快来!建立你的第一个Python聊天机器人项目


项目文件结构


项目完成后,将留下所有这些文件。快速浏览每一个。它将给开发员一个如何实施该项目的想法。


· Train_chatbot.py-在本文件中,构建和训练深度学习模型,该模型可以分类和识别用户向机器人提出的要求。


· Gui_Chatbot.py-这个文件是构建图形用户界面用来与训练后的聊天机器人聊天的地方。


· Intents.json-Intents文件包含将用于训练模型的所有数据。它包含一组标记及其相应的模式和响应。


· Chatbot_model.h5-这是一个分层数据格式文件,其中存储了训练模型的权重和体系结构。


· Classes.pkl-pickle文件可用于存储预测消息时要分类的所有标记名。


· Words.pkl-Words.pklpickle文件包含模型词汇表中的所有唯一单词。


下载源代码和数据集:


mailto:https://drive.google.com/drive/folders/1r6MrrdE8V0bWBxndGfJxJ4Om62dJ2OMP?usp=sharing


如何建立自己的聊天机器人?


笔者将这个聊天机器人的构建简化为5个步骤:


第一步。导入库并加载数据


创建一个新的python文件并将其命名为train_chatbot,然后导入所有必需的模块。之后,从Python程序中读取JSON数据文件。


<code>importnumpy as np/<code>
<code>fromkeras.models importSequential/<code>
<code>fromkeras.layers importDense, Activation,Dropout/<code>
<code>fromkeras.optimizers importSGD/<code>
<code>importrandom/<code>
<code>importnltk/<code>
<code>fromnltk.stem importWordNetLemmatizer/<code>
<code>lemmatizer = WordNetLemmatizer()/<code>
<code>importjson/<code>
<code>importpickle/<code>
<code>intents_file = open('intents.json').read()/<code>
<code>intents= json.loads(intents_file)/<code>

第二步。数据预处理


模型无法获取原始数据。为了使机器容易理解,必须经过许多预处理。对于文本数据,有许多预处理技术可用。第一种技术是标记化,把句子分解成单词。


通过观察intents文件,可以看到每个标记包含模式和响应的列表。标记每个模式并将单词添加到列表中。另外,创建一个类和文档列表来添加与模式相关的所有意图。


<code>words=[]/<code>
<code>classes= []/<code>
<code>documents= []/<code>
<code>ignore_letters = ['!', '?', ',', '.']/<code>
<code>forintent in intents['intents']:/<code>
<code>forpattern in intent['patterns']:/<code>
<code>#tokenize each word/<code>
<code>word= nltk.word_tokenize(pattern)/<code>
<code>words.extend(word)/<code>
<code>#add documents in the corpus/<code>
<code>documents.append((word, intent['tag']))/<code>
<code># add to our classes list/<code>
<code>ifintent['tag'] notin classes:/<code>
<code>classes.append(intent['tag'])/<code>
<code>print(documents)/<code>

另一种技术是词形还原。我们可以将单词转换成引理形式,这样就可以减少所有的规范单词。例如,单词play、playing、playing、played等都将替换为play。这样,可以减少词汇表中的单词总数。所以将每个单词进行引理,去掉重复的单词。


<code># lemmaztize and lower each word andremove duplicates/<code>
<code>words= [lemmatizer.lemmatize(w.lower()) forw in words if w notinignore_letters]/<code>
<code>words= sorted(list(set(words)))/<code>
<code># sort classes/<code>
<code>classes= sorted(list(set(classes)))/<code>
<code># documents = combination betweenpatterns and intents/<code>
<code>print(len(documents), "documents")/<code>
<code># classes = intents/<code>
<code>print(len(classes), "classes", classes)/<code>
<code># words = all words, vocabulary/<code>
<code>print(len(words), "unique lemmatized words", words)/<code>
<code>pickle.dump(words,open('words.pkl','wb'))/<code>
<code>pickle.dump(classes,open('classes.pkl','wb'))/<code>

最后,单词包含了项目的词汇表,类包含了要分类的所有实体。为了将python对象保存在文件中,使用pickle.dump()方法。这些文件将有助于训练完成后进行预测聊天。


​快来!建立你的第一个Python聊天机器人项目


第三步。创建训练集和测试集


为了训练模型,把每个输入模式转换成数字。首先,对模式中的每个单词进行引理,并创建一个长度与单词总数相同的零列表。只将值1设置为那些在模式中包含单词的索引。同样,将1设置为模式所属的类输入,来创建输出。


<code># create the training data/<code>
<code>training= []/<code>
<code># create empty array for the output/<code>
<code>output_empty = [0] * len(classes)/<code>
<code># training set, bag of words for everysentence/<code>
<code>fordoc in documents:/<code>
<code># initializing bag of words/<code>
<code>bag= []/<code>
<code># list of tokenized words for thepattern/<code>
<code>word_patterns = doc[0]/<code>
<code># lemmatize each word - create baseword, in attempt to represent related words/<code>
<code>word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]/<code> 
<code># create the bag of words array with1, if word is found in current pattern/<code>
<code>forword in words:/<code>
<code>bag.append(1) if word inword_patterns else bag.append(0)/<code>
<code># output is a '0' for each tag and '1'for current tag (for each pattern)/<code>
<code>output_row = list(output_empty)/<code>
<code>output_row[classes.index(doc[1])] = 1/<code>
<code>training.append([bag, output_row])/<code>
<code># shuffle the features and make numpyarray/<code>
<code>random.shuffle(training)/<code>
<code>training= np.array(training)/<code>
<code># create training and testing lists. X- patterns, Y - intents/<code>
<code>train_x= list(training[:,0])/<code>
<code>train_y= list(training[:,1])/<code>
<code>print("Training data is created")/<code>

第四步。训练模型


该模型将是一个由3个密集层组成的神经网络。第一层有128个神经元,第二层有64个,最后一层的神经元数量与类数相同。为了减少模型的过度拟合,引入了dropout层。使用SGD优化器并对数据进行拟合,开始模型的训练。在200个阶段的训练完成后,使用Kerasmodel.save(“chatbot_model.h5”)函数保存训练的模型。


<code># deep neural networds model/<code>
<code>model= Sequential()/<code>
<code>model.add(Dense(128,input_shape=(len(train_x[0]),), activation='relu'))/<code>
<code>model.add(Dropout(0.5))/<code>
<code>model.add(Dense(64,activation='relu'))/<code>
<code>model.add(Dropout(0.5))/<code>
<code>model.add(Dense(len(train_y[0]), activation='softmax'))/<code>
<code># Compiling model. SGD with Nesterovaccelerated gradient gives good results for this model/<code>
<code>sgd= SGD(lr=0.01,decay=1e-6, momentum=0.9, nesterov=True)/<code>
<code>model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])/<code>
<code>#Training and saving the model/<code>
<code>hist= model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5,verbose=1)/<code>
<code>model.save('chatbot_model.h5', hist)/<code>
<code>print("model is created")/<code>

第五步。与聊天机器人互动


模型已经准备好聊天了,现在在一个新文件中为聊天机器人创建一个很好的图形用户界面。可以将文件命名为gui_chatbot.py


在GUI文件中,使用Tkinter模块构建桌面应用程序的结构,然后捕获用户消息,并在将消息输入到训练模型之前,再次执行一些预处理。


然后,模型将预测用户消息的标签,从intents文件的响应列表中随机选择响应。


这是GUI文件的完整源代码。


<code>importnltk/<code>
<code>fromnltk.stem importWordNetLemmatizer/<code>
<code>lemmatizer = WordNetLemmatizer()/<code>
<code>importpickle/<code>
<code>importnumpy as np/<code>
<code>fromkeras.models importload_model/<code>
<code>model= load_model('chatbot_model.h5')/<code>
<code>importjson/<code>
<code>importrandom/<code>
<code>intents= json.loads(open('intents.json').read())/<code>
<code>words= pickle.load(open('words.pkl','rb'))/<code>
<code>classes= pickle.load(open('classes.pkl','rb'))/<code>
<code>defclean_up_sentence(sentence):/<code>
<code># tokenize the pattern - splittingwords into array/<code>
<code>sentence_words = nltk.word_tokenize(sentence)/<code>
<code># stemming every word - reducing tobase form/<code>
<code>sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]/<code>
<code>returnsentence_words/<code>
<code># return bag of words array: 0 or 1for words that exist in sentence/<code>
<code>defbag_of_words(sentence, words,show_details=True):/<code>
<code># tokenizing patterns/<code>
<code>sentence_words = clean_up_sentence(sentence)/<code>
<code># bag of words - vocabulary matrix/<code>
<code>bag= [0]*len(words)/<code>
<code>fors in sentence_words:/<code>
<code>fori,word inenumerate(words):/<code>
<code>ifword == s:/<code>
<code># assign 1 if current word is in thevocabulary position/<code>
<code>bag[i] = 1/<code>
<code>ifshow_details:/<code>
<code>print("found in bag:%s" % word)/<code>
<code>return(np.array(bag))/<code>
<code>defpredict_class(sentence):/<code>
<code># filter below thresholdpredictions/<code>
<code>p= bag_of_words(sentence,words,show_details=False)/<code>
<code>res= model.predict(np.array([p]))[0]/<code>
<code>ERROR_THRESHOLD = 0.25/<code>
<code>results= [[i,r] fori,r inenumerate(res) ifr>ERROR_THRESHOLD]/<code>
<code># sorting strength probability/<code>
<code>results.sort(key=lambdax: x[1],reverse=True)/<code>
<code>return_list = []/<code>
<code>forr in results:/<code>
<code>return_list.append({"intent": classes[r[0]],"probability": str(r[1])})/<code>
<code>returnreturn_list/<code>
<code>defgetResponse(ints, intents_json):/<code>
<code>tag= ints[0]['intent']/<code>
<code>list_of_intents = intents_json['intents']/<code>
<code>fori in list_of_intents:/<code>
<code>if(i['tag']== tag):/<code>
<code>result= random.choice(i['responses'])/<code>
<code>break/<code>
<code>returnresult/<code>
<code>#Creating tkinter GUI/<code>
<code>importtkinter/<code>
<code>fromtkinter import */<code>
<code>defsend():/<code>
<code>msg= EntryBox.get("1.0",'end-1c').strip()/<code>
<code>EntryBox.delete("0.0",END)/<code>
<code>ifmsg != '':/<code>
<code>ChatBox.config(state=NORMAL)/<code>
<code>ChatBox.insert(END, "You: " + msg+ '\\n\\n')/<code>
<code>ChatBox.config(foreground="#446665", font=("Verdana", 12 ))/<code>
<code>ints= predict_class(msg)/<code>
<code>res= getResponse(ints,intents)/<code>
<code>ChatBox.insert(END, "Bot: " + res+ '\\n\\n')/<code>
<code>ChatBox.config(state=DISABLED)/<code>
<code>ChatBox.yview(END)/<code>
<code>root= Tk()/<code>
<code>root.title("Chatbot")/<code>
<code>root.geometry("400x500"/<code>
<code>root.resizable(width=FALSE, height=FALSE)/<code>
<code>#Create Chat window/<code>
<code>ChatBox= Text(root, bd=0, bg="white",height="8", width="50", font="Arial",)/<code>
<code>ChatBox.config(state=DISABLED)/<code>
<code>#Bind scrollbar to Chat window/<code>
<code>scrollbar= Scrollbar(root,command=ChatBox.yview, cursor="heart")/<code>
<code>ChatBox['yscrollcommand'] = scrollbar.set/<code>
<code>#Create Button to send message/<code>
<code>SendButton = Button(root,font=("Verdana",12,'bold'),text="Send", width="12", height=5,/<code>
<code>bd=0,bg="#f9a602",activebackground="#3c9d9b",fg='#000000',/<code>
<code>command=send )/<code>
<code>#Create the box to enter message/<code>
<code>EntryBox= Text(root, bd=0, bg="white",width="29", height="5", font="Arial")/<code>
<code>#EntryBox.bind("<return>",send)/<return>/<code>
<code>#Place all components on the screen/<code>
<code>scrollbar.place(x=376,y=6, height=386)/<code>
<code>ChatBox.place(x=6,y=6, height=386,width=370)/<code>
<code>EntryBox.place(x=128,y=401, height=90,width=265)/<code>
<code>SendButton.place(x=6,y=401, height=90)/<code>
<code>root.mainloop()/<code>

运行聊天机器人


​快来!建立你的第一个Python聊天机器人项目

现在有两个独立的文件,一个是train_chatbot.py,首先使用它来训练模型。


<code>pythontrain_chatbot.py/<code>


快来试试吧~

​快来!建立你的第一个Python聊天机器人项目

​快来!建立你的第一个Python聊天机器人项目

我们一起分享AI学习与发展的干货


分享到:


相關文章: