首页 > 编程语言 >手把手教你用Python构建自己的「王二狗」

手把手教你用Python构建自己的「王二狗」

时间:2023-06-25 13:00:58浏览次数:49  
标签:intents word sentence Python 教你用 bag 王二狗 words classes

导读

在人手N部智能手机的时代,我们对聊天机器人早已不陌生。这两年很火的游戏群聊天机器人「王二狗」更是用它的机智幽默征服了很多人。

今天,我们将手把手教你用Python从头开始创建一个聊天机器人,这种机器人能够理解用户的话,并给出适当的回应。闲话不多说,让我们开始从头开始做出自己的「王二狗」吧!

作者:Shivashish Thkaur

编译:刘文元

预      备

需要使用开源人工神经网络库Keras、自然语言处理工具NLTK和其他一些有用的库。运行以下命令以确保已安装所有的库:

pip install tensorflow keras pickle nltk

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

聊天机器人都属于NLP(自然语言处理)范畴。NPL包括两方面:

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

当我们向聊天机器人提问:“嘿,今天有什么新闻?”

聊天机器人会将我们的句子分解为两部分:意图和限定。这句话的意图可能是“获取新闻”,因为它意在说明用户想要执行的操作。而限定则指明了“意图”的具体细节,也就是“今天”。

项目文件结构

项目完成后,将会留下以下所有文件。让我们快速浏览一下,它们会让你了解这个项目是怎么实施的。

  • Train_chatbot.py——在这个文件里,我们将构建和训练深度学习模型,该模型可以分类和识别用户对聊天机器人的要求。
  • Gui_Chatbot.py——这个文件是用来构建图形用户界面、与聊天机器人聊天的。
  • Intents.json——这个意图文件有我们即将用于训练模型的所有数据,它包含一批标签及其相应的模式和响应。
  • Chatbot_model.h5——这是一个分层数据格式文件,其中存储了训练模型的权重和架构。
  • Classes.pkl——pickle文件可用于存储所有的标签名,以便对我们预测消息进行分类。
  • Words.pkl——这个文件包含模型的词汇表中所有的特有词语(unique words)。

可以在这里下载源代码和数据集↓

https://drive.google.com/drive/folders/1r6MrrdE8V0bWBxndGfJxJ4Om62dJ2OMP

开始构建自己的聊天机器人吧

我们通过5个步骤简化这个构建过程。

步骤1. 导入库并加载数据

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

Python

1import numpy as np
 2from keras.models import Sequential
 3from keras.layers import Dense, Activation, Dropout
 4from keras.optimizers import SGD
 5import random
 6
 7import nltk
 8from nltk.stem import WordNetLemmatizer
 9lemmatizer = WordNetLemmatizer()
10import json
11import pickle
12
13intents_file = open('intents.json').read()
14intents = json.loads(intents_file)
步骤2. 预处理数据

该模型不能读取原始数据,它必须经过大量的预处理才能让机器轻松地理解。文本数据有许多可用的预处理技术。一种技术叫令牌化(tokenizing),我们用它把句子分解成单词。

通过观察意图文件(intents file),可以看到每个标签都包含一个模式和响应的列表。把每个模式做令牌化处理,并将单词添加到列表中。此外,我们还创建了一个类别和文档列表,以添加跟模式相关的所有意图。

Python

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

还有一种技术是词形还原(lemmatization)。可以将单词转换成词根(lemma)形式,这样就可以减少所有的标准词,例如单词play、playing、plays、played等都能用play替换。如此一来,就能减少词汇表中的总单词数了。所以,我们现在对每个单词进行词形还原并删除重复的单词。

Python

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

最后,单词包含了项目词汇表、类别包含了要分类的全部限定。为将Python对象保存在一个文件里,我们用pickle.dump()方法。

步骤3. 创建训练和测试数据

为了训练模型,我们将没种输入模式转换成数字。首先,对模式的每个单词进行词形还原,并创建一个0列表,其长度与单词总数相同的。将只对那些在模式中包含该词的索引设置为1。同样地,通过为模式所属类输入设置1来创建输出。

Python

1# create the training data
 2training = []
 3# create empty array for the output
 4output_empty = [0] * len(classes)
 5# training set, bag of words for every sentence
 6for doc in documents:
 7    # initializing bag of words
 8    bag = []
 9    # list of tokenized words for the pattern
10    word_patterns = doc[0]
11    # lemmatize each word - create base word, 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 with 1, if word is found in current pattern
14    for word in words:
15        bag.append(1) if word in word_patterns else bag.append(0)
16
17    # output is a '0' for each tag and '1' for current tag (for each pattern)
18    output_row = list(output_empty)
19    output_row[classes.index(doc[1])] = 1
20    training.append([bag, output_row])
21# shuffle the features and make numpy array
22random.shuffle(training)
23training = np.array(training)
24# create training and testing lists. X - patterns, Y - intents
25train_x = list(training[:,0])
26train_y = list(training[:,1])
27print("Training data is created")
步骤4. 训练模型

