聊天机器人对商业组织和客户都是非常有用的。大多数人更喜欢直接在Chatbox上交谈,而不是打电话给服务中心。Facebook发布的数据证明了机器人的价值。每月在人与公司之间发送超过20亿条信息。HubSpot的研究表明,71%的人希望从短信应用中获得客户支持。这是一种快速解决问题的方法,因此聊天机器人在组织中有着光明的前景。
入门Python其实很容易,但是我们要去坚持学习,每一天坚持很困难,我相信很多人学了一个星期就放弃了,为什么呢?其实没有好的学习资料给你去学习,你们是很难坚持的,这是小编收集的Python入门学习资料关注,转发,私信小编“01”,即可免费领取!希望对你们有帮助
今天,我们将在聊天机器人上建立一个令人兴奋的项目。我们将从无到有地实现一个聊天机器人,它将能够理解用户在谈论什么,并给出适当的响应。
先决条件
为了实现聊天机器人,我们将使用Keras(深度学习库)、NLTK(自然语言处理工具包)和一些有用的库。运行以下命令以确保安装了所有库
pip install tensorflow keras pickle nltk
Python备忘单- 免费学习Python的大师指南 .
聊天机器人是怎么工作的?
聊天机器人不过是一款智能软件,可以像人类一样与人进行交互和交流。有意思,不是吗!现在让我们了解它们是如何工作的。所有聊天机器人都属于NLP(自然语言处理)概念。NLP由两部分组成:
- 自然语言理解(NLU):机器理解人类语言如英语的能力。
- 自然语言生成(NLG):机器生成类似于人类书面句子的文本的能力。
想象一个用户问聊天机器人一个问题:“嘿,今天的新闻是什么?”聊天机器人将用户句子分解为两种情况:意图和实体。这个句子的意图可以是get_news,因为它指的是用户想要执行的操作。实体告诉具体细节的意图,所以这里‘今天’将是实体。因此,使用机器学习模型来识别聊天的意图和实体。
项目文件结构
项目完成后,您将得到所有这些文件。让我们快速浏览其中的每一个,它将给您一个如何实现项目的想法。
- 火车聊天室-在这个文件中,我们将建立和训练能够分类和识别用户对BOT的要求的深度学习模型。
- Gui_Chatbot.py-在这个文件中,我们将构建一个图形用户界面,与我们训练有素的聊天机器人聊天。
- 詹森intents文件包含我们将用来训练模型的所有数据。它包含一组标记及其对应的模式和响应。
- 聊天机器人模型.5-这是一个分层的数据格式文件,我们在其中存储了经过训练的模型的权重和体系结构。
- 类别.pkl-当我们预测消息时,泡菜文件可以用来存储所有要分类的标签名。
- Words.pkl-pkl泡菜文件包含所有唯一的单词,它们是我们模型的词汇表。
下载源代码和数据集
如何建立自己的聊天机器人?
我在5个步骤中简化了这个聊天机器人的构建:
步骤1.导入库并加载数据--创建一个新的python文件并将其命名为TRANCHATBOT,然后我们将导入所有必需的模块。之后,我们将在python程序中读取JSON数据文件。
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD
import random
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import json
import pickle
intents_file = open('intents.json').read()
intents = json.loads(intents_file)
下面是我们的意图文件的样子。
步骤2.数据预处理
模型不能接受原始数据。为了使机器易于理解,它必须经过大量的预处理。对于文本数据,有许多可用的预处理技术。第一种方法是标记化,我们把句子分解成单词。
通过观察intents文件,我们可以看到每个标记都包含一个模式和响应列表。我们标记每个模式并在列表中添加单词。此外,我们还创建了一个类和文档列表,以添加与模式相关的所有意图。
words=[]
classes = []
documents = []
ignore_letters = ['!', '?', ',', '.']
for intent in intents['intents']:
for pattern in intent['patterns']:
#tokenize each word
word = nltk.word_tokenize(pattern)
words.extend(word)
#add documents in the corpus
documents.append((word, intent['tag']))
# add to our classes list
if intent['tag'] not in classes:
classes.append(intent['tag'])
print(documents)
另一种技术是莱曼化。我们可以把单词转换成引理形式,这样我们就可以减少所有的规范词。例如,单词Play,Play等等都将被替换为Play。这样我们就可以减少词汇量中的总单词数。所以,现在我们把每个单词混合起来,去掉重复的单词。
# lemmaztize and lower each word and remove duplicates
words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_letters]
words = sorted(list(set(words)))
# sort classes
classes = sorted(list(set(classes)))
# documents = combination between patterns and intents
print (len(documents), "documents")
# classes = intents
print (len(classes), "classes", classes)
# words = all words, vocabulary
print (len(words), "unique lemmatized words", words)
pickle.dump(words,open('words.pkl','wb'))
pickle.dump(classes,open('classes.pkl','wb'))
最后,单词包含我们项目的词汇表,类包含要分类的全部实体。为了将python对象保存在文件中,我们使用泡菜()方法。这些文件将有助于完成培训和我们预测的聊天。
步骤3.创建培训和测试数据
为了训练模型,我们将把每个输入模式转换为数字。首先,我们将对模式中的每个单词进行归纳,并创建一个与单词总数相同长度的零列表。我们将值1设置为仅包含模式中单词的索引。同样,我们将通过将1设置为属于的类输入模式来创建输出。
# create the training data
training = []
# create empty array for the output
output_empty = [0] * len(classes)
# training set, bag of words for every sentence
for doc in documents:
# initializing bag of words
bag = []
# list of tokenized words for the pattern
word_patterns = doc[0]
# lemmatize each word - create base word, in attempt to represent related words
word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]
# create the bag of words array with 1, if word is found in current pattern
for word in words:
bag.append(1) if word in word_patterns else bag.append(0)
# output is a '0' for each tag and '1' for current tag (for each pattern)
output_row = list(output_empty)
output_row[classes.index(doc[1])] = 1
training.append([bag, output_row])
# shuffle the features and make numpy array
random.shuffle(training)
training = np.array(training)
# create training and testing lists. X - patterns, Y - intents
train_x = list(training[:,0])
train_y = list(training[:,1])
print("Training data is created")
步骤4.培训模型
该模型的结构将是一个由3个稠密层组成的神经网络。第一层有128个神经元,第二个层有64个神经元,最后一层的神经元数量与类数相同。为了减少模型的过度拟合,引入了降层。我们使用SGD优化器,并对数据进行拟合,开始对模型进行训练。在完成了200个历元的训练之后,我们使用Keras模型.Save(“chatbot_model.h5”)函数保存训练过的模型。
# deep neural networds model
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))
# Compiling model. SGD with Nesterov accelerated gradient gives good results for this model
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
#Training and saving the model
hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save('chatbot_model.h5', hist)
print("model is created")
步骤5.与聊天机器人交互
我们的模型已经准备好聊天了,所以现在让我们在一个新的文件中为聊天机器人创建一个很好的图形用户界面。您可以将该文件命名为gui_chatbot.py。
在GUI文件中,我们将使用Tkinter模块构建桌面应用程序的结构,然后我们将捕获用户消息,并在将消息输入经过训练的模型之前再次执行一些预处理。
然后,模型将预测用户消息的标记,我们将从意图文件中的响应列表中随机选择响应。
下面是GUI文件的完整源代码。
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, words,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
#Creating tkinter GUI
import tkinter
from tkinter import *
def send():
msg = EntryBox.get("1.0",'end-1c').strip()
EntryBox.delete("0.0",END)
if msg != '':
ChatBox.config(state=NORMAL)
ChatBox.insert(END, "You: " + msg + '\n\n')
ChatBox.config(foreground="#446665", font=("Verdana", 12 ))
ints = predict_class(msg)
res = getResponse(ints, intents)
ChatBox.insert(END, "Bot: " + res + '\n\n')
ChatBox.config(state=DISABLED)
ChatBox.yview(END)
root = Tk()
root.title("Chatbot")
root.geometry("400x500")
root.resizable(width=FALSE, height=FALSE)
#Create Chat window
ChatBox = Text(root, bd=0, bg="white", height="8", width="50", font="Arial",)
ChatBox.config(state=DISABLED)
#Bind scrollbar to Chat window
scrollbar = Scrollbar(root, command=ChatBox.yview, cursor="heart")
ChatBox['yscrollcommand'] = scrollbar.set
#Create Button to send message
SendButton = Button(root, font=("Verdana",12,'bold'), text="Send", width="12", height=5,
bd=0, bg="#f9a602", activebackground="#3c9d9b",fg='#000000',
command= send )
#Create the box to enter message
EntryBox = Text(root, bd=0, bg="white",width="29", height="5", font="Arial")
#EntryBox.bind("<Return>", send)
#Place all components on the screen
scrollbar.place(x=376,y=6, height=386)
ChatBox.place(x=6,y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=90, width=265)
SendButton.place(x=6, y=401, height=90)
root.mainloop()
运行聊天机器人
现在我们有两个独立的文件,一个是TRANCHatbot.py,我们将首先使用这个文件来训练模型。
python train_chatbot.py