搬山行者

无志愁压头,有志能搬山

业余程序员的学习笔记~


使用Rasa构建对话助理-管道组件

目录

管道组件

组件组成了NLU管道,并按顺序工作,将用户输入处理为结构化输出。 有用于实体提取、意图分类、响应选择、预处理等的组件。

语言模型(Language Models)

如果想在管道中使用预训练的词向量,以下组件将加载所需的预训练模型。

MitieNLP(MIT Information Extraction)

  • 简述: MITIE初始化器
  • 输出: 无
  • 要求:无
  • 说明: 初始化MITIE结构。 每个MITIE组件都依赖于此,因此这应该放在使用任何MITIE组件的每个管道的开头。
  • 配置: MITIE库需要一个语言模型文件,必须在配置中指定:
pipeline:
- name: "MitieNLP" # language model to load
  model: "data/total_word_feature_extractor.dat"

还可以使用MITIE从语言语料库中预训练自己的单词向量。为此:

  1. 获取一个干净的语言语料库(维基百科转储可用)作为一组文本文件。

  2. 在您的语料库上构建并运行MITIE Wordrep工具。这可能需要几个小时/几天,具体取决于数据集和工作站。需要128GB的RAM来运行wordrep

  3. 将新的total_word_feature_extractor.dat的路径设置为配置文件中MitieNLP组件的模型参数。

有关如何训练MITIE单词向量的完整示例,请查看Rasa NLU构建自己的中文NLU系统

SpacyNLP

  • 简述: spaCy语言初始化器
  • 输出: 无
  • 要求:无
  • 说明: 初始化spaCy结构。 每个spaCy组件都依赖于此,因此应该放在使用任何spaCy部件的每个管道的开头

  • 配置: 需要指定要使用的语言模型.
    该名称将传递给spacy.load(name)
    可在spaCy文档中找到有关可用模型的更多信息。
pipeline:
- name: "SpacyNLP"
  # language model to load
  model: "en_core_web_md"

  # when retrieving word vectors, this will decide if the casing
  # of the word is relevant. E.g. `hello` and `Hello` will
  # retrieve the same vector, if set to `False`. For some
  # applications and models it makes sense to differentiate
  # between these two words, therefore setting this to `True`.
  case_sensitive: False

除了SpaCy的预训练语言模型外,还可以使用此组件附加自己训练过的SpaCy模型。

分词器

分词器将文本拆分为标记(tokens)。 如果想将意图拆分为多个标签,例如用于预测多个意图或建模分层意图结构,请在任何标记器上使用以下标志:

  • intent_tokenization_flag指示是否对意图标签进行标记。将其设置为True,以便对意图标签进行标记。

  • intent_split_symbol设置分隔符字符串以分割intent标签,默认值为下划线(_)。

WhitespaceTokenizer

  • 简述: 使用空格作为分隔符的分词器
  • 输出: 用户消息、响应(如果存在)和意图(如果指定)的令牌
  • 要求:无
  • 说明:为每个空格分隔的字符序列创建一个标记。
  • 配置: ```yaml pipeline:
  • name: “WhitespaceTokenizer” # Flag to check whether to split intents “intent_tokenization_flag”: False # Symbol on which intent should be split “intent_split_symbol”: “_” # Regular expression to detect tokens “token_pattern”: None ```

JiebaTokenizer

  • 简述: 使用Jieba进行中文标记
  • 输出: 用户消息、响应(如果存在)和意图(如果指定)的令牌
  • 要求:无
  • 说明:使用专门用于中文的Jieba标记器创建标记。它只适用于中文。
  • 配置: 通过dictionary_path指定文件的目录路径,可以自动加载用户的自定义词典文件。 如果dictionary_path为None(默认值),则不会使用自定义词典。
pipeline:
- name: "JiebaTokenizer"
  dictionary_path: "path/to/custom/dictionary/dir" # Flag to check whether to split intents
  "intent_tokenization_flag": False # Symbol on which intent should be split
  "intent_split_symbol": "_" # Regular expression to detect tokens
  "token_pattern": None

MitieTokenizer

  • 简述: 使用MITIE的分词器
  • 输出: 用户消息、响应(如果存在)和意图(如果指定)的令牌
  • 要求:MitieNLP
  • 说明:使用MITIE分词器创建标记。
  • 配置: ```yaml pipeline:
  • name: “MitieTokenizer” # Flag to check whether to split intents “intent_tokenization_flag”: False # Symbol on which intent should be split “intent_split_symbol”: “_” # Regular expression to detect tokens “token_pattern”: None ```

SpacyTokenizer

  • 简述: 使用Spacy的分词器
  • 输出: 用户消息、响应(如果存在)和意图(如果指定)的令牌
  • 要求:SpacyNLP
  • 说明:使用Spacy分词器创建标记。
  • 配置: ```yaml pipeline:
  • name: “SpacyTokenizer” # Flag to check whether to split intents “intent_tokenization_flag”: False # Symbol on which intent should be split “intent_split_symbol”: “_” # Regular expression to detect tokens “token_pattern”: None ```

特征提取器(Featurizers)

文本特征分为两类:稀疏特征和密集特征。 稀疏提取器是返回具有大量缺失值(如零)的特征向量的特征提取器。 由于这些特征向量通常会占用大量内存,我们将其存储为稀疏特征。 稀疏特征仅存储非零的值及其在向量中的位置。

因此节省了大量内存,并能够在更大的数据集上进行训练。

所有特征提取器都可以返回两种不同的特征:序列特征和句子特征。

序列特征是一个大小矩阵(标记数量 x 特征维度)。
该矩阵包含序列中每个标记的特征向量。
这使得能够训练序列模型。
句子特征由大小矩阵(1 x 特征维度)表示。
它包含完整话语的特征向量。
句子特征可以在任何词袋模型中使用。
因此,相应的分类器可以决定使用哪种特征。 注意:序列和句子特征的特征维度不必相同。

MitieFeaturizer

  • 简述: 使用MITIE特征提取器创建用户消息和响应(如果指定)的矢量表示。
  • 输出: 用户消息和响应的密集特性
  • 要求:MitieNLP
  • 类型: 密集型
  • 说明:使用MITIE特征提取器创建实体提取、意图分类和响应分类的特征。
  • 配置: ```yaml pipeline:
  • name: “MitieFeaturizer” # Specify what pooling operation should be used to calculate the vector of the complete utterance. Available options: ‘mean’ and ‘max’. “pooling”: “mean” ```

SpacyFeaturizer

  • 简述: 使用Spacy特征提取器创建用户消息和响应(如果指定)的矢量表示。
  • 输出: 用户消息和响应的密集特性
  • 要求:SpacyNLP
  • 类型: 密集型
  • 说明:使用spaCy特征提取器创建实体提取、意图分类和响应分类的特征。
  • 配置: ```yaml pipeline:
  • name: “SpacyFeaturizer” # Specify what pooling operation should be used to calculate the vector of the complete utterance. Available options: ‘mean’ and ‘max’. “pooling”: “mean” ```

ConveRTFeaturizer

  • 简述: 使用ConveRT模型创建用户消息和响应(如果指定)的矢量表示。
  • 输出: 用户消息和响应的密集特性
  • 要求:SpacyNLP
  • 类型: 密集型
  • 说明:创建用于实体提取、意图分类和响应选择的特征。 它使用默认签名来计算输入文本的向量表示。 只支持英语。
  • 配置: ```yaml pipeline:
  • name: “ConveRTFeaturizer” # Remote URL/Local directory of model files(Required) “model_url”: None ```

LanguageModelFeaturizer

  • 简述: 使用预训练的语言模型创建用户消息和响应(如果指定)的向量表示。
  • 输出: 用户消息和响应的密集特性
  • 要求:SpacyNLP
  • 类型: 密集型
  • 说明:创建用于实体提取、意图分类和响应选择的特征。使用预训练的语言模型来计算输入文本的向量表示. 确保使用的语言模型是在与训练数据相同的语言语料库上预先训练的。
  • 配置: 在此组件之前包含一个Tokenizer组件。 应该通过参数model_name指定要加载的语言模型。 请参阅下表了解当前支持的语言模型。 要加载的权重可以通过附加参数model_weights指定。
    如果留空,则使用表中列出的默认模型权重。
    +----------------+--------------+-------------------------+
    | Language Model | Parameter    | Default value for       |
    |                | "model_name" | "model_weights"         |
    +----------------+--------------+-------------------------+
    | BERT           | bert         | rasa/LaBSE              |
    +----------------+--------------+-------------------------+
    | GPT            | gpt          | openai-gpt              |
    +----------------+--------------+-------------------------+
    | GPT-2          | gpt2         | gpt2                    |
    +----------------+--------------+-------------------------+
    | XLNet          | xlnet        | xlnet-base-cased        |
    +----------------+--------------+-------------------------+
    | DistilBERT     | distilbert   | distilbert-base-uncased |
    +----------------+--------------+-------------------------+
    | RoBERTa        | roberta      | roberta-base            |
    +----------------+--------------+-------------------------+
    | camemBERT      | camembert    | camembert-base          |
    +----------------+--------------+-------------------------+
    

