Default / 默认 · August 31, 2021

“基于chatterbot的聊天机器人”

Table of Content

ChatterBot.ipynb

chatterbot作为聊天机器人训练一多就性能不行.

挂载google硬盘

In [0]:
## 挂载google硬盘from google.colab import drivedrive.mount('/content/gdrive', force_remount=True)root_dir = "/content/gdrive/My Drive/"base_dir = root_dir + 'fastai-v3/'app_dir = base_dir+"ChatterBot"!mkdir /content/gdrive/My\ Drive/fastai-v3/ChatterBot
 
Mounted at /content/gdrive
In [0]:
 
 

ChatterBot

ChatterBot is a machine learning, conversational dialog engine for creating chat bots https://chatterbot.readthedocs.io

 

# 安装

In [0]:
!pip install chatterbot
 
Requirement already satisfied: chatterbot in /usr/local/lib/python3.6/dist-packages (1.0.4)Requirement already satisfied: chatterbot-corpus<1.3,>=1.2 in /usr/local/lib/python3.6/dist-packages (from chatterbot) (1.2.0)Requirement already satisfied: pymongo<4.0,>=3.3 in /usr/local/lib/python3.6/dist-packages (from chatterbot) (3.7.2)Requirement already satisfied: python-dateutil<2.8,>=2.7 in /usr/local/lib/python3.6/dist-packages (from chatterbot) (2.7.5)Requirement already satisfied: sqlalchemy<1.3,>=1.2 in /usr/local/lib/python3.6/dist-packages (from chatterbot) (1.2.18)Requirement already satisfied: pint>=0.8.1 in /usr/local/lib/python3.6/dist-packages (from chatterbot) (0.9)Requirement already satisfied: nltk<4.0,>=3.2 in /usr/local/lib/python3.6/dist-packages (from chatterbot) (3.2.5)Requirement already satisfied: mathparse<0.2,>=0.1 in /usr/local/lib/python3.6/dist-packages (from chatterbot) (0.1.2)Requirement already satisfied: PyYAML<4.0,>=3.12 in /usr/local/lib/python3.6/dist-packages (from chatterbot-corpus<1.3,>=1.2->chatterbot) (3.13)Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil<2.8,>=2.7->chatterbot) (1.11.0)
 

 测试使用

In [0]:
from chatterbot import ChatBotfrom chatterbot.trainers import ChatterBotCorpusTrainerchatbot = ChatBot('Ron Obvious')# Create a new trainer for the chatbottrainer = ChatterBotCorpusTrainer(chatbot)# Train the chatbot based on the english corpus or chinesetrainer.train("chatterbot.corpus.english")# Get a response to an input statementchatbot.get_response("Hello, how are you today?")
 
[nltk_data] Downloading package averaged_perceptron_tagger to[nltk_data]     /root/nltk_data...[nltk_data]   Package averaged_perceptron_tagger is already up-to-[nltk_data]       date![nltk_data] Downloading package punkt to /root/nltk_data...[nltk_data]   Package punkt is already up-to-date![nltk_data] Downloading package stopwords to /root/nltk_data...[nltk_data]   Package stopwords is already up-to-date!Training ai.yml: [####################] 100%Training computers.yml: [####################] 100%Training conversations.yml: [####################] 100%Training emotion.yml: [####################] 100%Training food.yml: [####################] 100%Training gossip.yml: [####################] 100%Training greetings.yml: [####################] 100%Training health.yml: [####################] 100%Training history.yml: [####################] 100%Training humor.yml: [####################] 100%Training money.yml: [####################] 100%Training movies.yml: [####################] 100%Training politics.yml: [####################] 100%Training psychology.yml: [####################] 100%Training science.yml: [####################] 100%Training sports.yml: [####################] 100%Training trivia.yml: [####################] 100%
Out[0]:
<Statement text:I'm not bragging, I'm just that awesome.>
 

进阶使用

 

Training data

In [0]:
from chatterbot import ChatBotfrom chatterbot.trainers import ChatterBotCorpusTrainerfrom chatterbot.conversation import Statementimport logging# bot = ChatBot('叨叨')# 初始化数据库bot = ChatBot(    '叨叨',#     storage_adapter='chatterbot.storage.MongoDatabaseAdapter',    logic_adapters=[        'chatterbot.logic.BestMatch',        'chatterbot.logic.MathematicalEvaluation',        # 'chatterbot.logic.TimeLogicAdapter'    ],    input_adapter='chatterbot.input.TerminalAdapter',  # 命令行端    output_adapter='chatterbot.output.TerminalAdapter',    storage_adapter="chatterbot.storage.SQLStorageAdapter"   # database_uri='mongodb://localhost:27017/chatterbot-database')# # # Create a new trainer for the chatbot# # 载入基本训练# # Create a new trainer for the chatbot# trainer = ChatterBotCorpusTrainer(bot)# # # Train the chatbot based on the english corpus# # # trainer.train("chatterbot.corpus.chinese")# trainer.train(#     # "chatterbot.corpus.chinese",#     # "./data/greetings_corpus/custom.corpus.json",#     "./Dialog_Corpus/"# )# 对话测试# The following loop will execute each time the user enters input# while True:#     try:#         user_input = input()#         bot_response = bot.get_response(user_input)#         print(bot_response)#     # Press ctrl-c or ctrl-d on the keyboard to exit#     except (KeyboardInterrupt, EOFError, SystemExit):#         break# while True:#     message = input('You: ')#     if message.strip() != 'Bye':#         reply = bot.get_response(message)#         print('Bot: ', reply)#     if message.strip() == 'bye':#         print('Bot : Bye')#         break# 对话训练def get_feedback():    text = input()    if 'y' in text.lower():        return True    elif 'n' in text.lower():        return False    else:        print('是否训练 "Yes(y)" or "No(n)"')        return get_feedback()print('输入要开始的东西......')# The following loop will execute each time the user enters inputwhile True:    try:        input_statement = Statement(text=input('>'))        response = bot.generate_response(            input_statement        )        print('>>>\n 机器人返回: "{}" 是否与:"{}"  相关吗? \n 是否需要训练 "Yes(y)" or "No(n)"'.format(            response.text,            input_statement.text        ))        if get_feedback():            print('请输入正确的')            correct_response = Statement(text=input('>'))            bot.learn_response(correct_response, input_statement)            print('已经修正机器人')            print('————————————————————————')            print('———开始新的训练————————————')            print('————————————————————————')    # Press ctrl-c or ctrl-d on the keyboard to exit    except (KeyboardInterrupt, EOFError, SystemExit):        break
 
[nltk_data] Downloading package averaged_perceptron_tagger to[nltk_data]     /root/nltk_data...[nltk_data]   Package averaged_perceptron_tagger is already up-to-[nltk_data]       date![nltk_data] Downloading package punkt to /root/nltk_data...[nltk_data]   Package punkt is already up-to-date![nltk_data] Downloading package stopwords to /root/nltk_data...[nltk_data]   Package stopwords is already up-to-date!输入要开始的东西......
 
No value for search_text was available on the provided input
 
>>> 机器人返回: "What is AI?" 是否与:"hah"  相关吗?  是否需要训练 "Yes(y)" or "No(n)"是否训练 "Yes(y)" or "No(n)"
 
No value for search_text was available on the provided input
 
>>> 机器人返回: "What is AI?" 是否与:"狗子"  相关吗?  是否需要训练 "Yes(y)" or "No(n)"
 

导出训练数据

In [0]:
# Now we can export the data to a filetrainer.export_for_training( app_dir+'/my_export.json')
%d bloggers like this: