當機器人訓練師加載了一段數據,它會根據加載的數據構建會話機器人的知識圖譜,過程如下:
1. 訓練師類
-
使用列表數據訓練
chatterbot.trainers.ListTrainer
(storage, ***kwargs*)示例1:
from chatterbot.trainers import ListTrainer
chatterbot = ChatBot("Training Example")
chatterbot.set_trainer(ListTrainer)
chatterbot.train([
"Hi there!",
"Hello",
])
chatterbot.train([
"Greetings!",
"Hello",
])
示例2:
chatterbot.train([
"How are you?",
"I am good.",
"That is good to hear.",
"Thank you",
"You are welcome.",
])
示例1和示例2的區別在於,示例1有兩個入口,而示例2有四個入口,也就是說,訓練完成之后,當對示例1的機器人說『Hi there!』或者『Greetings!』均會返回『hello』,對示例2的機器人說列表中的前四句中的任意一句話,機器人都會返回相應的下一句。
-
使用語料庫數據訓練
chatterbot.trainers.ChatterBotCorpusTrainer
(storage, ***kwargs*)- 訓練ChatterBot內嵌英文語料庫
from chatterbot.trainers import ChatterBotCorpusTrainer
chatterbot = ChatBot("Training Example")
chatterbot.set_trainer(ChatterBotCorpusTrainer)
chatterbot.train(
"chatterbot.corpus.english"
)
- 訓練ChatterBot內嵌部分語料庫
chatterbot.train(
"chatterbot.corpus.english.greetings",
"chatterbot.corpus.english.conversations"
)
- 訓練指定路徑的語料庫文件或者指定路徑文件夾內的語料庫
chatterbot.train(
"./data/greetings_corpus/custom.corpus.json",
"./data/my_corpus/"
)
-
使用Twitter的API接口訓練
chatterbot.trainers.TwitterTrainer
(storage, ***kwargs*)參數:
- random_seed_word - 首次查詢使用的關鍵字,默認:random
- twitter_consumer_key - 用戶KEY
- twitter_consumer_secret - 用戶密鑰
- twitter_access_token_key - 訪問token
- twitter_access_token_secret - 訪問密鑰
示例
# -*- coding: utf-8 -*-
from chatterbot import ChatBot
from settings import TWITTER
import logging
'''
This example demonstrates how you can train your chat bot
using data from Twitter.
To use this example, create a new file called settings.py.
In settings.py define the following:
TWITTER = {
"CONSUMER_KEY": "my-twitter-consumer-key",
"CONSUMER_SECRET": "my-twitter-consumer-secret",
"ACCESS_TOKEN": "my-access-token",
"ACCESS_TOKEN_SECRET": "my-access-token-secret"
}
'''
# Comment out the following line to disable verbose logging
logging.basicConfig(level=logging.INFO)
chatbot = ChatBot(
"TwitterBot",
logic_adapters=[
"chatterbot.logic.BestMatch"
],
input_adapter="chatterbot.input.TerminalAdapter",
output_adapter="chatterbot.output.TerminalAdapter",
database="./twitter-database.db",
twitter_consumer_key=TWITTER["CONSUMER_KEY"],
twitter_consumer_secret=TWITTER["CONSUMER_SECRET"],
twitter_access_token_key=TWITTER["ACCESS_TOKEN"],
twitter_access_token_secret=TWITTER["ACCESS_TOKEN_SECRET"],
trainer="chatterbot.trainers.TwitterTrainer"
)
chatbot.train()
chatbot.logger.info('Trained database generated successfully!')
-
使用Ubuntu對話語料庫訓練
chatterbot.trainers.UbuntuCorpusTrainer
(storage, ***kwargs*)該訓練師類會自動下載、解壓語料庫,如果已經存在下載文件,則不會重新下載,如果存在解壓后的文件,也不會再次進行解壓操作,由於Ubuntu的語料庫文件較大,所以下載、解壓、訓練的過程會花費較長時間。
2. 創建自定義訓練師類
現有的訓練師不能正確識別數據源格式時,需要自己構建訓練師類。自己構建的訓練師類需要繼承 chatterbot.trainers.Trainer
類,並且需要實現train
方法,參數可以自行定義。