除了默认的预训练模型权重外,如果满足以下条件,可以从HuggingFace模型中使用其他模型(提到的文件可以在模型网站的“文件和版本”部分找到):

  • 模型架构是支持的语言模型之一(检查config.json中的model_type是否列在表的model_name列中)
  • 模型具有预训练的Tensorflow权重(检查文件tf_model.h5是否存在)
  • 该模型使用默认的tokenizer(config.json不应包含自定义tokenizer_class设置)

以下配置使用rasa/LaBSE权重加载语言模型BERT,可以在此处找到:

pipeline:
  - name: LanguageModelFeaturizer # Name of the language model to use
    model_name: "bert"
    # Pre-Trained weights to be loaded
    model_weights: "rasa/LaBSE"

    # An optional path to a directory from which
    # to load pre-trained model weights.
    # If the requested model is not found in the
    # directory, it will be downloaded and
    # cached in this directory for future use.
    # The default value of `cache_dir` can be
    # set using the environment variable
    # `TRANSFORMERS_CACHE`, as per the
    # Transformers library.
    cache_dir: null

RegexFeaturizer

  • 简述: 使用正则表达式创建用户消息的向量表示。
  • 输出: 用户消息和标记模式的稀疏特性
  • 要求:tokens
  • 类型: 稀疏型
  • 说明:创建用于实体提取和意图分类的特征。 在训练过程中,RegexFeatureizer会创建一个以训练数据格式定义的正则表达式列表。 对于每个正则表达式,将设置一个特性,标记此表达式是否在用户消息中找到。
    所有特征稍后都将被输入到意图分类器/实体提取器中,以简化分类(假设分类器在训练阶段已经学习到,这组特征表示某个意图/实体)。 用于实体提取的正则表达式功能目前仅受CRFEntityExtractor和DIETClassifier组件的支持。

  • 配置: 通过添加case_sensitive:False选项使featizer不区分大小写,默认值为case_sensitive:True。

为了正确处理不使用空格进行单词分隔的中文等语言,用户需要添加use_word_boundaries:False选项,默认值为use_word_boundaries:True。

pipeline:
- name: "RegexFeaturizer"
  # Text will be processed with case sensitive as default
  "case_sensitive": True
  # use match word boundaries for lookup table
  "use_word_boundaries": True

为了确保sparse_feature在增量训练期间具有固定大小,应配置该组件以考虑将来可能添加到训练数据中的其他模式。 为此,在从头开始训练基础模型时配置number_additional_patterns参数:

pipeline:
- name: RegexFeaturizer
  number_additional_patterns: 10

如果用户没有配置,该组件将使用训练数据中当前存在的模式数量的两倍(包括查找表和正则表达式模式)作为number_additional_patterns的默认值。

为了避免在增量训练期间过于频繁地用完新模式的额外插槽,该数字保持在最小值10。

一旦组件用完了额外的pattern槽,新的pattern就会被丢弃,在特征化过程中不会被考虑。此时,建议从头开始重新训练新模型。

CountVectorsFeaturizer

  • 简述: 创建用户消息、意图和响应的词袋表示。
  • 输出: 用户消息和标记模式的稀疏特性
  • 要求:tokens
  • 类型: 稀疏型
  • 说明:创建用于意图分类和响应选择的特征。 使用sklearn的CountVectorizer创建用户消息、意图和响应的词袋表示。 所有仅由数字组成的令牌(例如123和99,但不是a123d)将被分配给同一特征。
  • 配置: 由于训练是在有限的词汇数据上进行的,因此无法保证在预测过程中算法不会遇到未知单词。为了教算法如何处理未知单词,训练数据中的一些单词可以用通用单词OOV_token替换。在这种情况下,在预测过程中,所有未知单词都将被视为这个通用单词OOV_token。 例如,可以在包含不同数量的OOV_token消息的训练数据中创建范围外的单独意图,也可以创建一些额外的通用单词。然后,算法可能会将包含未知单词的消息分类为超出范围的意图。

可以设置OOV_token或列表OOV_words:

  • OOV_token为未知的单词设置关键字; 如果训练数据在某些消息中包含OOV_token作为单词,则在预测期间,训练期间未看到的单词将被提供的OOV_token替换;如果OOV_token=None(默认行为),则在预测时间内将忽略训练期间未看到的单词;

  • OOV_words设置在训练过程中被视为OOV_token的单词列表;如果已知应被视为超出词汇表的单词列表,则可以将其设置为OOV_words,而不是在训练数据中手动更改或使用自定义预处理器。

这个特征提取器通过计数单词来创建一个单词袋表示,因此句子中OOV_token的数量可能很重要。

如果想在用户消息和意图之间共享词汇表,需要将选项use_shared_vocab设置为True。在这种情况下,将构建意图中的令牌和用户消息之间的通用词汇集。

pipeline:
- name: "CountVectorsFeaturizer"
  # Analyzer to use, either 'word', 'char', or 'char_wb'
  "analyzer": "word"
  # Set the lower and upper boundaries for the n-grams
  "min_ngram": 1
  "max_ngram": 1
  # Set the out-of-vocabulary token
  "OOV_token": "_oov_"
  # Whether to use a shared vocab
  "use_shared_vocab": False

为了确保sparse_feature在增量训练期间具有固定大小,该组件应配置为考虑未来可能作为新训练示例的一部分添加的额外词汇标记。 为此,在从头开始训练基础模型时配置additional_vocabulary_size参数

pipeline:
- name: CountVectorsFeaturizer
  additional_vocabulary_size:
    text: 1000
    response: 1000
    action_text: 1000

如上例所示,可以为文本(用户消息)、响应(ResponseSelector使用的机器人响应)和action_text(ResponseSelector不使用的机器人反应)中的每一个定义额外的词汇量。如果正在构建一个共享词汇表(use_shared_vocab=True),只需要为文本属性定义一个值。如果用户没有配置任何属性,则组件将当前词汇表大小的一半作为属性additional_vocabulary_size的默认值。这个数字保持在至少1000,以避免在增量训练期间过于频繁地用完额外的词汇槽。一旦组件用完了额外的词汇槽,新的词汇标记就会被丢弃,在功能化过程中不会被考虑。此时,建议从头开始重新训练新模型。

上述配置参数是应该配置的参数,以使模型适合您的数据。存在可以调整的其他参数。 更多可配置参数:

+---------------------------+-------------------------+--------------------------------------------------------------+
| Parameter                 | Default Value           | Description                                                  |
+===========================+=========================+==============================================================+
| use_shared_vocab          | False                   | If set to 'True' a common vocabulary is used for labels      |
|                           |                         | and user message.                                            |
+---------------------------+-------------------------+--------------------------------------------------------------+
| analyzer                  | word                    | Whether the features should be made of word n-gram or        |
|                           |                         | character n-grams. Option 'char_wb' creates character        |
|                           |                         | n-grams only from text inside word boundaries;               |
|                           |                         | n-grams at the edges of words are padded with space.         |
|                           |                         | Valid values: 'word', 'char', 'char_wb'.                     |
+---------------------------+-------------------------+--------------------------------------------------------------+
| strip_accents             | None                    | Remove accents during the pre-processing step.               |
|                           |                         | Valid values: 'ascii', 'unicode', 'None'.                    |
+---------------------------+-------------------------+--------------------------------------------------------------+
| stop_words                | None                    | A list of stop words to use.                                 |
|                           |                         | Valid values: 'english' (uses an internal list of            |
|                           |                         | English stop words), a list of custom stop words, or         |
|                           |                         | 'None'.                                                      |
+---------------------------+-------------------------+--------------------------------------------------------------+
| min_df                    | 1                       | When building the vocabulary ignore terms that have a        |
|                           |                         | document frequency strictly lower than the given threshold.  |
+---------------------------+-------------------------+--------------------------------------------------------------+
| max_df                    | 1                       | When building the vocabulary ignore terms that have a        |
|                           |                         | document frequency strictly higher than the given threshold  |
|                           |                         | (corpus-specific stop words).                                |
+---------------------------+-------------------------+--------------------------------------------------------------+
| min_ngram                 | 1                       | The lower boundary of the range of n-values for different    |
|                           |                         | word n-grams or char n-grams to be extracted.                |
+---------------------------+-------------------------+--------------------------------------------------------------+
| max_ngram                 | 1                       | The upper boundary of the range of n-values for different    |
|                           |                         | word n-grams or char n-grams to be extracted.                |
+---------------------------+-------------------------+--------------------------------------------------------------+
| max_features              | None                    | If not 'None', build a vocabulary that only consider the top |
|                           |                         | max_features ordered by term frequency across the corpus.    |
+---------------------------+-------------------------+--------------------------------------------------------------+
| lowercase                 | True                    | Convert all characters to lowercase before tokenizing.       |
+---------------------------+-------------------------+--------------------------------------------------------------+
| OOV_token                 | None                    | Keyword for unseen words.                                    |
+---------------------------+-------------------------+--------------------------------------------------------------+
| OOV_words                 | []                      | List of words to be treated as 'OOV_token' during training.  |
+---------------------------+-------------------------+--------------------------------------------------------------+
| alias                     | CountVectorFeaturizer   | Alias name of featurizer.                                    |
+---------------------------+-------------------------+--------------------------------------------------------------+
| use_lemma                 | True                    | Use the lemma of words for featurization.                    |
+---------------------------+-------------------------+--------------------------------------------------------------+
| additional_vocabulary_size| text: 1000              | Size of additional vocabulary to account for incremental     |
|                           | response: 1000          | training while training a model from scratch                 |
|                           | action_text: 1000       |                                                              |
+---------------------------+-------------------------+--------------------------------------------------------------+

