chatbot使用

聊天机器人对企业组织和客户都非常有帮助。 大多数人都喜欢直接从聊天室进行交谈,而不是致电服务中心。 Facebook发布的数据证明了机器人的价值。 每月在人与公司之间发送的消息超过20亿条。 HubSpot研究表明,有71%的人希望从消息传递应用程序获得客户支持。 这是解决问题的快速方法,因此聊天机器人在组织中拥有光明的前景。

今天,我们将在Chatbot上构建一个令人兴奋的项目。 我们将从头开始实现一个聊天机器人,该聊天机器人将能够理解用户在说什么并给出适当的响应。

先决条件

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

pipinstall tensorflow keras pickle nltk 

Python备忘单- 免费学习Python的主要指南

聊天机器人如何工作?

聊天机器人不过是一种智能软件,可以像人类一样与人互动和交流。 有趣吗? 现在让我们了解它们的实际工作原理。 所有聊天机器人都属于NLP(自然语言处理)概念。 NLP由两部分组成:

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

向用户提问,向聊天机器人成像“嘿,今天的新闻是什么? 聊天机器人会将用户句子分为两部分:意图和实体。 该句子的意图可能是get_news,因为它表示用户想要执行的操作。 实体会告知有关意图的具体细节,因此“今天”将是实体。 因此,通过这种方式,机器学习模型可用于识别聊天的意图和实体。

项目文件结构

项目完成后,将剩下所有这些文件。 让我们快速浏览它们的每一个,它将使您对如何实施该项目有所了解。

  1. Train_chatbot.py-在此文件中,我们将构建和训练深度学习模型,该模型可以分类和识别用户对机器人的要求。
  2. Gui_Chatbot.py-此文件是我们将在其中建立图形用户界面以与我们训练有素的聊天机器人聊天的地方。
  3. Intents.json-intents文件包含我们将用于训练模型的所有数据。 它包含标签的集合及其相应的模式和响应。
  4. Chatbot_model.h5-这是一个分层数据格式文件,我们在其中存储了经过训练的模型的权重和体系结构。
  5. Classes.pkl-泡菜文件可用于存储所有标签名称,以便在我们预测消息时进行分类。
  6. Words.pkl- words.pkl泡菜文件包含所有唯一的单词,这些单词都是我们模型的词汇。

下载源代码和数据集

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

我通过5个步骤简化了此聊天机器人的构建:

步骤1.导入库并加载数据 -创建一个新的python文件,并将其命名为train_chatbot,然后我们将导入所有必需的模块。 之后,我们将在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.预处理数据

该模型无法获取原始数据。 为了使机器易于理解,它必须经过很多预处理。 对于文本数据,有许多可用的预处理技术。 第一种技术是令牌化,其中我们将句子分解为单词。

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

words=[]
classes = []
documents = []
ignore_letters = ['!' , '?' , ',' , '.' ]
for intent in intents[ 'intents' ]:for pattern in intent[ 'patterns' ]:#tokenize each wordword = nltk.word_tokenize(pattern)words.extend(word)#add documents in the corpusdocuments.append((word, intent[ 'tag' ]))# add to our classes listif intent[ 'tag' ] not in classes:classes.append(intent[ 'tag' ])
print(documents)

另一种技术是放缩。 我们可以将单词转换为引理形式,以便我们可以减少所有规范的单词。 例如,单词play(正在播放),playing(正在播放),plays(已播放),played(已播放)等都将被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对象保存在文件中,我们使用了pickle.dump()方法。 这些文件在培训结束后将很有帮助,我们可以预测聊天记录。

步骤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 wordsbag = []# list of tokenized words for the patternword_patterns = doc[ 0 ]# lemmatize each word - create base word, in attempt to represent related wordsword_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]# create the bag of words array with 1, if word is found in current patternfor 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 ])] = 1training.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 model.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模块构建桌面应用程序的结构,然后将捕获用户消息,并再次执行一些预处理,然后再将消息输入到经过训练的模型中。

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

这是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 arraysentence_words = nltk.word_tokenize(sentence)# stemming every word - reducing to base formsentence_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 patternssentence_words = clean_up_sentence(sentence)# bag of words - vocabulary matrixbag = [ 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 positionbag[i] = 1if show_details:print ( "found in bag: %s" % word)return (np.array(bag))
def predict_class (sentence) :# filter below  threshold predictionsp = bag_of_words(sentence, words,show_details= False )res = model.predict(np.array([p]))[ 0 ]ERROR_THRESHOLD = 0.25results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]# sorting strength probabilityresults.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' ])breakreturn 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()

运行聊天机器人

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

python train_chatbot. py

通过源代码探索更多@Python项目

翻译自: https://hackernoon.com/python-chatbot-project-build-your-first-python-project-5mt30mi

chatbot使用

