学会聊天
这里我基于chatterbot和第三方的语义库,高度定制化地 训练自己的机器人聊天对话系统 1.环境配置:- pip install chatterbot
- pip install chatterbot_corpus
复制代码 2.尝试训练官方的中文数据集并使用
- from chatterbot import ChatBot
- from chatterbot.trainers import ChatterBotCorpusTrainer
- 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')
-
- # Start by training our bot with the ChatterBot corpus data
- trainer = ChatterBotCorpusTrainer(chatbot)
-
- def train():
- trainer.train(
- 'chatterbot.corpus.chinese'
- )
-
- def chat(word = ''):
- word = chatbot.get_response(word)
- return word
-
- def test1():
- train()
- while 1:
- print(chatbot.get_response(input(">")))
-
- test1()
复制代码 若无报错则,可以继续下一步,训练自己的数据集,实现高度定制化。
3.我提供一个数据集:https://download.csdn.net/download/weixin_51331359/76479596
大概长这样:
下载后,在你的项目文件夹中建立一个名为 corpus 的文件夹,把下载好的 corpus.txt 放进去。 进行训练,代码: - from chatterbot import ChatBot
- from chatterbot.trainers import ListTrainer
- from chatterbot.trainers import ChatterBotCorpusTrainer
-
-
- # 构建ChatBot并指定Adapter
- my_bot = ChatBot(
- 'COCO',
- storage_adapter='chatterbot.storage.SQLStorageAdapter',
- logic_adapters=[
- {
- 'import_path': 'chatterbot.logic.BestMatch',
- 'threshold': 0.65,#低于置信度,则默认回答
- 'default_response':'coco没听懂'
- }
- ]
- )
-
-
- def train_myword():
- file = open("./corpus/corpus.txt", 'r', encoding='utf-8')
- corpus = []
- print('开始加载语料!')
- # 导入语料库
- while 1:
- try:
- line = file.readline()
- if not line:
- break
- if line == '===\n':
- continue
- temp = line.strip('\n')
- # print(temp)
- corpus.append(temp)
- except:
- pass
- file.close()
- print('语料加载完毕')
- print('》'*30)
-
- #my_bot = ChatBot("coco")
- #my_bot.set_trainer(ListTrainer)
- trainer = ListTrainer(my_bot)
- print('开始训练!')
- trainer.train(corpus[:10000])
- print('训练完毕!')
-
- def chat1():
- while True:
- print(my_bot.get_response(input("user:")))
-
- def chat_my(word = ''):
- word = my_bot.get_response(word)
- return word
-
- def test1():
- train_myword()
- chat1()
-
- test1()
-
复制代码 训练完毕:
- 开始加载语料!
- 语料加载完毕
- 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》
- 开始训练!
- List Trainer: [####################] 100%
- 训练完毕!
复制代码 这里我只训练语库的前10000条对话,建议不要训练太多的条对话,贪多嚼不烂,就算训练出来了也有很高的回复延迟,甚至直接无法运行回复,非常影响用户体验。
|