LexicalSyntacticFeaturizer

  • 简述: 为用户消息创建词汇和句法特征以支持实体提取。
  • 输出: 用户消息和标记模式的稀疏特性
  • 要求:tokens
  • 类型: 稀疏型
  • 说明:创建用于意图分类和响应选择的特征。
  • 配置: 可以配置featurister应该提取什么样的词汇和句法特征。以下功能可用:
    ==============  ==========================================================================================
    Feature Name    Description
    ==============  ==========================================================================================
    BOS             Checks if the token is at the beginning of the sentence.
    EOS             Checks if the token is at the end of the sentence.
    low             Checks if the token is lower case.
    upper           Checks if the token is upper case.
    title           Checks if the token starts with an uppercase character and all remaining characters are
                  lowercased.
    digit           Checks if the token contains just digits.
    prefix5         Take the first five characters of the token.
    prefix2         Take the first two characters of the token.
    suffix5         Take the last five characters of the token.
    suffix3         Take the last three characters of the token.
    suffix2         Take the last two characters of the token.
    suffix1         Take the last character of the token.
    pos             Take the Part-of-Speech tag of the token (``SpacyTokenizer`` required).
    pos2            Take the first two characters of the Part-of-Speech tag of the token
                  (``SpacyTokenizer`` required).
    ==============  ==========================================================================================
    

当featurizer在带有滑动窗口的用户消息中移动令牌时,可以在滑动窗口中为之前的令牌、当前令牌和下一个令牌定义特征。可以将特征定义为[before,token,after]数组。

如果要为之前的令牌、当前令牌和之后的令牌定义功能,则功能配置如下:

pipeline:
- name: LexicalSyntacticFeaturizer
  "features": [
    ["low", "title", "upper"],
    ["BOS", "EOS", "low", "upper", "title", "digit"],
    ["low", "title", "upper"],
  ]

此配置也是默认配置。 如果需要使用pos或pos2,需将SpacyTokenizer添加到管道中。

意图分类器(Intent Classifiers)

意图分类器将domain文件中定义的意图之一分配给传入的用户消息

MitieIntentClassifier

  • 简述: MITIE意图分类器(使用文本分类器)。
  • 输出: 意图
    {
      "intent": {"name": "greet", "confidence": 0.98343}
    }
    
  • 要求:tokens和MitieNLP
  • 说明:该分类器使用MITIE进行意图分类。底层分类器使用具有稀疏线性核的多类线性SVM。
  • 配置: ```yaml pipeline:
  • name: “MitieIntentClassifier” ```

LogisticRegressionClassifier

  • 简述: 逻辑回归意图分类器,使用scikit-learn实现。。
  • 输出: 意图和意图排名
    {
      "intent": {"name": "greet", "confidence": 0.780},
      "intent_ranking": [
          {
              "confidence": 0.780,
              "name": "greet"
          },
          {
              "confidence": 0.140,
              "name": "goodbye"
          },
          {
              "confidence": 0.080,
              "name": "restaurant_search"
          }
      ]
    }
    
  • 要求:需要存在sparse_features或dense_features
  • 说明:该分类器使用scikit-learn的逻辑回归实现来执行意图分类。 它只能使用稀疏特征,但也会拾取存在的任何密集特征。 通常,DIET应该产生更高的准确度结果,但这个分类器应该训练得更快,可以用作轻量级的基准。 实现使用scikit-learn的基本设置,但class_weight参数除外,在该参数中假设为balanced设置
  • 配置: ```yaml pipeline:
  • name: LogisticRegressionClassifier max_iter: 100 # 求解器收敛所需的最大迭代次数 solver: lbfgs # 要使用的求解器。对于非常小的数据集,可以考虑liblinear。 tol: 0.0001 # 优化器停止标准的容忍度 random_state: 42 # 用于在训练前对数据进行洗牌 ranking_length: 10 # 要报告的顶级意图数。设置为0以报告所有意图 ```

SklearnIntentClassifier

  • 简述: Sklearn意图分类器。
  • 输出: 意图和意图排名
    {
      "intent": {"name": "greet", "confidence": 0.7800},
      "intent_ranking": [
          {
              "confidence": 0.7800,
              "name": "greet"
          },
          {
              "confidence": 0.1400,
              "name": "goodbye"
          },
          {
              "confidence": 0.0800,
              "name": "restaurant_search"
          }
      ]
    }
    
  • 要求:用户消息的密集特性
  • 说明:sklearn意图分类器训练一个线性SVM,该SVM使用网格搜索进行优化。 它还提供了未获胜的标签的排名。 SklearnIntentClassifier需要前置一个密集类型的特征提取器。 特征提取器创建了用于分类的特征。

  • 配置: 在SVM的训练过程中,运行超参数搜索以找到最佳参数集。 在配置中,可以指定将要尝试的参数。 ```yaml pipeline:
  • name: “SklearnIntentClassifier” # Specifies the list of regularization values to cross-validate over for C-SVM. This is used with the kernel hyperparameter in GridSearchCV. C: [1, 2, 5, 10, 20, 100] # Specifies the kernel to use with C-SVM This is used with the C hyperparameter in GridSearchCV. kernels: [“linear”] # Gamma parameter of the C-SVM. “gamma”: [0.1] # We try to find a good number of cross folds to use during intent training, this specifies the max number of folds. “max_cross_validation_folds”: 5 # Scoring function used for evaluating the hyper parameters. This can be a name or a function. “scoring_function”: “f1_weighted” ```

KeywordIntentClassifier

  • 简述: 简单的关键字匹配意图分类器,适用于小型短期项目。
  • 输出: 意图
    {
      "intent": {"name": "greet", "confidence": 1.0}
    }
    
  • 要求: 无
  • 说明: 此分类器通过在消息中搜索关键字来工作。 默认情况下,匹配区分大小写,仅搜索用户消息中关键字字符串的精确匹配。 意图的关键字是NLU训练数据中该意图的示例。 这意味着整个示例都是关键字,而不是示例中的单个单词。

  • 配置 ```yaml pipeline:
  • name: “KeywordIntentClassifier” case_sensitive: True ```

DIETClassifier

  • 简述: 用于意图分类和实体提取的双意图实体转换器(DIET).
  • 输出: 实体、意图和意图排名.
    {
      "intent": {"name": "greet", "confidence": 0.7800},
      "intent_ranking": [
          {
              "confidence": 0.7800,
              "name": "greet"
          },
          {
              "confidence": 0.1400,
              "name": "goodbye"
          },
          {
              "confidence": 0.0800,
              "name": "restaurant_search"
          }
      ],
      "entities": [{
          "end": 53,
          "entity": "time",
          "start": 48,
          "value": "2017-04-10T00:00:00.000+02:00",
          "confidence": 1.0,
          "extractor": "DIETClassifier"
      }]
    }
    
  • 要求: 用户消息的密集特征和/或稀疏特征,以及可选的意图.
  • 说明: DIET(Dual Intent and Entity Transformer)是一种用于意图分类和实体识别的多任务架构。 该架构基于一个为两个任务共享的转换器。 通过与令牌输入序列对应的转换器输出序列之上的条件随机字段(CRF)标记层来预测实体标签序列。 对于意图标签,完整话语和意图标签的转换器输出被嵌入到单个语义向量空间中。 使用点积损失来最大化与目标标签的相似性,并最小化与负样本的相似性。 DIET不提供预训练的单词嵌入或预训练的语言模型,但如果将这些功能添加到管道中,它就可以使用这些功能。 了解更多关于该模型的信息,请查看YouTube上的算法白板系列,其中将详细解释模型架构。。

