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

开发 后端 机器人
利用Python,我们可以实现很多目标,比如说建立一个你专属的聊天机器人程序。聊天机器人程序不光满足个人需求,它对商业组织和客户都非常有帮助。大多数人喜欢直接通过聊天室交谈,而不是打电话给服务中心。

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

[[316320]]

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

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

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

先决条件

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

  1. pip installtensorflow keras pickle nltk 

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

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

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

  • NLU(自然语言理解):机器理解人类语言(如英语)的能力。
  • NLG(自然语言生成):机器生成类似于人类书面句子的文本的能力。

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

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

项目文件结构

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

  • 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数据文件。 

  1. importnumpy as np 
  2. fromkeras.models importSequential 
  3. fromkeras.layers importDense, Activation,Dropout 
  4. fromkeras.optimizers importSGD 
  5. importrandom 
  6. importnltk 
  7. fromnltk.stem importWordNetLemmatizer 
  8. lemmatizer = WordNetLemmatizer() 
  9. importjson 
  10. importpickle 
  11. intents_file = open('intents.json').read() 
  12. intents= json.loads(intents_file) 

第二步:数据预处理

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

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

  1. words=[] 
  2. classes= [] 
  3. documents= [] 
  4. ignore_letters = ['!''?'',''.'
  5. forintent in intents['intents']: 
  6. forpattern in intent['patterns']: 
  7. #tokenize each word 
  8. word= nltk.word_tokenize(pattern) 
  9. words.extend(word) 
  10. #add documents in the corpus 
  11. documents.append((word, intent['tag'])) 
  12. add to our classes list 
  13. ifintent['tag'] notin classes: 
  14. classes.append(intent['tag']) 
  15. print(documents) 

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

  1. # lemmaztize and lower each word andremove duplicates 
  2. words= [lemmatizer.lemmatize(w.lower()) forw in words if w notinignore_letters] 
  3. words= sorted(list(set(words))) 
  4. # sort classes 
  5. classes= sorted(list(set(classes))) 
  6. # documents = combination betweenpatterns and intents 
  7. print(len(documents), "documents"
  8. # classes = intents 
  9. print(len(classes), "classes", classes) 
  10. # words = all words, vocabulary 
  11. print(len(words), "unique lemmatized words", words) 
  12. pickle.dump(words,open('words.pkl','wb')) 
  13. pickle.dump(classes,open('classes.pkl','wb')) 

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

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

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

  1. create the training data 
  2. training= [] 
  3. create empty array for the output 
  4. output_empty = [0] * len(classes) 
  5. # training set, bag of words for everysentence 
  6. fordoc in documents: 
  7. # initializing bag of words 
  8. bag= [] 
  9. # list of tokenized words for thepattern 
  10. word_patterns = doc[0] 
  11. # lemmatize each word - create baseword, in attempt to represent related words 
  12. word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns] 
  13. create the bag of words array with1, if word is found in current pattern 
  14. forword in words: 
  15. bag.append(1) if word inword_patterns else bag.append(0) 
  16. output is a '0' for each tag and '1'for current tag (for each pattern) 
  17. output_row = list(output_empty) 
  18. output_row[classes.index(doc[1])] = 1 
  19. training.append([bag, output_row]) 
  20. # shuffle the features and make numpyarray 
  21. random.shuffle(training) 
  22. training= np.array(training) 
  23. create training and testing lists. X- patterns, Y - intents 
  24. train_x= list(training[:,0]) 
  25. train_y= list(training[:,1]) 
  26. print("Training data is created"

第四步:训练模型

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

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

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

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

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

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

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

  1. importnltk 
  2. fromnltk.stem importWordNetLemmatizer 
  3. lemmatizer = WordNetLemmatizer() 
  4. importpickle 
  5. importnumpy as np 
  6. fromkeras.models importload_model 
  7. model= load_model('chatbot_model.h5'
  8. importjson 
  9. importrandom 
  10. intents= json.loads(open('intents.json').read()) 
  11. words= pickle.load(open('words.pkl','rb')) 
  12. classes= pickle.load(open('classes.pkl','rb')) 
  13. defclean_up_sentence(sentence): 
  14. # tokenize the pattern - splittingwords into array 
  15. sentence_words = nltk.word_tokenize(sentence) 
  16. # stemming every word - reducing tobase form 
  17. sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] 
  18. returnsentence_words 
  19. return bag of words array: 0 or 1for words that exist in sentence 
  20. defbag_of_words(sentence, words,show_details=True): 
  21. # tokenizing patterns 
  22. sentence_words = clean_up_sentence(sentence) 
  23. # bag of words - vocabulary matrix 
  24. bag= [0]*len(words) 
  25. fors in sentence_words: 
  26. fori,word inenumerate(words): 
  27. ifword == s: 
  28. # assign 1 if current word is in thevocabulary position 
  29. bag[i] = 1 
  30. ifshow_details: 
  31. print("found in bag:%s" % word) 
  32. return(np.array(bag)) 
  33. defpredict_class(sentence): 
  34. # filter below thresholdpredictions 
  35. p= bag_of_words(sentence,words,show_details=False
  36. res= model.predict(np.array([p]))[0] 
  37. ERROR_THRESHOLD = 0.25 
  38. results= [[i,r] fori,r inenumerate(res) ifr>ERROR_THRESHOLD] 
  39. # sorting strength probability 
  40. results.sort(key=lambdax: x[1],reverse=True
  41. return_list = [] 
  42. forr in results: 
  43. return_list.append({"intent": classes[r[0]],"probability": str(r[1])}) 
  44. returnreturn_list 
  45. defgetResponse(ints, intents_json): 
  46. tag= ints[0]['intent'
  47. list_of_intents = intents_json['intents'
  48. fori in list_of_intents: 
  49. if(i['tag']== tag): 
  50. result= random.choice(i['responses']) 
  51. break 
  52. returnresult 
  53. #Creating tkinter GUI 
  54. importtkinter 
  55. fromtkinter import * 
  56. defsend(): 
  57. msg= EntryBox.get("1.0",'end-1c').strip() 
  58. EntryBox.delete("0.0",END
  59. ifmsg != ''
  60. ChatBox.config(state=NORMAL) 
  61. ChatBox.insert(END"You: " + msg+ '\n\n'
  62. ChatBox.config(foreground="#446665", font=("Verdana", 12 )) 
  63. ints= predict_class(msg) 
  64. res= getResponse(ints,intents) 
  65. ChatBox.insert(END"Bot: " + res+ '\n\n'
  66. ChatBox.config(state=DISABLED) 
  67. ChatBox.yview(END
  68. root= Tk() 
  69. root.title("Chatbot"
  70. root.geometry("400x500" 
  71. root.resizable(width=FALSE, height=FALSE
  72. #Create Chat window 
  73. ChatBox= Text(root, bd=0, bg="white",height="8", width="50", font="Arial",) 
  74. ChatBox.config(state=DISABLED) 
  75. #Bind scrollbar to Chat window 
  76. scrollbar= Scrollbar(root,command=ChatBox.yview, cursor="heart"
  77. ChatBox['yscrollcommand'] = scrollbar.set 
  78. #Create Button to send message 
  79. SendButton = Button(root,font=("Verdana",12,'bold'),text="Send", width="12", height=5, 
  80. bd=0,bg="#f9a602",activebackground="#3c9d9b",fg='#000000'
  81. command=send ) 
  82. #Create the box to enter message 
  83. EntryBox= Text(root, bd=0, bg="white",width="29", height="5", font="Arial"
  84. #EntryBox.bind("<Return>",send) 
  85. #Place all components on the screen 
  86. scrollbar.place(x=376,y=6, height=386) 
  87. ChatBox.place(x=6,y=6, height=386,width=370) 
  88. EntryBox.place(x=128,y=401, height=90,width=265) 
  89. SendButton.place(x=6,y=401, height=90) 
  90. root.mainloop() 

运行聊天机器人

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

  1. pythontrain_chatbot.py 

快来试试吧~

 

责任编辑:华轩 来源: 今日头条
相关推荐

2016-10-09 13:40:44

PythonSlack聊天机器人

2020-07-30 08:06:34

Python开发工具

2020-08-07 14:40:09

Python聊天机器人编程语言

2022-09-30 13:55:46

Python机器人

2021-11-30 10:56:43

ChatterBot机器人人工智能

2023-12-18 19:05:34

2020-12-02 13:00:17

Recast.AI聊天机器人人工智能

2021-05-24 15:29:24

人工智能机器人聊天

2021-10-28 22:46:13

Python机器人数据

2022-08-04 07:03:41

AnswersInfobip无代码

2022-07-05 06:42:01

聊天机器人人工智能

2017-06-08 10:07:53

机器人银行微软

2019-04-19 14:40:15

代码Python机器人

2020-02-20 09:00:00

网络应用数据技术

2017-08-21 13:31:44

AI聊天机器人facebook

2023-07-27 14:38:58

人工智能机器人开发

2020-02-02 09:19:14

聊天机器人机器人智能

2021-03-30 17:51:25

机器人系统聊天

2018-06-08 16:18:43

Python微信聊天机器人

2017-03-28 12:21:21

机器人定义
点赞
收藏

51CTO技术栈公众号