用chatterbot从零开始创建一个聊天机器人(一)

简介

  • chatterbot是一个python的第三方库,可以构建一个任何语言的问答机器人。

安装

pip install chatterbot
pip install chatterbot-corpus

原理

  • chatterbot是以搜索匹配的方式来找寻训练库中最接近的回答;

  • 它不会进行分词,因此支持任何语言的训练;

  • 由于它会全库扫描一遍以寻求最佳答案,训练库越多他的效率就越慢,只适合单一领域的简单应答;

  • 训练库会保留每一次的输入和回答记录,因此可以在使用的过程中进行学习。

训练

  • ChatterBot包含一些工具,可以帮助简化训练聊天机器人实例的过程。

  • ChatterBot的训练过程包括将示例对话框加载到聊天机器人的数据库中。

  • 这将创建或构建表示已知语句和响应集的图形数据结构。

  • 当向聊天机器人训练器提供数据集时,它将在聊天机器人的知识图中创建必要的条目,以便正确表示语句输入和响应。

  • 通过列表数据进行训练

from chatbot import chatbot
from chatterbot.trainers import ListTrainer

chatbot = ChatBot('Training Example')
trainer = ListTrainer(chatbot)

trainer.train([
    "Hi there!",
    "Hello",
])

trainer.train([
    "Greetings!",
    "Hello",
])
  • 通过语料库进行训练

from chatbot import chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Training Example')
trainer = ChatterBotCorpusTrainer(chatbot)

trainer.train(
    "chatterbot.corpus.english"
)
  • 通过文件进行训练

from chatbot import chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Training Example')
trainer = ChatterBotCorpusTrainer(chatbot)

trainer.train(
    "./data/greetings_corpus/custom.corpus.json",
    "./data/my_corpus/"
)

组成

1、预处理:

  • 删除任何连续的空白字符。

chatterbot.preprocessors.clean_whitespace(statement)
  • 去除html标签

chatterbot.preprocessors.unescape_html(statement)
  • 将unicode字符转换为的ASCII

chatterbot.preprocessors.convert_to_ascii(statement)

2、逻辑适配器

  • Best Match Adapter--最佳匹配适配器:
    最佳匹配适配器使用一个函数来将输入语句与已知语句进行比较。一旦找到与输入语句最接近的匹配,它就使用另一个函数来选择对该语句的已知响应之一。

chatbot = ChatBot(
    "My ChatterBot",
    logic_adapters=[
        {
            "import_path": "chatterbot.logic.BestMatch",
            "statement_comparison_function": chatterbot.comparisons.levenshtein_distance,
            "response_selection_method": chatterbot.response_selection.get_first_response
        }
    ]
)
  • Time Logic Adapter--时间逻辑适配器:
    没啥用,就只能返回当前时间

User: What time is it?
Bot: The current time is 4:45PM.
  • Mathematical Evaluation Adapter--数学评价适配器:
    解析输入,以确定用户是否在提出需要进行数学运算的问题。如果是,则从输入中提取方程并返回计算结果。简单来说,就是实现计算器的功能。

User: What is four plus four?
Bot: (4 + 4) = 8
  • Specific Response Adapter--特定响应适配器:
    如果聊天机器人接收到的输入与为该适配器指定的输入文本匹配,则将返回指定的响应。

from chatterbot import ChatBot

# Create a new instance of a ChatBot
bot = ChatBot(
    'Exact Response Example Bot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.BestMatch'
        },
        {
            'import_path': 'chatterbot.logic.SpecificResponseAdapter',
            'input_text': 'Help me!',
            'output_text': 'Ok, here is a link: http://chatterbot.rtfd.org'
        }
    ]
)

# Get a response given the specific input
response = bot.get_response('Help me!')
print(response)

3、存储适配器

  • SQL Storage Adapter--SQL存储适配器:
    支持的任何数据库中存储会话数据。
    所有参数都是可选的,默认使用sqlite数据库。
    它将检查是否有表,如果没有,它将尝试创建所需的表。

from chatterbot import ChatBot

# Uncomment the following lines to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)

# Create a new instance of a ChatBot
bot = ChatBot(
    'SQLMemoryTerminal',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    database_uri=None,
    logic_adapters=[
        'chatterbot.logic.MathematicalEvaluation',
        'chatterbot.logic.TimeLogicAdapter',
        'chatterbot.logic.BestMatch'
    ]
)

# Get a few responses from the bot

bot.get_response('What time is it?')

bot.get_response('What is 7 plus 7?')
  • MongoDB Storage Adapter--MongoDB存储适配器:
    允许ChatterBot在MongoDB数据库中存储语句的接口。

from chatterbot import ChatBot

# Uncomment the following lines to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)

# Create a new ChatBot instance
bot = ChatBot(
    'Terminal',
    storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
    logic_adapters=[
        'chatterbot.logic.BestMatch'
    ],
    database_uri='mongodb://localhost:27017/chatterbot-database'
)

print('Type something to begin...')

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

4、过滤器

  • 过滤器是创建可以传递到ChatterBot的存储适配器的查询的有效方法。过滤器将减少聊天机器人在选择响应时必须处理的语句数量。

chatbot = ChatBot(
    "My ChatterBot",
    filters=[filters.get_recent_repeated_responses]
)

常用配置

  • read_only=True:禁用学习它收到的每个新输入语句,默认会自动学习。

  • get_default_response():当逻辑适配器无法生成任何其他有意义的响应时,将调用此方法。

  • maximum_similarity_threshold:可以设置最大置信度,达到该置信度将不再匹配其他内容,默认0.95

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值