如果在预测时间内,消息只包含训练期间未见的单词,并没有使用词汇外预处理器,则预测空意图的置信度为0.0。 如果只将CountVectorsFeaturer与单词分析器一起用作featurizer,则可能会出现这种情况。 如果使用char_wb分析器,应该总是得到一个置信度值大于0.0的意图。

  • 配置 如果只想将DIETClassifier用于意图分类,请将entity_recognition设置为False。 如果只想进行实体识别,请将intent_classification设置为False。 默认情况下,DIETClassifier会同时执行这两项操作。

  • epochs: 此参数设置算法将看到训练数据的轮次数(默认值:300)。 一轮等于所有训练示例的一次前向传播和反向传播。 有时,模型需要更多的时间来正确学习。 有时,更多的轮次不会影响性能。 迭代次数越少,模型的训练速度就越快。

  • hidden_layers_sizes: 此参数允许您定义用户消息和意图的前馈层数及其输出维度(默认值:text:[],label:[])。 列表中的每个条目都对应一个前馈层。 例如,如果您设置text:[256, 128],这将在转换器前面添加两个前馈层。 输入令牌的向量(来自用户消息)将传递到这些层。 第一层将具有256的输出维度,第二层将具有128的输出维度。 如果使用空列表(默认行为),则不会添加前馈层。 确保只使用正整数值。通常使用2的幂。 此外,通常的做法是列表中的值递减:下一个值小于或等于前一个值。

  • embedding_dimension: 此参数定义模型内使用的嵌入层的输出维度(默认值:20)。 模型架构中使用了多个嵌入层。 例如,完整话语和意图的向量在比较和计算损失之前被传递到嵌入层。

  • number_of_transformer_layers:此参数设置要使用的转换器层数(默认值:2)。转换器层的数量对应于用于模型的转换器块。

  • transformer_size:此参数设置转换器中的单位数(默认值:256)。 来自转换器的向量将具有给定的转换器大小。 transformer_size应该是number_of_attention_heads参数的倍数,否则训练将退出并出错。

  • connection_density:此参数定义了模型中所有前馈层设置为非零值的内核权重分数(默认值:0.2)。 该值应介于0和1之间。 如果将connection_density设置为1,则不会将内核权重设置为0,该层充当标准前馈层。 不应该将connection_density设置为0,因为这将导致所有内核权重都为0,即模型无法学习。

  • constrain_similarities:当此参数设置为True时,会对所有相似性项应用S形交叉熵损失。这有助于将输入和负标签之间的相似性保持在较小的值。 这应该有助于将模型更好地推广到现实世界的测试集。

  • model_confidence:此参数允许用户配置在推理过程中如何计算置信度。 它只能接受一个值作为输入,即softmax1。 在softmax中,置信度在[0,1]范围内。计算出的相似性用softmax激活函数进行归一化。

更多可配置参数:

+---------------------------------+------------------+--------------------------------------------------------------+
| Parameter                       | Default Value    | Description                                                  |
+=================================+==================+==============================================================+
| hidden_layers_sizes             | text: []         | Hidden layer sizes for layers before the embedding layers    |
|                                 | label: []        | for user messages and labels. The number of hidden layers is |
|                                 |                  | equal to the length of the corresponding list.               |
+---------------------------------+------------------+--------------------------------------------------------------+
| share_hidden_layers             | False            | Whether to share the hidden layer weights between user       |
|                                 |                  | messages and labels.                                         |
+---------------------------------+------------------+--------------------------------------------------------------+
| transformer_size                | 256              | Number of units in transformer.                              |
+---------------------------------+------------------+--------------------------------------------------------------+
| number_of_transformer_layers    | 2                | Number of transformer layers.                                |
+---------------------------------+------------------+--------------------------------------------------------------+
| number_of_attention_heads       | 4                | Number of attention heads in transformer.                    |
+---------------------------------+------------------+--------------------------------------------------------------+
| use_key_relative_attention      | False            | If 'True' use key relative embeddings in attention.          |
+---------------------------------+------------------+--------------------------------------------------------------+
| use_value_relative_attention    | False            | If 'True' use value relative embeddings in attention.        |
+---------------------------------+------------------+--------------------------------------------------------------+
| max_relative_position           | None             | Maximum position for relative embeddings.                    |
+---------------------------------+------------------+--------------------------------------------------------------+
| unidirectional_encoder          | False            | Use a unidirectional or bidirectional encoder.               |
+---------------------------------+------------------+--------------------------------------------------------------+
| batch_size                      | [64, 256]        | Initial and final value for batch sizes.                     |
|                                 |                  | Batch size will be linearly increased for each epoch.        |
|                                 |                  | If constant `batch_size` is required, pass an int, e.g. `8`. |
+---------------------------------+------------------+--------------------------------------------------------------+
| batch_strategy                  | "balanced"       | Strategy used when creating batches.                         |
|                                 |                  | Can be either 'sequence' or 'balanced'.                      |
+---------------------------------+------------------+--------------------------------------------------------------+
| epochs                          | 300              | Number of epochs to train.                                   |
+---------------------------------+------------------+--------------------------------------------------------------+
| random_seed                     | None             | Set random seed to any 'int' to get reproducible results.    |
+---------------------------------+------------------+--------------------------------------------------------------+
| learning_rate                   | 0.001            | Initial learning rate for the optimizer.                     |
+---------------------------------+------------------+--------------------------------------------------------------+
| embedding_dimension             | 20               | Dimension size of embedding vectors.                         |
+---------------------------------+------------------+--------------------------------------------------------------+
| dense_dimension                 | text: 128        | Dense dimension for sparse features to use.                  |
|                                 | label: 20        |                                                              |
+---------------------------------+------------------+--------------------------------------------------------------+
| concat_dimension                | text: 128        | Concat dimension for sequence and sentence features.         |
|                                 | label: 20        |                                                              |
+---------------------------------+------------------+--------------------------------------------------------------+
| number_of_negative_examples     | 20               | The number of incorrect labels. The algorithm will minimize  |
|                                 |                  | their similarity to the user input during training.          |
+---------------------------------+------------------+--------------------------------------------------------------+
| similarity_type                 | "auto"           | Type of similarity measure to use, either 'auto' or 'cosine' |
|                                 |                  | or 'inner'.                                                  |
+---------------------------------+------------------+--------------------------------------------------------------+
| loss_type                       | "cross_entropy"  | The type of the loss function, either 'cross_entropy'        |
|                                 |                  | or 'margin'. If type 'margin' is specified,                  |
|                                 |                  | "model_confidence=cosine" will be used which is deprecated   |
|                                 |                  | as of 2.3.4. See footnote (1).                               |
+---------------------------------+------------------+--------------------------------------------------------------+
| ranking_length                  | 10               | Number of top intents to report. Set to 0 to report all      |
|                                 |                  | intents.                                                     |
+---------------------------------+------------------+--------------------------------------------------------------+
| renormalize_confidences         | False            | Normalize the reported top intents. Applicable only with loss|
|                                 |                  | type 'cross_entropy' and 'softmax' confidences.              |
+---------------------------------+------------------+--------------------------------------------------------------+
| maximum_positive_similarity     | 0.8              | Indicates how similar the algorithm should try to make       |
|                                 |                  | embedding vectors for correct labels.                        |
|                                 |                  | Should be 0.0 < ... < 1.0 for 'cosine' similarity type.      |
+---------------------------------+------------------+--------------------------------------------------------------+
| maximum_negative_similarity     | -0.4             | Maximum negative similarity for incorrect labels.            |
|                                 |                  | Should be -1.0 < ... < 1.0 for 'cosine' similarity type.     |
+---------------------------------+------------------+--------------------------------------------------------------+
| use_maximum_negative_similarity | True             | If 'True' the algorithm only minimizes maximum similarity    |
|                                 |                  | over incorrect intent labels, used only if 'loss_type' is    |
|                                 |                  | set to 'margin'.                                             |
+---------------------------------+------------------+--------------------------------------------------------------+
| scale_loss                      | False            | Scale loss inverse proportionally to confidence of correct   |
|                                 |                  | prediction.                                                  |
+---------------------------------+------------------+--------------------------------------------------------------+
| regularization_constant         | 0.002            | The scale of regularization.                                 |
+---------------------------------+------------------+--------------------------------------------------------------+
| negative_margin_scale           | 0.8              | The scale of how important it is to minimize the maximum     |
|                                 |                  | similarity between embeddings of different labels.           |
+---------------------------------+------------------+--------------------------------------------------------------+
| connection_density              | 0.2              | Connection density of the weights in dense layers.           |
|                                 |                  | Value should be between 0 and 1.                             |
+---------------------------------+------------------+--------------------------------------------------------------+
| drop_rate                       | 0.2              | Dropout rate for encoder. Value should be between 0 and 1.   |
|                                 |                  | The higher the value the higher the regularization effect.   |
+---------------------------------+------------------+--------------------------------------------------------------+
| drop_rate_attention             | 0.0              | Dropout rate for attention. Value should be between 0 and 1. |
|                                 |                  | The higher the value the higher the regularization effect.   |
+---------------------------------+------------------+--------------------------------------------------------------+
| use_sparse_input_dropout        | True             | If 'True' apply dropout to sparse input tensors.             |
+---------------------------------+------------------+--------------------------------------------------------------+
| use_dense_input_dropout         | True             | If 'True' apply dropout to dense input tensors.              |
+---------------------------------+------------------+--------------------------------------------------------------+
| evaluate_every_number_of_epochs | 20               | How often to calculate validation accuracy.                  |
|                                 |                  | Set to '-1' to evaluate just once at the end of training.    |
+---------------------------------+------------------+--------------------------------------------------------------+
| evaluate_on_number_of_examples  | 0                | How many examples to use for hold out validation set.        |
|                                 |                  | Large values may hurt performance, e.g. model accuracy.      |
+---------------------------------+------------------+--------------------------------------------------------------+
| intent_classification           | True             | If 'True' intent classification is trained and intents are   |
|                                 |                  | predicted.                                                   |
+---------------------------------+------------------+--------------------------------------------------------------+
| entity_recognition              | True             | If 'True' entity recognition is trained and entities are     |
|                                 |                  | extracted.                                                   |
+---------------------------------+------------------+--------------------------------------------------------------+
| use_masked_language_model       | False            | If 'True' random tokens of the input message will be masked  |
|                                 |                  | and the model has to predict those tokens. It acts like a    |
|                                 |                  | regularizer and should help to learn a better contextual     |
|                                 |                  | representation of the input.                                 |
+---------------------------------+------------------+--------------------------------------------------------------+
| tensorboard_log_directory       | None             | If you want to use tensorboard to visualize training         |
|                                 |                  | metrics, set this option to a valid output directory. You    |
|                                 |                  | can view the training metrics after training in tensorboard  |
|                                 |                  | via 'tensorboard --logdir <path-to-given-directory>'.        |
+---------------------------------+------------------+--------------------------------------------------------------+
| tensorboard_log_level           | "epoch"          | Define when training metrics for tensorboard should be       |
|                                 |                  | logged. Either after every epoch ('epoch') or for every      |
|                                 |                  | training step ('batch').                                 |
+---------------------------------+------------------+--------------------------------------------------------------+
| featurizers                     | []               | List of featurizer names (alias names). Only features        |
|                                 |                  | coming from the listed names are used. If list is empty      |
|                                 |                  | all available features are used.                             |
+---------------------------------+------------------+--------------------------------------------------------------+
| checkpoint_model                | False            | Save the best performing model during training. Models are   |
|                                 |                  | stored to the location specified by `--out`. Only the one    |
|                                 |                  | best model will be saved.                                    |
|                                 |                  | Requires `evaluate_on_number_of_examples > 0` and            |
|                                 |                  | `evaluate_every_number_of_epochs > 0`                        |
+---------------------------------+------------------+--------------------------------------------------------------+
| split_entities_by_comma         | True             | Splits a list of extracted entities by comma to treat each   |
|                                 |                  | one of them as a single entity. Can either be `True`/`False` |
|                                 |                  | globally, or set per entity type, such as:                   |
|                                 |                  | ```                                                          |
|                                 |                  | ...                                                          |
|                                 |                  | - name: DIETClassifier                                       |
|                                 |                  |   split_entities_by_comma:                                   |
|                                 |                  |     address: True                                            |
|                                 |                  |     ...                                                      |
|                                 |                  | ...                                                          |
|                                 |                  | ```                                                          |
+---------------------------------+------------------+--------------------------------------------------------------+
| constrain_similarities          | False            | If `True`, applies sigmoid on all similarity terms and adds  |
|                                 |                  | it to the loss function to ensure that similarity values are |
|                                 |                  | approximately bounded. Used only if `loss_type=cross_entropy`|
+---------------------------------+------------------+--------------------------------------------------------------+
| model_confidence                | "softmax"        | Affects how model's confidence for each intent               |
|                                 |                  | is computed. Currently, only one value is supported:         |
|                                 |                  | 1. `softmax` - Similarities between input and intent         |
|                                 |                  | embeddings are post-processed with a softmax function,       |
|                                 |                  | as a result of which confidence for all intents sum up to 1. |
|                                 |                  | This parameter does not affect the confidence for entity     |
|                                 |                  | prediction.                                                  |
+---------------------------------+------------------+--------------------------------------------------------------+

