在上一节中,训练了一个最简单的机器人,通过一组简单的对话输入,对机器人进行训练,完成以后进行,就可以跟机器人进行对话了。
这是一个最简单的例子了,简单到只能用来说明问题,我们会想每次都进行语料的准备,语料如果比较全面,一种极端的情况是语料覆盖了方方面面,输入的对话都能在语料中找到相似的语句,通过语句就可以找到最适合的回答。
可以准备非常多的高质量的聊天内容,通过聊天内容可以构建训练的语料。而对于语言来说,还要考虑的一点是语种,中文,英语的语料可分开进行。
ChatterBot
提供了一些简单的聊天语料,在\site-packages\chatterbot_corpus\data
,有一些不同语种的聊天语料。有中文,英文,西班牙文等等,但是这些语料多过于简单,在项目中可以通过各种不同的方式进行补充。
使用ChatterBot加载语料,训练机器人:
#!/usr/bin/python
#coding=utf-8
from chatterbot import ChatBot
import logging
'''
This is an example showing how to train a chat bot using the
ChatterBot Corpus of conversation dialog.
'''
# Enable info level logging
logging.basicConfig(level=logging.INFO)
chatbot = ChatBot(
'Example Bot',
trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
)
# Start by training our bot with the ChatterBot corpus data
chatbot.train(
'chatterbot.corpus.chinese'
)
# Now let's get a response to a greeting
response = chatbot.get_response('最近如何')
print(response)
在chatbot.train中,选择的是chatterbot.corpus.chinese语料,语料进行训练以后,回答’最近如何’的对话,运行的过程:
conversations.yml Training: [####################] 100%
greetings.yml Training: [####################] 100%
trivia.yml Training: [####################] 100%
INFO:chatterbot.adapters:Recieved input statement: 最近如何
INFO:chatterbot.adapters:"最近如何" is a known statement
INFO:chatterbot.adapters:Using "最近如何" as a close match to "嗨,最近如何?"
INFO:chatterbot.adapters:Selecting response from 6 optimal responses.
INFO:chatterbot.response_selection:Selecting first response from list of 6 options.
INFO:chatterbot.adapters:Response selected. Using "挺好"
INFO:chatterbot.adapters:BestMatch selected "挺好" as a response with a confidence of 0.73
INFO:chatterbot.adapters:NoKnowledgeAdapter selected "最近如何" as a response with a confidence of 0
挺好
程序运行的过程,就是上一章分析的过程,找到最相近的"嗨,最近如何?",根据"嗨,最近如何?"的对话进行回复,内容为:挺好。