chatbot使用_如何使用Python构建Chatbot项目相关推荐

  1. 如何在验证集加噪声_如何使用Python构建机器学习模型

    如何使用Python构建机器学习模型?在构建机器学习模型时,我们希望将误差保持在尽可能低的水平.对于任何打算学习Python进行大数据分析的人来说,这都是一项关键技能.误差的两个主要来源是偏差和方差. ...

  2. python 3d打印机_如何使用Python构建自己的CNC控制器和3D打印机

    python 3d打印机 by Nikolay Khabarov 通过尼古拉·哈巴罗夫(Nikolay Khabarov) 如何使用Python构建自己的CNC控制器和3D打印机 (How you c ...

  3. pycharm创建python工程_使用Pycharm(Python工具)新建项目及创建Python文件的教程

    创建项目 首先打开Pycharm 勾选I confirm that I have read and accept the terms of this User Agreement 接下来选择Don't ...

  4. react中使用构建缓存_如何使用React构建Chatbot

    react中使用构建缓存 My philosophy is simple. To become good at something, you need to do it a lot. 我的哲学很简单. ...

  5. python使用md5加密_如何使用Python构建加密机器人并将其连接到Facebook Messenger

    python使用md5加密 by Paul Pinard 保罗·皮纳德(Paul Pinard) 认识Sato the Cryptobot,他能够从外部API获取任何加密货币的价格! (Meet Sa ...

  6. python opencv 界面按钮_如何使用Python构建简单的UI?

    借助Streamlit框架,使用用户界面展示Python项目变得前所未有的简单,你可以仅仅使用Python代码来构建基于浏览器的UI.本次演示将为迷宫求解器程序构建UI.StreamlitStream ...

  7. git 创建webpack项目_从 0 开始构建 webpack 项目【Webpack Book 翻译】

    在开始之前,请确保你使用的是 Node 的最新版本.至少是最新的 LTS(长期支持)版本,本书的配置基于 LTS 版本所写,你的终端需要有 node 和 npm 命令,Yarn 也是一个不错的选择,也 ...

  8. python 开源项目 书_十大 Python 机器学习开源项目

    1.Scikit-learn 用于数据挖掘和数据分析的简单而有效的工具,基于NumPy,SciPy和matplotlib,开源,商业可用的BSD许可证. Commits: 21486, Contrib ...

  9. python将姓王的都改成老王_老王Python基础+进阶+项目篇(高清无密)

    老王Python教程 基础篇 基础篇1-福利课python先入为主上 基础篇2-福利课-python先入为主下篇 基础篇3-虚拟机安装xubuntu开发环境 基础篇4-linux基本命令以及开发环境 ...

最新文章

  1. 如何在Django中接收JSON格式的数据
  2. css盒子子类继承父类哪些,css不继承父类的属性有哪些
  3. 拆解 Linux 网络包发送过程
  4. Linux for sougou ping yin (http://pinyin.sogou.com/linux/help.php)
  5. 安卓 linux arm go,go arm、android版本
  6. [数位dp][状压dp] Jzoj P3458 密码
  7. Android 监听软键盘弹出/隐藏,控制软键盘弹出/隐藏
  8. [半监督学习] ReMixMatch: Semi-Supervised Learning with Distribution Alignment and Augmentation Anchoring
  9. Android 一个改善的okHttp封装库
  10. 【OR】S Lemma
  11. java.util.LinkedHashMap cannot be cast to 问题
  12. PMP有效期三年后,还有必要续证吗?详细续证流程PDU积攒方法
  13. IDEA注释模板设置【非常实用】
  14. 永恒python奇美拉_87级稀有双龙头奇美拉 等到熊猫人时再来抓
  15. antd Upload组件上传状态一直处于uploading
  16. java设计九宫格拼图软件哪个好用_九宫格拼图软件下载_抖音很火的九宫格拼图软件app下载_易玩网...
  17. linux setfont设置大小,setfont命令
  18. springBoot项目--平台控制商品订单中各商家打印机打印小票--终极版
  19. 全景虚拟漫游实现(three.js)
  20. 百度2023届暑期实习生面经-产品运营岗

热门文章

  1. python基于pingouin包进行统计分析:使用tost函数执行单样本的双单侧检验(TOST)、以dataframe的形式输出分析结果(包含p值、自由度、bound等)
  2. 大数据基础之常用Linux命令
  3. 网络流量 pv、uv、ip 各代表的含义
  4. BLDC无刷直流电机和PMSM永磁同步电机 基于stm32F1的有传感器和无传感驱动 直流无刷电机有传感器和无传感驱动程序
  5. HTTP基本使用方法
  6. 批量更改Excel数据透视表字段汇总方式
  7. Linux中if语句用法总结
  8. 手撸Spring系列4:IOC/DI 思想(实战篇)
  9. 如何安装emmet?
  10. 使用UC浏览器安卓版访问大多数网站遇到400 bad request错误