FallbackClassifier

  • 简述: 如nlu意图分类分数不明确,则使用意图nlu_fallback对消息进行分类。 置信度设置为与回退阈值相同。
  • 输出: 实体、意图和意图排名
    
      {
          "intent": {"name": "nlu_fallback", "confidence": 0.7183846840434321},
          "intent_ranking": [
              {
                  "confidence": 0.7183846840434321,
                  "name": "nlu_fallback"
              },
              {
                  "confidence": 0.28161531595656784,
                  "name": "restaurant_search"
              }
          ],
          "entities": [{
              "end": 53,
              "entity": "time",
              "start": 48,
              "value": "2017-04-10T00:00:00.000+02:00",
              "confidence": 1.0,
              "extractor": "DIETClassifier"
          }]
      }
    
  • 要求: 先前意图分类器的意图和意图排序输出
  • 说明: FallbackClassifier使用intent nlu_fallback对用户消息进行分类,以防之前的意图分类器无法以大于或等于FallbackClassifiers阈值的置信度对意图进行分类。 当两个排名靠前的意图的置信度得分接近ambiguity_threshold时,它还可以预测回退意图。

可以使用FallbackClassifier来实现一个回退操作,该操作处理具有不确定NLU预测的消息。

rules:

- rule: Ask the user to rephrase in case of low NLU confidence
  steps:
  - intent: nlu_fallback
  - action: utter_please_rephrase
  • 配置

FallbackClassifier只会在没有其他意图被预测的置信度大于或等于阈值的情况下添加其对nlu_fallback意图的预测。

threshold:此参数设置预测nlu_fallback意图的阈值。如果先前意图分类器预测的意图的置信度不大于或等于阈值,则回退分类器将添加一个置信度为1.0的nlu_fallback意图预测。

ambiguity_threshold:如果你配置了一个ambiguity_threshold,如果两个排名最高的意图的置信度得分差小于ambiguity.threshold,FallbackClassifier也会预测nlu_fallback意图。

实体提取器(Entity Extractors)

实体提取器从用户消息中提取实体,如人名或位置。

如果使用多个实体提取器,建议每个提取器都针对一组独占的实体类型。 例如,使用Duckling提取日期和时间,使用DIETClassifier提取人名。 否则,如果多个提取器针对相同的实体类型,则很可能会多次提取实体。

例如,如果使用两个或多个通用提取器,如MitieEntityExtractor、DIETClassifier或CRFEntityExtractor,则所有这些提取器都将找到并提取训练数据中的实体类型。 如果填充实体类型的插槽是文本类型,则管道中的最后一个提取器将获胜。 如果插槽类型为list,则所有结果都将添加到列表中,包括重复结果。

即使提取器关注不同的实体类型,也可能发生另一种不太明显的重复/重叠提取情况。 想象一下,一个送餐机器人和一条用户消息,比如我想订购周一特价。 假设时间提取器的性能不是很好,它可能会在这里提取周一作为点餐时间,而你的另一个提取器可能会提取周一特价作为餐。 如果很难处理这种重叠的实体,那么添加额外的训练数据来改进提取器可能是有意义的。 如果这还不够,可以添加一个自定义组件,根据自己的逻辑解决实体提取中的冲突。

MitieEntityExtractor

  • 简述: MITIE实体提取(使用MITIE NER训练器)。
  • 输出: 实体 python { "entities": [{ "value": "New York City", "start": 20, "end": 33, "confidence": null, "entity": "city", "extractor": "MitieEntityExtractor" }] }
  • 要求: MitieNLP和tokens
  • 说明: MitieEntityExtractor使用MITIE实体提取来查找消息中的实体。

底层分类器使用具有稀疏线性核和自定义特征的多类线性SVM。 MITIE组件不提供实体置信度值。

  • 配置: ```yaml pipeline:
  • name: “MitieEntityExtractor” ```

SpacyEntityExtractor

  • 简述: spaCy实体提取
  • 输出: 实体
    {
      "entities": [{
          "value": "New York City",
          "start": 20,
          "end": 33,
          "confidence": null,
          "entity": "city",
          "extractor": "SpacyEntityExtractor"
      }]
    }
    
  • 要求:SpacyNLP
  • 说明: 使用spaCy,此组件预测消息的实体。 spaCy使用统计BILOU转换模型。 到目前为止,该组件只能使用spaCy内置的实体提取模型,不能重新训练。 此提取器不提供任何置信度分数。

  • 配置: 配置spaCy组件应提取哪些维度,即实体类型。

可用维度尺寸的完整列表可以在spaCy文档中找到。 未指定维度尺寸选项将提取所有可用维度尺寸。

pipeline:
- name: "SpacyEntityExtractor" # dimensions to extract
  dimensions: ["PERSON", "LOC", "ORG", "PRODUCT"]

CRFEntityExtractor

  • 简述: 条件随机字段(CRF)实体提取
  • 输出: 实体
    {
      "entities": [{
          "value": "New York City",
          "start": 20,
          "end": 33,
          "entity": "city",
          "confidence": 0.874,
          "extractor": "CRFEntityExtractor"
      }]
    }
    
  • 要求: tokens和密集特征(可选)
  • 说明: 该组件实现了一个条件随机字段(CRF)来进行命名实体识别。 CRF可以被认为是一个无向马尔可夫链,其中时间步长是单词,状态是实体类。 单词的特征(大写、POS标签等)为某些实体类提供了概率,相邻实体标签之间的转换也是如此,然后计算并返回最可能的标签集。