该模型的架构将是一个由3个致密层组成的神经网络。第一层有128个神经元,第二层有64个神经元,最后一层的神经元数量与“类”的数量相同。引入丢弃层(drop out layers)是为了减少模型的过度拟合。我们使用SGD优化器并拟合数据来开始模型的训练。在完成了200个epoch的训练后,使用Keras model.save(“chatbot_model.h5”)保存训练好的模型。

Python

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

至此,我们的模型已经可以聊天了,所以现在让我们在一个新文件中为聊天机器人创建一个漂亮的图形用户界面。可以讲该文件命名为gui_chatbot.py

在GUI文件中,我们使用Tkinter模块来构建桌面应用程序的结构,然后我们将捕获用户的消息,并再次做一些预处理,然后将信息输入我们训练好的模型。

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

下面是GUI文件的完整源代码:

Python

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

最后:运行聊天机器人

现在我们有两个单独的文件,其中一个是train_chatbot.py,我们先用它来训练模型。

python train_chatbot.py

本文编译自:

https://dzone.com/articles/python-chatbot-project-build-your-first-python-pro


标签:intents,word,sentence,Python,教你用,bag,王二狗,words,classes
From: https://blog.51cto.com/u_15767091/6545033

相关文章

  • Python爬虫之数据解析技术
    Python爬虫需要数据解析的原因是,爬取到的网页内容通常是包含大量标签和结构的HTML或XML文档。这些文档中包含所需数据的信息,但是需要通过解析才能提取出来,以便后续的处理和分析。以下是一些使用数据解析的原因:数据提取:网页内容通常包含大量的无关信息和嵌套结构,数据解析可以帮......
  • Python全栈工程师(11:网络基础_网络协议篇)
    操作系统基础 操作系统:(OperatingSystem,简称OS)是管理和控制计算机硬件与软件资源的计算机程序,是直接运行在“裸机”上的最基本的系统软件,任何其他软件都必须在操作系统的支持下才能运行。注:计算机(硬件)->os->应用软件二.网络通信原理2.1互联网的本质就是一系列的网络协议......
  • Python全栈工程师(7:面向对象高级进阶)
    面向对象高级语法部分类的字段、方法、属性经典类vs新式类Python2中:经典类--深度优先;新式类--广度优先Python3中:均为广度优先super()方法:抽象接口#/usr/bin/env.python#-*-coding:utf-8-*-importabcclassAlert(object):'''报警基类'''__metaclass__=abc.......
  • Python全栈工程师(5:模块)
    模块介绍第三方库一般存放在site-packages下模块的定义:一个模块就是一个包含了一组功能的python文件,比如spam.py,模块名为spam,可以通过importspam使用。在python中,模块的使用方式都是一样的,细分模块可以分为四个通用类别:1使用python编写的.py文件(自定义模块)2已......
  • Python全栈工程师(31:css)
    css属性设置方法:方式1:在标签上设置style属性;<divstyle="height:10px;width:10px"></div>方式2:放在head里添加css模式;<head><style>#i1,#i2{height:10px;width:10px;}/*id选择器*/.c1{height:10px;width:10px;}/*class选择器*/div{height:10px......
  • python模块之hashlib
    用于加密相关的操作,3.x里代替了md5(不可反解)模块和sha模块,主要提供 SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法importhashlibm=hashlib.md5()m.update(b"He......
  • 成为python爬虫工程师需要哪些知识?
    爬虫(Webcrawler)是一种自动化程序,用于从互联网上抓取、解析和提取网页数据。它模拟浏览器行为,通过发送HTTP请求获取网页内容,并通过解析网页源代码或DOM结构,提取所需的信息。以python爬虫为例,作为一名合格的工程师需要具备那些专业技能?Python爬虫的难度可以因个人经验和项目需求而......
  • python 大根堆
    python默认的都是小根堆,实现数字的大根堆,可在堆化前把数字乘以-1,输出时再乘以-1变回原值。比如:[5,20,6],堆化前用列表推导式把列表转为: [-5,-20,-6]importheapqimportrandomdata=list(range(1,30))random.shuffle(data)#打乱顺序data=data[:12]#......
  • 基于k6和python进行自动化性能测试
    摘要:在性能测试中,达到相应的性能指标对于一个软件来说十分重要,在本文中,将介绍一种现代化性能测试工具k6。本文分享自华为云社区《基于k6和python进行自动化性能测试》,作者:风做了云的梦。当我们开发完成一个应用程序时,往往需要对其进行性能测试,以帮助我们更好的优化程序以及发现......
  • pytest + yaml 框架 -41.postman 和 python代码也能录制成用例
    前言python代码和postman写的接口也能通过录制功能自动生成yaml格式用例了。python代码运行后自动录制环境准备参考前面一篇https://www.cnblogs.com/yoyoketang/p/17495374.html在项目本地新建一个recorde.py,名称随便定义frompytest_yaml_yoyo.mitm_httpimportRecode......