美文网首页AI算法工程师RasaNLP程序员
基于rasa的对话系统搭建(上)

基于rasa的对话系统搭建(上)

作者: zqh_zy | 来源:发表于2018-01-12 13:12 被阅读4063次

    文章介绍使用rasa nlu和 rasa core 实现一个电信领域对话系统demo,实现简单的业务查询办理功能,更完善的实现需要进一步数据的收集。demo基于玩具数据集,可以达到下面的效果:

    Bot loaded. Type a message and press enter : 
    YOU:你是谁
    BOT:您好!,我是机器人小热,很高兴为您服务。
    YOU:我想看一下消费情况
    BOT:您想查询哪个月的消费?
    YOU:十月份的
    BOT:好,请稍等
    BOT:您好,您十月份共消费二十八元。
    YOU:好谢谢
    BOT:您开心我就开心
    BOT:您还想干什么
    YOU:没什么了
    BOT:Bye, 下次再见
    

    用Rasa_NLU构建自己的中文NLU系统

    系统demo 的数据和代码路径:
    https://github.com/zqhZY/rasa_chatbot

    项目依赖安装(包括rasa nlu 和 rasa core)参考相应路径:
    https://github.com/zqhZY/rasa_chatbot/blob/master/INSTALL.md

    关于rasa nlu的使用方法,可以参考:
    https://github.com/RasaHQ/rasa_nlu
    http://www.crownpku.com/2017/07/27/用Rasa_NLU构建自己的中文NLU系统.html

    确定意图和实体类别

    根据业务查询和办理的场景,首先需要确定意图和实体的类别,这里系统包含如下意图和实体类型:

    intents:
    • greet
    • confirm # 确认
    • goodbye
    • thanks
    • inform_item # 告知业务类型
    • inform_package # 告知套餐类型
    • inform_time # 告知时间
    • request_management # 办理请求
    • request_search # 查询请求
    • deny # 否定
    • inform_current_phone # 告知本机号码
    • inform_other_phone # 告知其他号码
    entities:
    • item # 业务类型
    • time # 时间
    • phone_number # 电话号码
    • price # 价格

    数据准备

    通常项目刚开始,往往伴随着冷启动的问题。没有数据的情况下可以根据实际业务场景自行标注数据并结合规则方式先实现第一版本,线上收集真实数据(如果有机会上线的话-),并反过来迭代模型。 这里使用的训练数据为结合实际场景的自造数据,并转换为rasa nlu训练数据的格式,供学习使用。

    数据格式如下:

    {
      "rasa_nlu_data": {
        "common_examples": [
          {
            "text": "帮我查一下我的流量这里还有多少",
            "intent": "request_search",
            "entities": [
              {
                "start": 7,
                "end": 9,
                "value": "流量",
                "entity": "item"
              }
            ]
          },
          ...
          ...
          {
            "text": "给我办一个三十的新流量业务",
            "intent": "request_management",
            "entities": [
              {
                "start": 10,
                "end": 12,
                "value": "流量",
                "entity": "item"
              },
              {
                "start": 5,
                "end": 7,
                "value": "三十",
                "entity": "price"
              }
            ]
          },
          ...
          ...
        ],
        "regex_features": [],
        "entity_synonyms": [{
            "value": "消费",
            "synonyms": ["话费"]
          }]
      }
    }
    

    训练自然语言理解模型

    这里使用rasa nlu 的pipeline 为 MITIE+Jieba+sklearn, rasa nlu 的配置文件为:

    {
      "name": "rasa_nlu",
      "project": "ivr",
      "fixed_model_name": "demo",
      "pipeline": ["nlp_mitie",
            "tokenizer_jieba",
            "ner_mitie",
            "ner_synonyms",
            "intent_entity_featurizer_regex",
            "intent_featurizer_mitie",
            "intent_classifier_sklearn"],
      "language": "zh",
      "mitie_file": "data/total_word_feature_extractor.dat",
      "path" : "models",
      "data" : "data/mobile_nlu_data.json"
    }
    
    MITIE模型训练

    由于使用了mitie 所以需要事先准备相应的词特征向量(total_word_feature_extractor.dat),类似训练word2vec,
    方法如下:

    把所有分好词的语料文件放在同一个文件路径下。接下来我们要训练MITIE模型。

    首先将MITIE clone下来:

    $ git clone https://github.com/mit-nlp/MITIE.git
    

    我们要使用的只是MITIE其中wordrep这一个工具。我们先build它。

    $ cd MITIE/tools/wordrep
    $ mkdir build
    $ cd build
    $ cmake ..
    $ cmake --build . --config Release
    

    然后训练模型,得到total_word_feature_extractor.dat。注意这一步训练会耗费几十GB的内存,大概需要两到三天的时间。

    $ ./wordrep -e /path/to/your/folder_of_cutted_text_files
    

    项目链接里包含了用真实电信业务数据训练的total_word_feature_extractor.dat,也可以使用wiki百科训练的相应模型。

    链接:http://pan.baidu.com/s/1micEF0G 密码:opli
    
    训练rasa nlu 模型

    使用rasa nlu 的终端接口训练模型:

    python -m rasa_nlu.train -c mobile_nlu_model_config.json
    

    也可以使用bot.py 里的Python 接口:

    def train_nlu():
        from rasa_nlu.converters import load_data
        from rasa_nlu.config import RasaNLUConfig
        from rasa_nlu.model import Trainer
    
        training_data = load_data("data/mobile_nlu_data.json")
        trainer = Trainer(RasaNLUConfig("mobile_nlu_model_config.json"))
        trainer.train(training_data)
        model_directory = trainer.persist("models/", project_name="ivr", fixed_model_name="demo")
    
        return model_directory
    

    运行相应命令:

    python bot.py train-nlu
    

    两种方式都会在项目根目录models下生成模型:

    models/
    └── ivr
        ├── demo
           ├── entity_extractor.dat
           ├── entity_synonyms.json
           ├── intent_classifier.pkl
           ├── metadata.json
           └── training_data.json
    
    
    rasa nlu 测试

    训练好模型后可以使用http接口进行测试,启动项目的httpserver,服务会load模型,并接受http请求,对新文本进行预测:

    $ python httpserver.py 
    2018-01-12 11:48:23+0800 [-] Log opened.
    2018-01-12 11:48:23+0800 [-] Site starting on 1235
    2018-01-12 11:48:23+0800 [-] Starting factory <twisted.web.server.Site object at 0x7f090a9d49b0>
    
    

    向服务发送http请求测试结果:

    $ curl -XPOST 127.0.0.1:1235/parse -d '{"text":"给我查一下我上个月的流量"}'
    {"text": "给我查一下我上个月的流量", "intent": "request_search", "entities": {"time": "上个月", "item": "流量"}}
    

    同时httpserver 后台打印完整log,包括每个intent的预测confidence。

    小结

    篇幅原因,这里只介绍训练rasa nlu的流程,更多rasa nlu的用法可以到官方文档了解。下篇文章介绍利用这里训练的nlu模型,使用rasa core 的online learning (或强化学习)方式进行对话管理模型的训练和测试。

    原创文章,转载注明出处
    更多关注公众号:

    wechat

    相关文章

      网友评论

      • 3843419ddb09:哦 我并没有训练 nlu 没跑下来
      • 3843419ddb09:请问 httpsever.py 是怎样写成的 我看 chat_detection_model = "models/ivr/demo_chat_detection" chat_detection_config = "chat_detection/mobile_chat_detection_model_config.json"找不到上述的两个文件 我实现了本地对话 如果想实现http的请求参照什么写
      • 羁绊_455a:cmake.. 用完以后报 C 和CXX的错怎么办
      • ciel:你好,那个链接失效了能去哪儿下载啊?
        ciel:@zqh_zy 谢谢:heart_eyes:
        zqh_zy:https://github.com/zqhZY/_rasa_chatbot 未失效
      • 优蜜:大神,你这个如果在win10下,如何配置?最后的接口调用怎样调用?
      • 努力努力再努力s_60a5:请教一下,python -m rasa_nlu.train --config mobile_nlu_model_config.json --data data/mobile_nlu_data.json --path models命令训练完rasa nlu之后只出现
        \models\default\model_20180718-165716\entity_extractor.dat这一个文件是怎么回事呢?
        c51b2c80fd64:应该跟你配置文件的pipeline有关,可以加个联系方式吗,我的qq1073521013,共同学习共同进步!
      • 8eca3d96e923:请问测试rasa_nlu时出现:
        <span>builtins.UnicodeDecodeError</span>: <span>'utf-8' codec can't decode byte 0xb8 in position 7: invalid start byte</span>
        问题,并且运行时还返回了一堆标签是怎么回事啊?
      • 8eca3d96e923:请问
        $ curl -XPOST 127.0.0.1:1235/parse -d '{"text":"给我查一下我上个月的流量"}'
        {"text": "给我查一下我上个月的流量", "intent": "request_search", "entities": {"time": "上个月", "item": "流量"}}这句话在windows上怎么测试?
        zqh_zy:@无情Array 搜索windows往本机1235端口发json请求的方法
      • 8eca3d96e923:请教一下,训练rasa_nlu模型时,用python bot.py train_nlu时出现如下错误是怎么回事呢?
        Traceback (most recent call last):
        File "C:\Users\Cf\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_nlu\model.py", line 66, in load
        data = utils.read_json_file(metadata_file)
        File "C:\Users\Cf\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_nlu\utils\__init__.py", line 208, in read_json_file
        content = read_file(filename)
        File "C:\Users\Cf\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_nlu\utils\__init__.py", line 202, in read_file
        with io.open(filename, encoding=encoding) as f:
        FileNotFoundError: [Errno 2] No such file or directory: 'models/ivr/demo\\metadata.json'

        During handling of the above exception, another exception occurred:

        Traceback (most recent call last):
        File "bot.py", line 120, in <module>
        interpreter=RasaNLUInterpreter("models/ivr/demo"),
        File "C:\Users\Cf\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_core\interpreter.py", line 221, in __init__
        self._load_interpreter()
        File "C:\Users\Cf\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_core\interpreter.py", line 237, in _load_interpreter
        self.interpreter = Interpreter.load(self.model_directory)
        File "C:\Users\Cf\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_nlu\model.py", line 270, in load
        model_metadata = Metadata.load(model_dir)
        File "C:\Users\Cf\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_nlu\model.py", line 71, in load
        "from '{}'. {}".format(abspath, e))
        rasa_nlu.model.InvalidProjectError: Failed to load model metadata from 'D:\基于rasa的对话系统3\_rasa_chatbot-master\models\ivr\demo\metadata.json'. [Errno 2] No such file or directory: 'models/ivr/demo\\metadata.json'
        8eca3d96e923:@zqh_zy 你好,请问“项目根目录models下生成模型:”中的models文件夹以及它的子文件夹是代码自动生成的吗?
        zqh_zy:@无情Array 看最新的readme.md, rasa版本更新的原因,另外对话管理我这还没更新
        zqh_zy:@无情Array python -m rasa_nlu.train --config mobile_nlu_model_config.json --data data/mobile_nlu_data.json --path models
      • c9869868e335:张哥,您好,能请教一下你的运行环境么,python版本是多少?mitie版本是多少,rasa_core版本是多少?rasa_nlu版本是多少?linux版本是多少?我最近在向您学习,研究rasa,想搭建一套和您一样的测试环境。
      • 328a515db2e8:您好,我在照着《用Rasa_NLU构建自己的中文NLU系统》时,
        $ python -m rasa_nlu.train -c config_jieba_mitie_sklearn.json
        usage: train.py [-h] [-o PATH] (-d DATA | -u URL) -c CONFIG [-t NUM_THREADS]
        [--project PROJECT] [--fixed_model_name FIXED_MODEL_NAME]
        [--storage STORAGE] [--debug] [-v]
        train.py: error: one of the arguments -d/--data -u/--url is required
        然后:
        $ python -m rasa_nlu.train -c /config_jieba_mitie_sklearn.json -d demo-rasa_zh.json
        又报错:
        /rasa_nlu/config.py", line 146, in <listcomp> return [c.get("name") for c in self.pipeline]
        AttributeError: 'str' object has no attribute 'get'
        请问这是怎么回事?pipeline并没有改动,谢谢
        c9869868e335:使用最新的rasa_core 0.9.0 + rasa_nlu 0.12.3.我也碰到这个问题,新版本里面self.pipeline是数组,内容是组件的class名称,这个时候不需要再c.get("name") 直接使用c就可以了。但是后面会报其他错误。应该都是版本更新惹的祸,还需要张哥看看。
        328a515db2e8:@zqh_zy 好的,谢谢
        zqh_zy:@走在路上_15a7 这块好像是rasa的版本有更新,我回头再整理一下:smile:
      • c0657cdd4b99:能否分享一下源代码,非常感谢dhnl2016@163.com
      • 4e4a7d8448f5:您好,请问能分享一下源码么,谢谢。
        e35b92cca32a:您好,github上的项目已删除。作者有将源码分享给您了是吗?麻烦把完整版的分享一下,谢谢。zuyinup@163.com:smile:
        4e4a7d8448f5:@zqh_zy 好的,太感谢了。:smile:
        zqh_zy:@小冰棍123 给github里的邮箱发个邮件就好
      • 黄晶_2aba:你好,有几点我没有搞明白
        1.:data/total_word_feature_extractor.dat 里面是词向量 不谈解码 数据具体格式是什么?是词与词向量的映射么? 比如 火箭 000010 这种对应关系么 还是会有其他信息?
        2:mobile_nlu_model_config.json 里面包含的内容很多 比如里面有个data文件 会和训练完 model目录下生成那些文件里training_data.json很像 几乎一样 我没明白这些文件的意思 能否简单解释下 不同文件是做什么用途的么 谢谢
      • 庞贝船长:真是太棒了,最近也在为移动做这一块。
      • 2c646167632d:请问rasaCore可以实现远程的调用吗?在服务器上装上后,客户端可以直接调用与机器人对话而不需要任何配置吗
        zqh_zy:@Oo悠oO 远程调用可能需要http接口,这块我没有测试过,你看下这里是不是你要的远程调用https://core.rasa.ai/http.html
      • f6b3c53c6415:您好,谢谢您的记录,收获满满。我在github上down下您程序,您在安装依赖时,pip install git+https://github.com/mit-nlp/MITIE.git 这一步时,报错:是一个UnicodeDecodeError错误。我看您在文中写:
        MITIE$ cd MITIE/tools/wordrep
        $ mkdir build....
        是先bulid再pip install吗?
        我并没有训练语料,想先直接拿您已经训练好的搭建起来。
        谢谢您。。
        zqh_zy:@笨笨酱3 你好,这个问题我没有遇到过,看log只能想到是python版本的问题。:smile:不过建议有条件的话可以在linux下搞,很多问题可以避免,各种操作也更加方便。
        f6b3c53c6415:@zqh_zy 嗯,您的意思是,我不需要bulid,只需要运行一下pip install git+https://github.com/mit-nlp/MITIE.git 这句话是吗?还是这句话也不需要运行呢? 我是py3.6.3..现在问题卡在这~~:sob: 报错信息如下:
        E:\bot_create\Scripts>pip install git+https://github.com/mit-nlp/MITIE.git
        Collecting git+https://github.com/mit-nlp/MITIE.git
        Cloning https://github.com/mit-nlp/MITIE.git to c:\users\min_z\appdata\local\temp\pip-82ktbuce-build
        Installing collected packages: mitie
        Running setup.py install for mitie ... error
        Exception:
        Traceback (most recent call last):
        File "e:\bot_create\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str
        return s.decode(sys.__stdout__.encoding)
        UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 24: invalid continuation byte

        During handling of the above exception, another exception occurred:

        Traceback (most recent call last):
        File "e:\bot_create\lib\site-packages\pip\basecommand.py", line 215, in main
        status = self.run(options, args)
        File "e:\bot_create\lib\site-packages\pip\commands\install.py", line 342, in run
        prefix=options.prefix_path,
        File "e:\bot_create\lib\site-packages\pip\req\req_set.py", line 784, in install
        **kwargs
        File "e:\bot_create\lib\site-packages\pip\req\req_install.py", line 878, in install
        spinner=spinner,
        File "e:\bot_create\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess
        line = console_to_str(proc.stdout.readline())
        File "e:\bot_create\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str
        return s.decode('utf_8')
        UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 24: invalid continuation byte
        ....
        还是不用git方式,可以把项目load下来,直接运行MITIE的setup.py吗?但也报错。。···
        不知道,楼主是否有遇到过这样的问题。
        谢谢。
        zqh_zy:@笨笨酱3 如果不想自己训练mitie不需要build,你的问题应该是其他问题。会不会是python版本,您的是py3吗

      本文标题:基于rasa的对话系统搭建(上)

      本文链接:https://www.haomeiwen.com/subject/tscfoxtx.html