如果想将自定义功能(如预训练的单词嵌入)传递给CRFEntityExtractor,可以在CRFEntity Extractor之前将任何密集特征添加到管道中,然后通过在其功能配置中添加“text_dense_feature”来配置CRFEntiteExtractor以利用密集特征。

CRFEntityExtractor会自动查找其他密集特征,并检查密集特征是否是len(标记)的可迭代对象,其中每个条目都是一个向量。如果检查失败,将显示警告。 但是,CRFEntityExtractor将在没有其他自定义功能的情况下继续训练。 如果存在密集特征,CRFEntityExtractor将把密集特征传递给sklearn_crfsuite并将其用于训练。

  • 配置:
    ===================  ==========================================================================================
    Feature Name         Description
    ===================  ==========================================================================================
    low                  word identity - use the lower-cased token as a feature.
    upper                Checks if the token is upper case.
    title                Checks if the token starts with an uppercase character and all remaining characters are
                       lowercased.
    digit                Checks if the token contains just digits.
    prefix5              Take the first five characters of the token.
    prefix2              Take the first two characters of the token.
    suffix5              Take the last five characters of the token.
    suffix3              Take the last three characters of the token.
    suffix2              Take the last two characters of the token.
    suffix1              Take the last character of the token.
    pos                  Take the Part-of-Speech tag of the token (``SpacyTokenizer`` required).
    pos2                 Take the first two characters of the Part-of-Speech tag of the token
                       (``SpacyTokenizer`` required).
    pattern              Take the patterns defined by ``RegexFeaturizer``.
    bias                 Add an additional "bias" feature to the list of features.
    text_dense_features  Adds additional features from a dense featurizer.
    ===================  ==========================================================================================
    

当featurizer在带有滑动窗口的用户消息中移动令牌时,可以为之前的令牌、当前令牌和下一个令牌定义特征。 可以将特征定义为[before,token,after]数组。

BILOU_flag决定是否使用BILOU标记。默认值为True。

pipeline:
- name: "CRFEntityExtractor"
  # BILOU_flag determines whether to use BILOU tagging or not.
  "BILOU_flag": True
  # features to extract in the sliding window
  "features": [
    ["low", "title", "upper"],
    [
      "bias",
      "low",
      "prefix5",
      "prefix2",
      "suffix5",
      "suffix3",
      "suffix2",
      "upper",
      "title",
      "digit",
      "pattern",
      "text_dense_features"
    ],
    ["low", "title", "upper"],
  ]
  # The maximum number of iterations for optimization algorithms.
  "max_iterations": 50
  # weight of the L1 regularization
  "L1_c": 0.1
  # weight of the L2 regularization
  "L2_c": 0.1
  # Name of dense featurizers to use.
  # If list is empty all available dense features are used.
  "featurizers": []
  # Indicated whether a list of extracted entities should be split into individual entities for a given entity type
  "split_entities_by_comma":
      address: False
      email: True

如果使用POS功能(POS或pos2),管道中需要有SpacyTokenizer。

如果使用模式特征,管道中需要有RegexFeatureizer。

如果使用text_dense_features特征,则需要在管道中有一个密集的特征化器(例如LanguageModelFeatureizer)。

DucklingEntityExtractor

  • 简述: Duckling允许提取多种语言中的常见实体,如日期、金额、距离等。

  • 输出: 实体
    {
      "entities": [{
          "end": 53,
          "entity": "time",
          "start": 48,
          "value": "2017-04-10T00:00:00.000+02:00",
          "confidence": 1.0,
          "extractor": "DucklingEntityExtractor"
      }]
    }
    
  • 要求: 无
  • 说明: 要使用此组件,您需要运行一个duckling服务器。 最简单的选择是使用docker run-p 8000:8000 rasa/duck启动docker容器.

Duckling允许识别日期、数字、距离和其他结构化实体,并对其进行规范化。

请注意,Duckling试图在不提供排名的情况下提取尽可能多的实体类型。

如果将数字和时间都指定为Duckling组件的维度 文本: 我将在10分钟后到达。 该组件将从文本中提取两个实体: 10作为数字,10分钟后作为时间。

在这种情况下,应用程序必须决定哪种实体类型是正确的。

提取器将始终返回1.0作为置信度,因为它是一个基于规则的系统。

  • 配置:
pipeline:
- name: "DucklingEntityExtractor"   # url of the running duckling server
  url: "http://localhost:8000"   # dimensions to extract
  dimensions: ["time", "number", "amount-of-money", "distance"]
  ## allows you to configure the locale, by default the language is
  ## used
  locale: "de_DE"
  # if not set the default timezone of Duckling is going to be used
  # needed to calculate dates from relative expressions like "tomorrow"
  timezone: "Europe/Berlin"
  # Timeout for receiving response from http url of the running duckling server
  # if not set the default timeout of duckling http url is set to 3 seconds.
  timeout : 3

DIETClassifier

  • 简述: 用于意图分类和实体提取的双意图实体转换器(DIET)

  • 说明: 可在Intent Classifiers一节中找到DIETClassifier的详细描述。

RegexEntityExtractor

  • 简述: 使用训练数据中定义的查找表和/或正则表达式提取实体.
  • 输出: 实体
  • 要求: 无
  • 说明: 此组件使用训练数据中定义的查找表和正则表达式提取实体。 该组件检查用户消息是否包含其中一个查找表的条目或与其中一个正则表达式匹配。 如果找到匹配项,则将值提取为实体。

此组件仅使用那些名称等于训练数据中定义的实体之一的正则表达式特征。 确保每个实体至少注释一个示例。

当将此提取器与MitieEntityExtractor、CRFEntityExtractor或DIETClassifier结合使用时,可能会导致实体的多次提取。 特别是如果许多训练句也定义了正则表达式的实体类型有实体注释。 有关多重提取的更多信息,请参阅实体提取器部分开头的说明。

如果需要此RegexEntityExtractor和另一个上述统计提取器,建议考虑以下两个选项之一。

  1. 当每种提取器都有独占的实体类型时,建议使用此选项。 为了确保提取器不会相互干扰,为每种正则表达式/查找实体类型只注释一个例句,而不是更多。

  2. 当希望使用正则表达式匹配作为统计提取器的附加信号,但没有单独的实体类型时,此选项很有用。 在这种情况下,需要 1)在管道中的提取器之前添加RegexFeatureizer 2)在训练数据中注释所有实体示例, 3)从管道中删除RegexEntityExtractor。 这样,统计提取器将收到有关正则表达式匹配存在的额外信号,并能够统计地确定何时依赖这些匹配,何时不依赖。

  • 配置: 通过添加case_sensitive:True 选项使实体提取器区分大小写,默认值为case_sensitive:False。

为了正确处理不使用空格进行单词分隔的中文等语言,用户需要添加use_word_boundaries:False选项,默认值为use_word_boundaries:True。

    pipeline:
    - name: RegexEntityExtractor
      # text will be processed with case insensitive as default
      case_sensitive: False
      # use lookup tables to extract entities
      use_lookup_tables: True
      # use regexes to extract entities
      use_regexes: True
      # use match word boundaries for lookup table
      use_word_boundaries: True

EntitySynonymMapper

  • 简述: 将同义实体值映射到相同的值。
  • 输出: 修改以前实体提取组件找到的现有实体。
  • 要求: 一个实体提取器
  • 说明: 如果训练数据包含定义的同义词,则此组件将确保检测到的实体值映射到相同的值。 例如,如果您的训练数据包含以下示例:
    [
      {
        "text": "I moved to New York City",
        "intent": "inform_relocation",
        "entities": [{
          "value": "nyc",
          "start": 11,
          "end": 24,
          "entity": "city",
        }]
      },
      {
        "text": "I got a new flat in NYC.",
        "intent": "inform_relocation",
        "entities": [{
          "value": "nyc",
          "start": 20,
          "end": 23,
          "entity": "city",
        }]
      }
    ]
    

    此组件将允许您将实体New York City和NYC映射到NYC。 即使消息中包含nyc,实体提取也会返回nyc。 当此组件更改现有实体时,它会将自己附加到此实体的处理器列表中。

  • 配置: ``` yaml pipeline:
  • name: “EntitySynonymMapper” ``` 当将EntitySynonymMapper用作NLU管道的一部分时,它需要放置在配置文件中的任何实体提取器下方。

组合意图分类器和实体提取器

DIETClassifier

  • 简述: 用于意图分类和实体提取的双意图实体转换器(DIET)

  • 输出: 实体、意图和意图排名
    {
      "intent": {"name": "greet", "confidence": 0.7800},
      "intent_ranking": [
          {
              "confidence": 0.7800,
              "name": "greet"
          },
          {
              "confidence": 0.1400,
              "name": "goodbye"
          },
          {
              "confidence": 0.0800,
              "name": "restaurant_search"
          }
      ],
      "entities": [{
          "end": 53,
          "entity": "time",
          "start": 48,
          "value": "2017-04-10T00:00:00.000+02:00",
          "confidence": 1.0,
          "extractor": "DIETClassifier"
      }]
    }
    
  • 要求: 用户消息的密集特征和/或稀疏特征,以及可选的意图

  • 说明: DIET(Dual Intent and Entity Transformer)是一种用于意图分类和实体识别的多任务架构。 该架构基于被两个任务共享的转换器。 通过与令牌输入序列对应的转换器输出序列之上的条件随机字段(CRF)标记层来预测实体标签序列。 对于意图标签,完整话语和意图标签的转换器输出被嵌入到单个语义向量空间中。 使用点积损失来最大化与目标标签的相似性,并最小化与负样本的相似性。

如果在预测时间内,消息只包含训练期间未见的单词,且没有使用词汇外预处理器,则预测空意图“无”的置信度为0.0。 如果只将CountVectorsFeaturer与单词分析器一起用作featurizer,则可能会出现这种情况。 如果使用char_wb分析器,应该总是得到一个置信度值大于0.0的意图。

  • 配置: 如果只用于意图分类,将entity_agnition设置为False。 如果只进行实体识别,将intent_classification设置为False。 默认情况下,DIETClassifier会同时执行这两项操作。

参数列表: 略.

选择器(Selectors)

选择器从一组候选响应中预测机器人的响应。

ResponseSelector

  • 简述: 响应选择器
  • 输出: 一个字典,其关键字作为响应选择器的检索意图,值包含预测响应、置信度和检索意图下的响应关键字.

NLU的解析输出将具有一个名为response_selector的属性,其中包含每个响应选择器组件的输出。

每个响应选择器由该响应选择器的retrieveal_intent参数标识,并存储两个属性: response:对应检索意图下的预测响应关键字、预测置信度和相关响应。 ranking:根据前10个候选响应密钥的置信度进行排名。

{
    "response_selector": {
      "faq": {
        "response": {
          "id": 1388783286124361986,
          "confidence": 0.7,
          "intent_response_key": "chitchat/ask_weather",
          "responses": [
            {
              "text": "It's sunny in Berlin today",
              "image": "https://i.imgur.com/nGF1K8f.jpg"
            },
            {
              "text": "I think it's about to rain."
            }
          ],
          "utter_action": "utter_chitchat/ask_weather"
         },
        "ranking": [
          {
            "id": 1388783286124361986,
            "confidence": 0.7,
            "intent_response_key": "chitchat/ask_weather"
          },
          {
            "id": 1388783286124361986,
            "confidence": 0.3,
            "intent_response_key": "chitchat/ask_name"
          }
        ]
      }
    }
}

如果特定响应选择器的retrieval_intent参数保留为默认值,则相应的响应选择器将在返回的输出中被标识为默认值。

{
    "response_selector": {
      "default": {
        "response": {
          "id": 1388783286124361986,
          "confidence": 0.7,
          "intent_response_key": "chitchat/ask_weather",
          "responses": [
            {
              "text": "It's sunny in Berlin today",
              "image": "https://i.imgur.com/nGF1K8f.jpg"
            },
            {
              "text": "I think it's about to rain."
            }
          ],
          "utter_action": "utter_chitchat/ask_weather"
         },
        "ranking": [
          {
            "id": 1388783286124361986,
            "confidence": 0.7,
            "intent_response_key": "chitchat/ask_weather"
          },
          {
            "id": 1388783286124361986,
            "confidence": 0.3,
            "intent_response_key": "chitchat/ask_name"
          }
        ]
      }
    }
}
  • 要求: 用户消息和响应的密集特征和/或稀疏特征
  • 说明: 响应选择器组件可用于构建响应检索模型,以直接从一组候选响应中预测机器人响应。 对话管理器使用此模型的预测来发出预测的响应。 它将用户输入和响应标签嵌入到相同的空间中,并遵循与DIET分类器完全相同的神经网络架构和优化。

要使用此组件,训练数据应包含检索意图。 要定义这些,请查看NLU训练示例的文档和为检索意图定义响应语句的文档。

如果在预测时间内,消息只包含训练期间未见的单词,并没有使用词汇外预处理器,则预测空意图的置信度为0.0。 如果只将CountVectorsFeaturer与单词分析器一起用作featurizer,则可能会出现这种情况。 如果使用char_wb分析器,应该总是得到一个置信度值大于0.0的意图。

  • 配置: 该算法几乎包括DIETClassifier使用的所有超参数。

  • epochs: 此参数设置算法将看到训练数据的轮次数(默认值:300)。 一轮等于所有训练示例的一次前向传播和反向传播。 有时,模型需要更多的时间来正确学习。 有时,更多的轮次不会影响性能。 迭代次数越少,模型的训练速度就越快。

  • hidden_layers_sizes: 此参数允许您定义用户消息和意图的前馈层数及其输出维度(默认值:text:[],label:[])。 列表中的每个条目都对应一个前馈层。 例如,如果您设置text:[256, 128],这将在转换器前面添加两个前馈层。 输入令牌的向量(来自用户消息)将传递到这些层。 第一层将具有256的输出维度,第二层将具有128的输出维度。 如果使用空列表(默认行为),则不会添加前馈层。 确保只使用正整数值。通常使用2的幂。 此外,通常的做法是列表中的值递减:下一个值小于或等于前一个值。

  • embedding_dimension: 此参数定义模型内使用的嵌入层的输出维度(默认值:20)。 模型架构中使用了多个嵌入层。 例如,完整话语和意图的向量在比较和计算损失之前被传递到嵌入层。

  • number_of_transformer_layers:此参数设置要使用的转换器层数(默认值:2)。转换器层的数量对应于用于模型的转换器块。

  • transformer_size:此参数设置转换器中的单位数(默认值:256)。 来自转换器的向量将具有给定的转换器大小。 transformer_size应该是number_of_attention_heads参数的倍数,否则训练将退出并出错。

  • connection_density: 此参数定义了模型中所有前馈层设置为非零值的内核权重分数(默认值:0.2)。 该值应介于0和1之间。 如果将connection_density设置为1,则不会将内核权重设置为0,该层充当标准前馈层。 不应该将connection_density设置为0,因为这将导致所有内核权重都为0,即模型无法学习。

  • constrain_similarities:当此参数设置为True时,会对所有相似性项应用S形交叉熵损失。这有助于将输入和负标签之间的相似性保持在较小的值。 这应该有助于将模型更好地推广到现实世界的测试集。

  • model_confidence:此参数允许用户配置在推理过程中如何计算置信度。 它只能接受一个值作为输入,即softmax1。 在softmax中,置信度在[0,1]范围内。计算出的相似性用softmax激活函数进行归一化。

该组件还可以被配置为针对特定的检索意图训练响应选择器。 参数retrieval_intent设置了训练此响应选择器模型的检索意图的名称。 默认值为None,即模型针对所有检索意图进行训练。

在默认配置中,该组件使用带有响应键(例如faq/ask_name)的检索意图作为训练标签。 或者,也可以通过将use_text_as_label切换为True来配置为使用响应的文本作为训练标签。 在此模式下,组件将使用具有文本属性的第一个可用响应进行训练。 如果没有找到,则退回到使用检索意图和响应键作为标签。

更多配置参数:

+---------------------------------+-------------------+--------------------------------------------------------------+
| Parameter                       | Default Value     | Description                                                  |
+=================================+===================+==============================================================+
| hidden_layers_sizes             | text: [256, 128]  | Hidden layer sizes for layers before the embedding layers    |
|                                 | label: [256, 128] | for user messages and labels. The number of hidden layers is |
|                                 |                   | equal to the length of the corresponding list. We recommend  |
|                                 |                   | disabling the hidden layers (by providing empty lists) when  |
|                                 |                   | the transformer is enabled.                                  |
+---------------------------------+-------------------+--------------------------------------------------------------+
| share_hidden_layers             | False             | Whether to share the hidden layer weights between user       |
|                                 |                   | messages and labels.                                         |
+---------------------------------+-------------------+--------------------------------------------------------------+
| transformer_size                | None              | Number of units in the transformer. When a positive value is |
|                                 |                   | provided for `number_of_transformer_layers`, the default size|
|                                 |                   | becomes `256`.                                               |
+---------------------------------+-------------------+--------------------------------------------------------------+
| number_of_transformer_layers    | 0                 | Number of transformer layers; positive values enable the     |
|                                 |                   | transformer.                                                 |
+---------------------------------+-------------------+--------------------------------------------------------------+
| number_of_attention_heads       | 4                 | Number of attention heads in transformer.                    |
+---------------------------------+-------------------+--------------------------------------------------------------+
| use_key_relative_attention      | False             | If 'True' use key relative embeddings in attention.          |
+---------------------------------+-------------------+--------------------------------------------------------------+
| use_value_relative_attention    | False             | If 'True' use value relative embeddings in attention.        |
+---------------------------------+-------------------+--------------------------------------------------------------+
| max_relative_position           | None              | Maximum position for relative embeddings.                    |
+---------------------------------+-------------------+--------------------------------------------------------------+
| unidirectional_encoder          | False             | Use a unidirectional or bidirectional encoder.               |
+---------------------------------+-------------------+--------------------------------------------------------------+
| batch_size                      | [64, 256]         | Initial and final value for batch sizes.                     |
|                                 |                   | Batch size will be linearly increased for each epoch.        |
|                                 |                   | If constant `batch_size` is required, pass an int, e.g. `8`. |
+---------------------------------+-------------------+--------------------------------------------------------------+
| batch_strategy                  | "balanced"        | Strategy used when creating batches.                         |
|                                 |                   | Can be either 'sequence' or 'balanced'.                      |
+---------------------------------+-------------------+--------------------------------------------------------------+
| epochs                          | 300               | Number of epochs to train.                                   |
+---------------------------------+-------------------+--------------------------------------------------------------+
| random_seed                     | None              | Set random seed to any 'int' to get reproducible results.    |
+---------------------------------+-------------------+--------------------------------------------------------------+
| learning_rate                   | 0.001             | Initial learning rate for the optimizer.                     |
+---------------------------------+-------------------+--------------------------------------------------------------+
| embedding_dimension             | 20                | Dimension size of embedding vectors.                         |
+---------------------------------+-------------------+--------------------------------------------------------------+
| dense_dimension                 | text: 512         | Dense dimension for sparse features to use if no dense       |
|                                 | label: 512        | features are present.                                        |
+---------------------------------+-------------------+--------------------------------------------------------------+
| concat_dimension                | text: 512         | Concat dimension for sequence and sentence features.         |
|                                 | label: 512        |                                                              |
+---------------------------------+-------------------+--------------------------------------------------------------+
| number_of_negative_examples     | 20                | The number of incorrect labels. The algorithm will minimize  |
|                                 |                   | their similarity to the user input during training.          |
+---------------------------------+-------------------+--------------------------------------------------------------+
| similarity_type                 | "auto"            | Type of similarity measure to use, either 'auto' or 'cosine' |
|                                 |                   | or 'inner'.                                                  |
+---------------------------------+-------------------+--------------------------------------------------------------+
| loss_type                       | "cross_entropy"   | The type of the loss function, either 'cross_entropy'        |
|                                 |                   | or 'margin'. Type 'margin' is only compatible with           |
|                                 |                   | "model_confidence=cosine",                                   |
|                                 |                   | which is deprecated (see changelog for 2.3.4).               |
+---------------------------------+-------------------+--------------------------------------------------------------+
| ranking_length                  | 10                | Number of top responses to report. Set to 0 to report all    |
|                                 |                   | responses.                                                   |
+---------------------------------+-------------------+--------------------------------------------------------------+
| renormalize_confidences         | False             | Normalize the top responses. Applicable only with loss type  |
|                                 |                   | 'cross_entropy' and 'softmax' confidences.                   |
+---------------------------------+-------------------+--------------------------------------------------------------+
| maximum_positive_similarity     | 0.8               | Indicates how similar the algorithm should try to make       |
|                                 |                   | embedding vectors for correct labels.                        |
|                                 |                   | Should be 0.0 < ... < 1.0 for 'cosine' similarity type.      |
+---------------------------------+-------------------+--------------------------------------------------------------+
| maximum_negative_similarity     | -0.4              | Maximum negative similarity for incorrect labels.            |
|                                 |                   | Should be -1.0 < ... < 1.0 for 'cosine' similarity type.     |
+---------------------------------+-------------------+--------------------------------------------------------------+
| use_maximum_negative_similarity | True              | If 'True' the algorithm only minimizes maximum similarity    |
|                                 |                   | over incorrect intent labels, used only if 'loss_type' is    |
|                                 |                   | set to 'margin'.                                             |
+---------------------------------+-------------------+--------------------------------------------------------------+
| scale_loss                      | True              | Scale loss inverse proportionally to confidence of correct   |
|                                 |                   | prediction.                                                  |
+---------------------------------+-------------------+--------------------------------------------------------------+
| regularization_constant         | 0.002             | The scale of regularization.                                 |
+---------------------------------+-------------------+--------------------------------------------------------------+
| negative_margin_scale           | 0.8               | The scale of how important is to minimize the maximum        |
|                                 |                   | similarity between embeddings of different labels.           |
+---------------------------------+-------------------+--------------------------------------------------------------+
| connection_density              | 0.2               | Connection density of the weights in dense layers.           |
|                                 |                   | Value should be between 0 and 1.                             |
+---------------------------------+-------------------+--------------------------------------------------------------+
| drop_rate                       | 0.2               | Dropout rate for encoder. Value should be between 0 and 1.   |
|                                 |                   | The higher the value the higher the regularization effect.   |
+---------------------------------+-------------------+--------------------------------------------------------------+
| drop_rate_attention             | 0.0               | Dropout rate for attention. Value should be between 0 and 1. |
|                                 |                   | The higher the value the higher the regularization effect.   |
+---------------------------------+-------------------+--------------------------------------------------------------+
| use_sparse_input_dropout        | False             | If 'True' apply dropout to sparse input tensors.             |
+---------------------------------+-------------------+--------------------------------------------------------------+
| use_dense_input_dropout         | False             | If 'True' apply dropout to dense input tensors.              |
+---------------------------------+-------------------+--------------------------------------------------------------+
| evaluate_every_number_of_epochs | 20                | How often to calculate validation accuracy.                  |
|                                 |                   | Set to '-1' to evaluate just once at the end of training.    |
+---------------------------------+-------------------+--------------------------------------------------------------+
| evaluate_on_number_of_examples  | 0                 | How many examples to use for hold out validation set.        |
|                                 |                   | Large values may hurt performance, e.g. model accuracy.      |
|                                 |                   | Set to 0 for no validation.                                  |
+---------------------------------+-------------------+--------------------------------------------------------------+
| use_masked_language_model       | False             | If 'True' random tokens of the input message will be masked  |
|                                 |                   | and the model should predict those tokens.                   |
+---------------------------------+-------------------+--------------------------------------------------------------+
| retrieval_intent                | None              | Name of the intent for which this response selector model is |
|                                 |                   | trained.                                                     |
+---------------------------------+-------------------+--------------------------------------------------------------+
| use_text_as_label               | False             | Whether to use the actual text of the response as the label  |
|                                 |                   | for training the response selector. Otherwise, it uses the   |
|                                 |                   | response key as the label.                                   |
+---------------------------------+-------------------+--------------------------------------------------------------+
| tensorboard_log_directory       | None              | If you want to use tensorboard to visualize training         |
|                                 |                   | metrics, set this option to a valid output directory. You    |
|                                 |                   | can view the training metrics after training in tensorboard  |
|                                 |                   | via 'tensorboard --logdir <path-to-given-directory>'.        |
+---------------------------------+-------------------+--------------------------------------------------------------+
| tensorboard_log_level           | "epoch"           | Define when training metrics for tensorboard should be       |
|                                 |                   | logged. Either after every epoch ("epoch") or for every      |
|                                 |                   | training step ("batch").                                     |
+---------------------------------+-------------------+--------------------------------------------------------------+
| featurizers                     | []                | List of featurizer names (alias names). Only features        |
|                                 |                   | coming from the listed names are used. If list is empty      |
|                                 |                   | all available features are used.                             |
+---------------------------------+-------------------+--------------------------------------------------------------+
| checkpoint_model                | False             | Save the best performing model during training. Models are   |
|                                 |                   | stored to the location specified by `--out`. Only the one    |
|                                 |                   | best model will be saved.                                    |
|                                 |                   | Requires `evaluate_on_number_of_examples > 0` and            |
|                                 |                   | `evaluate_every_number_of_epochs > 0`                        |
+---------------------------------+-------------------+--------------------------------------------------------------+
| constrain_similarities          | False             | If `True`, applies sigmoid on all similarity terms and adds  |
|                                 |                   | it to the loss function to ensure that similarity values are |
|                                 |                   | approximately bounded. Used only if `loss_type=cross_entropy`|
+---------------------------------+-------------------+--------------------------------------------------------------+
| model_confidence                | "softmax"         | Affects how model's confidence for each response label       |
|                                 |                   | is computed. Currently, only one value is supported:         |
|                                 |                   | 1. `softmax` - Similarities between input and response label |
|                                 |                   | embeddings are post-processed with a softmax function,       |
|                                 |                   | as a result of which confidence for all labels sum up to 1.  |
+---------------------------------+-------------------+--------------------------------------------------------------+

自定义组件(Custom Components)

可以创建一个自定义组件来执行NLU当前不提供的特定任务(例如,情绪分析)。

通过添加模块路径将自定义组件添加到管道中。 假设有一个名为sentiment的模块,包含一个SentimentAnalyzer类:

pipeline:
- name: "sentiment.SentimentAnalyzer"

有关自定义组件的完整指南,请参阅自定义图形组件指南。 另外,请务必阅读组件生命周期部分。