经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
自定义Graph Component:1-开发指南
来源:cnblogs  作者:扫地升  时间:2023/11/13 8:45:29  对本文有异议

??可以使用自定义NLU组件和策略扩展Rasa,本文提供了如何开发自己的自定义Graph Component指南。
??Rasa提供各种开箱即用的NLU组件和策略。可以使用自定义Graph Component对其进行自定义或从头开始创建自己的组件。
??要在Rasa中使用自定义Graph Component,它必须满足以下要求:

  • 它必须实现GraphComponent接口
  • 必须注册使用过的model配置
  • 必须在配置文件中使用它
  • 它必须使用类型注释。Rasa利用类型注释来验证模型配置。不允许前向引用。如果使用Python 3.7,可以使用from __future__ import annotations来摆脱前向引用。

一.Graph Components
??Rasa使用传入的模型配置(config.yml)来构建DAG,描述了config.yml中Component间的依赖关系以及数据如何在它们之间流动。这有两个主要好处:

  • Rasa可以使用计算图来优化模型的执行。这方面的例子包括训练步骤的高效缓存或并行执行独立的步骤。
  • Rasa可以灵活地表示不同的模型架构。只要图保持非循环,Rasa理论上可以根据模型配置将任何数据传递给任何图组件,而无需将底层软件架构与使用的模型架构绑定。

??将config.yml转换为计算图时,Policy和NLU组件成为该图中的节点。虽然模型配置中的Policy和NLU组件之间存在区别,但当它们被放置在图中时,这种区别就被抽象出来了。此时,Policy和NLU组件成为抽象图组件。在实践中,这由GraphComponent接口表示:Policy和NLU组件都必须继承此接口,才能与Rasa的图兼容并可执行。

二.入门指南
??在开始之前,必须决定是实现自定义NLU组件还是Policy。如果正在实现自定义策略,那么建议扩展现有的rasa.core.policies.policy.Policy类,该类已经实现了GraphComponent接口。如下所示:

  1. from rasa.core.policies.policy import Policy
  2. from rasa.engine.recipes.default_recipe import DefaultV1Recipe
  3.  
  4. # TODO: Correctly register your graph component
  5. @DefaultV1Recipe.register(
  6.     [DefaultV1Recipe.ComponentType.POLICY_WITHOUT_END_TO_END_SUPPORT], is_trainable=True
  7. )
  8. class MyPolicy(Policy):
  9.     ...

??如果要实现自定义NLU组件,要从以下框架开始:

  1. from typing import Dict, Text, Any, List
  2.  
  3. from rasa.engine.graph import GraphComponent, ExecutionContext
  4. from rasa.engine.recipes.default_recipe import DefaultV1Recipe
  5. from rasa.engine.storage.resource import Resource
  6. from rasa.engine.storage.storage import ModelStorage
  7. from rasa.shared.nlu.training_data.message import Message
  8. from rasa.shared.nlu.training_data.training_data import TrainingData
  9.  
  10. # TODO: Correctly register your component with its type
  11. @DefaultV1Recipe.register(
  12.     [DefaultV1Recipe.ComponentType.INTENT_CLASSIFIER], is_trainable=True
  13. )
  14. class CustomNLUComponent(GraphComponent):
  15.     @classmethod
  16.     def create(
  17.         cls,
  18.         config: Dict[Text, Any],
  19.         model_storage: ModelStorage,
  20.         resource: Resource,
  21.         execution_context: ExecutionContext,
  22.     ) -> GraphComponent:
  23.         # TODO: Implement this
  24.         ...
  25.  
  26.     def train(self, training_data: TrainingData) -> Resource:
  27.         # TODO: Implement this if your component requires training
  28.         ...
  29.  
  30.     def process_training_data(self, training_data: TrainingData) -> TrainingData:
  31.         # TODO: Implement this if your component augments the training data with
  32.         #       tokens or message features which are used by other components
  33.         #       during training.
  34.         ...
  35.  
  36.         return training_data
  37.  
  38.     def process(self, messages: List[Message]) -> List[Message]:
  39.         # TODO: This is the method which Rasa Open Source will call during inference.
  40.         ...
  41.         return messages

??下面会介绍如何解决上述示例中的TODO,以及需要在自定义组件中实现的其它方法。
自定义词法分析器:如果创建了一个自定义的tokenizer,应该扩展rasa.nlu.tokenizers.tokenizer. Tokenizer类。train和process方法已经实现,所以只需要覆盖tokenize方法。

三.GraphComponent接口
??要使用Rasa运行自定义NLU组件或Policy,必须实现GraphComponent接口。如下所示:

  1. from __future__ import annotations
  2. from abc import ABC, abstractmethod
  3. from typing import List, Type, Dict, Text, Any, Optional
  4.  
  5. from rasa.engine.graph import ExecutionContext
  6. from rasa.engine.storage.resource import Resource
  7. from rasa.engine.storage.storage import ModelStorage
  8.  
  9.  
  10. class GraphComponent(ABC):
  11.     """Interface for any component which will run in a graph."""
  12.  
  13.     @classmethod
  14.     def required_components(cls) -> List[Type]:
  15.         """Components that should be included in the pipeline before this component."""
  16.         return []
  17.  
  18.     @classmethod
  19.     @abstractmethod
  20.     def create(
  21.         cls,
  22.         config: Dict[Text, Any],
  23.         model_storage: ModelStorage,
  24.         resource: Resource,
  25.         execution_context: ExecutionContext,
  26.     ) -> GraphComponent:
  27.         """Creates a new `GraphComponent`.
  28.  
  29.         Args:
  30.             config: This config overrides the `default_config`.
  31.             model_storage: Storage which graph components can use to persist and load
  32.                 themselves.
  33.             resource: Resource locator for this component which can be used to persist
  34.                 and load itself from the `model_storage`.
  35.             execution_context: Information about the current graph run.
  36.  
  37.         Returns: An instantiated `GraphComponent`.
  38.         """
  39.         ...
  40.  
  41.     @classmethod
  42.     def load(
  43.         cls,
  44.         config: Dict[Text, Any],
  45.         model_storage: ModelStorage,
  46.         resource: Resource,
  47.         execution_context: ExecutionContext,
  48.         **kwargs: Any,
  49.     ) -> GraphComponent:
  50.         """Creates a component using a persisted version of itself.
  51.  
  52.         If not overridden this method merely calls `create`.
  53.  
  54.         Args:
  55.             config: The config for this graph component. This is the default config of
  56.                 the component merged with config specified by the user.
  57.             model_storage: Storage which graph components can use to persist and load
  58.                 themselves.
  59.             resource: Resource locator for this component which can be used to persist
  60.                 and load itself from the `model_storage`.
  61.             execution_context: Information about the current graph run.
  62.             kwargs: Output values from previous nodes might be passed in as `kwargs`.
  63.  
  64.         Returns:
  65.             An instantiated, loaded `GraphComponent`.
  66.         """
  67.         return cls.create(config, model_storage, resource, execution_context)
  68.  
  69.     @staticmethod
  70.     def get_default_config() -> Dict[Text, Any]:
  71.         """Returns the component's default config.
  72.  
  73.         Default config and user config are merged by the `GraphNode` before the
  74.         config is passed to the `create` and `load` method of the component.
  75.  
  76.         Returns:
  77.             The default config of the component.
  78.         """
  79.         return {}
  80.  
  81.     @staticmethod
  82.     def supported_languages() -> Optional[List[Text]]:
  83.         """Determines which languages this component can work with.
  84.  
  85.         Returns: A list of supported languages, or `None` to signify all are supported.
  86.         """
  87.         return None
  88.  
  89.     @staticmethod
  90.     def not_supported_languages() -> Optional[List[Text]]:
  91.         """Determines which languages this component cannot work with.
  92.  
  93.         Returns: A list of not supported languages, or
  94.             `None` to signify all are supported.
  95.         """
  96.         return None
  97.  
  98.     @staticmethod
  99.     def required_packages() -> List[Text]:
  100.         """Any extra python dependencies required for this component to run."""
  101.         return []
  102.  
  103.     @classmethod
  104.     def fingerprint_addon(cls, config: Dict[str, Any]) -> Optional[str]:
  105.         """Adds additional data to the fingerprint calculation.
  106.  
  107.         This is useful if a component uses external data that is not provided
  108.         by the graph.
  109.         """
  110.         return None

1.create方法
??create方法用于在训练期间实例化图组件,并且必须被覆盖。Rasa在调用该方法时传递以下参数:
(1)config:这是组件的默认配置,与模型配置文件中提供给图组件的配置合并。
(2)model_storage:可以使用此功能来持久化和加载图组件。有关其用法的更多详细信息,请参阅模型持久化部分。
(3)resource:模型存储中组件的唯一标识符。有关其用法的更多详细信息,请参阅模型持久性部分。
(4)execution_context:提供有关当前执行模式的额外信息:

  • model_id: 推理过程中使用的模型的唯一标识符。在训练过程中,此参数为None。
  • should_add_diagnostic_data:如果为True,则应在实际预测的基础上向图组件的预测中添加额外的诊断元数据。
  • is_finetuning:如果为True,则可以使用微调来训练图组件。
  • graph_schema:graph_schema描述用于训练助手或用它进行预测的计算图。
  • node_name:node_name是图模式中步骤的唯一标识符,由所调用的图组件完成。

2.load方法
??在推理过程中,使用load方法来实例化图组件。此方法的默认实现会调用create方法。如果图组件将数据作为训练的一部分,建议覆盖此方法。有关各个参数的描述,参阅create方法。

3.get_default_config方法
??get_default_config方法返回图组件的默认配置。它的默认实现返回一个空字典,这意味着图组件没有任何配置。Rasa将在运行时使用配置文件(config.yml)中的给定值更新默认配置。

4.supported_languages方法
??supported_languages方法指定了图组件支持的语言。Rasa将使用模型配置文件中的语言键来验证图组件是否可用于指定的语言。如果图组件返回None(这是默认实现),则表示图组件支持not_supported_languages中未包含的所有语言。示例如下所示:

  • []:图组件不支持任何语言
  • None:支持所有语言,但不支持not_supported_languages中定义的语言
  • ["en"]:图组件只能用于英语对话

5.not_supported_languages方法
??not_supported_languages方法指定图组件不支持哪些语言。Rasa将使用模型配置文件中的语言键来验证图组件是否可用于指定的语言。如果图组件返回None(这是默认实现),则表示它支持supported_languages中指定的所有语言。示例如下所示:

  • 无或[]:支持supported_languages中指定的所有语言。
  • ["en"]:该图形组件可用于除英语以外的任何语言。

6.required_packages方法
??required_packages方法表明需要安装哪些额外的Python包才能使用此图组件。如果在运行时找不到所需的库,Rasa将在执行过程中抛出错误。默认情况下,此方法返回一个空列表,这意味着图组件没有任何额外的依赖关系。示例如下所示:

  • []:使用此图组件不需要额外的包
  • ["spacy"]:需要安装Python包spacy才能使用此图组件。

四.模型持久化
??一些图组件需要在训练期间持久化数据,这些数据在推理时应该对图组件可用。一个典型的用例是存储模型权重。为此,Rasa为图组件的create和load方法提供了model_storage和resource参数,如下面的代码片段所示。model_storage提供对所有图组件数据的访问。resource允许唯一标识图组件在模型存储中的位置。

  1. from __future__ import annotations
  2.  
  3. from typing import Any, Dict, Text
  4.  
  5. from rasa.engine.graph import GraphComponent, ExecutionContext
  6. from rasa.engine.storage.resource import Resource
  7. from rasa.engine.storage.storage import ModelStorage
  8.  
  9. class MyComponent(GraphComponent):
  10.     @classmethod
  11.     def create(
  12.         cls,
  13.         config: Dict[Text, Any],
  14.         model_storage: ModelStorage,
  15.         resource: Resource,
  16.         execution_context: ExecutionContext,
  17.     ) -> MyComponent:
  18.         ...
  19.  
  20.     @classmethod
  21.     def load(
  22.         cls,
  23.         config: Dict[Text, Any],
  24.         model_storage: ModelStorage,
  25.         resource: Resource,
  26.         execution_context: ExecutionContext,
  27.         **kwargs: Any
  28.     ) -> MyComponent:
  29.         ...

1.写模型存储
??下面的代码片段演示了如何将图组件的数据写入模型存储。要在训练后持久化图组件,train方法需要访问model_storage和resource的值。因此,应该在初始化时存储model_storage和resource的值。 图组件的train方法必须返回resource的值,以便Rasa可以在训练之间缓存训练结果。self._model_storage.write_to(self._resource)上下文管理器提供了一个目录路径,可以在其中持久化图组件所需的任何数据。

  1. from __future__ import annotations
  2. import json
  3. from typing import Optional, Dict, Any, Text
  4.  
  5. from rasa.engine.graph import GraphComponent, ExecutionContext
  6. from rasa.engine.storage.resource import Resource
  7. from rasa.engine.storage.storage import ModelStorage
  8. from rasa.shared.nlu.training_data.training_data import TrainingData
  9.  
  10. class MyComponent(GraphComponent):
  11.  
  12.     def __init__(
  13.         self,
  14.         model_storage: ModelStorage,
  15.         resource: Resource,
  16.         training_artifact: Optional[Dict],
  17.     ) -> None:
  18.         # Store both `model_storage` and `resource` as object attributes to be able
  19.         # to utilize them at the end of the training
  20.         self._model_storage = model_storage
  21.         self._resource = resource
  22.  
  23.     @classmethod
  24.     def create(
  25.         cls,
  26.         config: Dict[Text, Any],
  27.         model_storage: ModelStorage,
  28.         resource: Resource,
  29.         execution_context: ExecutionContext,
  30.     ) -> MyComponent:
  31.         return cls(model_storage, resource, training_artifact=None)
  32.  
  33.     def train(self, training_data: TrainingData) -> Resource:
  34.         # Train your graph component
  35.         ...
  36.  
  37.         # Persist your graph component
  38.         with self._model_storage.write_to(self._resource) as directory_path:
  39.             with open(directory_path / "artifact.json", "w") as file:
  40.                 json.dump({"my": "training artifact"}, file)
  41.  
  42.         # Return resource to make sure the training artifacts
  43.         # can be cached.
  44.         return self._resource

2.读模型存储
??Rasa将调用图组件的load方法来实例化它以进行推理。可以使用上下文管理器self._model_storage.read_from(resource)来获取图组件数据所保存的目录的路径。使用提供的路径,可以加载保存的数据并用它初始化图组件。请注意,如果给定的资源没有找到保存的数据,model_storage将抛出ValueError。

  1. from __future__ import annotations
  2. import json
  3. from typing import Optional, Dict, Any, Text
  4.  
  5. from rasa.engine.graph import GraphComponent, ExecutionContext
  6. from rasa.engine.storage.resource import Resource
  7. from rasa.engine.storage.storage import ModelStorage
  8.  
  9. class MyComponent(GraphComponent):
  10.  
  11.     def __init__(
  12.         self,
  13.         model_storage: ModelStorage,
  14.         resource: Resource,
  15.         training_artifact: Optional[Dict],
  16.     ) -> None:
  17.         self._model_storage = model_storage
  18.         self._resource = resource
  19.  
  20.     @classmethod
  21.     def load(
  22.         cls,
  23.         config: Dict[Text, Any],
  24.         model_storage: ModelStorage,
  25.         resource: Resource,
  26.         execution_context: ExecutionContext,
  27.         **kwargs: Any,
  28.     ) -> MyComponent:
  29.         try:
  30.             with model_storage.read_from(resource) as directory_path:
  31.                 with open(directory_path / "artifact.json", "r") as file:
  32.                     training_artifact = json.load(file)
  33.                     return cls(
  34.                         model_storage, resource, training_artifact=training_artifact
  35.                     )
  36.         except ValueError:
  37.             # This allows you to handle the case if there was no
  38.             # persisted data for your component
  39.             ...

五.用模型配置注册Graph Components
??为了让图组件可用于Rasa,可能需要使用recipe注册图组件。Rasa使用recipe将模型配置的内容转换为可执行的graph。目前,Rasa支持default.v1和实验性graph.v1 recipe。对于default.v1 recipe,需要使用DefaultV1Recipe.register装饰器注册图组件:

  1. from rasa.engine.graph import GraphComponent
  2. from rasa.engine.recipes.default_recipe import DefaultV1Recipe
  3.  
  4. @DefaultV1Recipe.register(
  5.     component_types=[DefaultV1Recipe.ComponentType.INTENT_CLASSIFIER],
  6.     is_trainable=True,
  7.     model_from="SpacyNLP",
  8. )
  9. class MyComponent(GraphComponent):
  10.     ...

??Rasa使用register装饰器中提供的信息以及图组件在配置文件中的位置来调度图组件及其所需数据的执行。DefaultV1Recipe.register装饰器允许指定以下详细信息:
1.component_types
??指定了图组件在助手内实现的目的。可以指定多种类型(例如,如果图组件既是意图分类器又是实体提取器)。
(1)ComponentType.MODEL_LOADER
??语言模型的组件类型。如果指定了model_from=

六.在模型配置中使用自定义组件
??可以在模型配置中使用自定义图组件,就像其它NLU组件或策略一样。唯一的变化是,必须指定完整的模块名称,而不是仅指定类名。完整的模块名称取决于模块相对于指定的PYTHONPATH的位置。默认情况下,Rasa会将运行CLI的目录添加到PYTHONPATH。例如,如果从/Users/<user>/my-rasa-project运行CLI,并且模块MyComponent在/Users/<user>/my-rasa-project/custom_components/my_component.py 中,则模块路径为custom_components.my_component.MyComponent。除了name条目之外,所有内容都将作为config传递给组件。config.yml文件如下所示:

  1. recipe: default.v1
  2. language: en
  3. pipeline:
  4. # other NLU components
  5. - name: your.custom.NLUComponent
  6.   setting_a: 0.01
  7.   setting_b: string_value
  8.  
  9. policies:
  10. # other dialogue policies
  11. - name: your.custom.Policy

七.实现提示
1.消息元数据
??当在训练数据中为意图示例定义元数据时,NLU组件可以在处理过程中访问意图元数据和意图示例元数据,如下所示:

  1. # in your component class
  2. def process(self, message: Message, **kwargs: Any) -> None:
  3.     metadata = message.get("metadata")
  4.     print(metadata.get("intent"))
  5.     print(metadata.get("example"))

2.稀疏和稠密消息特征
??如果创建了一个自定义的消息特征器,可以返回两种不同的特征:序列特征和句子特征。序列特征是一个大小为(number-of-tokens x feature-dimension)的矩阵,即该矩阵包含序列中每个token的特征向量。句子特征由大小为(1 x feature-dimension)的矩阵表示。

八.自定义组件的例子
1.稠密消息特征器
??使用预训练模型的一个dense message featurizer的例子,如下所示:

  1. import numpy as np
  2. import logging
  3. from bpemb import BPEmb
  4. from typing import Any, Text, Dict, List, Type
  5.  
  6. from rasa.engine.recipes.default_recipe import DefaultV1Recipe
  7. from rasa.engine.graph import ExecutionContext, GraphComponent
  8. from rasa.engine.storage.resource import Resource
  9. from rasa.engine.storage.storage import ModelStorage
  10. from rasa.nlu.featurizers.dense_featurizer.dense_featurizer import DenseFeaturizer
  11. from rasa.nlu.tokenizers.tokenizer import Tokenizer
  12. from rasa.shared.nlu.training_data.training_data import TrainingData
  13. from rasa.shared.nlu.training_data.features import Features
  14. from rasa.shared.nlu.training_data.message import Message
  15. from rasa.nlu.constants import (
  16.     DENSE_FEATURIZABLE_ATTRIBUTES,
  17.     FEATURIZER_CLASS_ALIAS,
  18. )
  19. from rasa.shared.nlu.constants import (
  20.     TEXT,
  21.     TEXT_TOKENS,
  22.     FEATURE_TYPE_SENTENCE,
  23.     FEATURE_TYPE_SEQUENCE,
  24. )
  25.  
  26.  
  27. logger = logging.getLogger(__name__)
  28.  
  29.  
  30. @DefaultV1Recipe.register(
  31.     DefaultV1Recipe.ComponentType.MESSAGE_FEATURIZER, is_trainable=False
  32. )
  33. class BytePairFeaturizer(DenseFeaturizer, GraphComponent):
  34.     @classmethod
  35.     def required_components(cls) -> List[Type]:
  36.         """Components that should be included in the pipeline before this component."""
  37.         return [Tokenizer]
  38.  
  39.     @staticmethod
  40.     def required_packages() -> List[Text]:
  41.         """Any extra python dependencies required for this component to run."""
  42.         return ["bpemb"]
  43.  
  44.     @staticmethod
  45.     def get_default_config() -> Dict[Text, Any]:
  46.         """Returns the component's default config."""
  47.         return {
  48.             **DenseFeaturizer.get_default_config(),
  49.             # specifies the language of the subword segmentation model
  50.             "lang": None,
  51.             # specifies the dimension of the subword embeddings
  52.             "dim": None,
  53.             # specifies the vocabulary size of the segmentation model
  54.             "vs": None,
  55.             # if set to True and the given vocabulary size can't be loaded for the given
  56.             # model, the closest size is chosen
  57.             "vs_fallback": True,
  58.         }
  59.  
  60.     def __init__(
  61.         self,
  62.         config: Dict[Text, Any],
  63.         name: Text,
  64.     ) -> None:
  65.         """Constructs a new byte pair vectorizer."""
  66.         super().__init__(name, config)
  67.         # The configuration dictionary is saved in `self._config` for reference.
  68.         self.model = BPEmb(
  69.             lang=self._config["lang"],
  70.             dim=self._config["dim"],
  71.             vs=self._config["vs"],
  72.             vs_fallback=self._config["vs_fallback"],
  73.         )
  74.  
  75.     @classmethod
  76.     def create(
  77.         cls,
  78.         config: Dict[Text, Any],
  79.         model_storage: ModelStorage,
  80.         resource: Resource,
  81.         execution_context: ExecutionContext,
  82.     ) -> GraphComponent:
  83.         """Creates a new component (see parent class for full docstring)."""
  84.         return cls(config, execution_context.node_name)
  85.  
  86.     def process(self, messages: List[Message]) -> List[Message]:
  87.         """Processes incoming messages and computes and sets features."""
  88.         for message in messages:
  89.             for attribute in DENSE_FEATURIZABLE_ATTRIBUTES:
  90.                 self._set_features(message, attribute)
  91.         return messages
  92.  
  93.     def process_training_data(self, training_data: TrainingData) -> TrainingData:
  94.         """Processes the training examples in the given training data in-place."""
  95.         self.process(training_data.training_examples)
  96.         return training_data
  97.  
  98.     def _create_word_vector(self, document: Text) -> np.ndarray:
  99.         """Creates a word vector from a text. Utility method."""
  100.         encoded_ids = self.model.encode_ids(document)
  101.         if encoded_ids:
  102.             return self.model.vectors[encoded_ids[0]]
  103.  
  104.         return np.zeros((self.component_config["dim"],), dtype=np.float32)
  105.  
  106.     def _set_features(self, message: Message, attribute: Text = TEXT) -> None:
  107.         """Sets the features on a single message. Utility method."""
  108.         tokens = message.get(TEXT_TOKENS)
  109.  
  110.         # If the message doesn't have tokens, we can't create features.
  111.         if not tokens:
  112.             return None
  113.  
  114.         # We need to reshape here such that the shape is equivalent to that of sparsely
  115.         # generated features. Without it, it'd be a 1D tensor. We need 2D (n_utterance, n_dim).
  116.         text_vector = self._create_word_vector(document=message.get(TEXT)).reshape(
  117.             1, -1
  118.         )
  119.         word_vectors = np.array(
  120.             [self._create_word_vector(document=t.text) for t in tokens]
  121.         )
  122.  
  123.         final_sequence_features = Features(
  124.             word_vectors,
  125.             FEATURE_TYPE_SEQUENCE,
  126.             attribute,
  127.             self._config[FEATURIZER_CLASS_ALIAS],
  128.         )
  129.         message.add_features(final_sequence_features)
  130.         final_sentence_features = Features(
  131.             text_vector,
  132.             FEATURE_TYPE_SENTENCE,
  133.             attribute,
  134.             self._config[FEATURIZER_CLASS_ALIAS],
  135.         )
  136.         message.add_features(final_sentence_features)
  137.  
  138.     @classmethod
  139.     def validate_config(cls, config: Dict[Text, Any]) -> None:
  140.         """Validates that the component is configured properly."""
  141.         if not config["lang"]:
  142.             raise ValueError("BytePairFeaturizer needs language setting via `lang`.")
  143.         if not config["dim"]:
  144.             raise ValueError(
  145.                 "BytePairFeaturizer needs dimensionality setting via `dim`."
  146.             )
  147.         if not config["vs"]:
  148.             raise ValueError("BytePairFeaturizer needs a vector size setting via `vs`.")

2.稀疏消息特征器
??以下是稀疏消息特征器的示例,它训练了一个新模型:

  1. import logging
  2. from typing import Any, Text, Dict, List, Type
  3.  
  4. from sklearn.feature_extraction.text import TfidfVectorizer
  5. from rasa.engine.recipes.default_recipe import DefaultV1Recipe
  6. from rasa.engine.graph import ExecutionContext, GraphComponent
  7. from rasa.engine.storage.resource import Resource
  8. from rasa.engine.storage.storage import ModelStorage
  9. from rasa.nlu.featurizers.sparse_featurizer.sparse_featurizer import SparseFeaturizer
  10. from rasa.nlu.tokenizers.tokenizer import Tokenizer
  11. from rasa.shared.nlu.training_data.training_data import TrainingData
  12. from rasa.shared.nlu.training_data.features import Features
  13. from rasa.shared.nlu.training_data.message import Message
  14. from rasa.nlu.constants import (
  15.     DENSE_FEATURIZABLE_ATTRIBUTES,
  16.     FEATURIZER_CLASS_ALIAS,
  17. )
  18. from joblib import dump, load
  19. from rasa.shared.nlu.constants import (
  20.     TEXT,
  21.     TEXT_TOKENS,
  22.     FEATURE_TYPE_SENTENCE,
  23.     FEATURE_TYPE_SEQUENCE,
  24. )
  25.  
  26. logger = logging.getLogger(__name__)
  27.  
  28.  
  29. @DefaultV1Recipe.register(
  30.     DefaultV1Recipe.ComponentType.MESSAGE_FEATURIZER, is_trainable=True
  31. )
  32. class TfIdfFeaturizer(SparseFeaturizer, GraphComponent):
  33.     @classmethod
  34.     def required_components(cls) -> List[Type]:
  35.         """Components that should be included in the pipeline before this component."""
  36.         return [Tokenizer]
  37.  
  38.     @staticmethod
  39.     def required_packages() -> List[Text]:
  40.         """Any extra python dependencies required for this component to run."""
  41.         return ["sklearn"]
  42.  
  43.     @staticmethod
  44.     def get_default_config() -> Dict[Text, Any]:
  45.         """Returns the component's default config."""
  46.         return {
  47.             **SparseFeaturizer.get_default_config(),
  48.             "analyzer": "word",
  49.             "min_ngram": 1,
  50.             "max_ngram": 1,
  51.         }
  52.  
  53.     def __init__(
  54.         self,
  55.         config: Dict[Text, Any],
  56.         name: Text,
  57.         model_storage: ModelStorage,
  58.         resource: Resource,
  59.     ) -> None:
  60.         """Constructs a new tf/idf vectorizer using the sklearn framework."""
  61.         super().__init__(name, config)
  62.         # Initialize the tfidf sklearn component
  63.         self.tfm = TfidfVectorizer(
  64.             analyzer=config["analyzer"],
  65.             ngram_range=(config["min_ngram"], config["max_ngram"]),
  66.         )
  67.  
  68.         # We need to use these later when saving the trained component.
  69.         self._model_storage = model_storage
  70.         self._resource = resource
  71.  
  72.     def train(self, training_data: TrainingData) -> Resource:
  73.         """Trains the component from training data."""
  74.         texts = [e.get(TEXT) for e in training_data.training_examples if e.get(TEXT)]
  75.         self.tfm.fit(texts)
  76.         self.persist()
  77.         return self._resource
  78.  
  79.     @classmethod
  80.     def create(
  81.         cls,
  82.         config: Dict[Text, Any],
  83.         model_storage: ModelStorage,
  84.         resource: Resource,
  85.         execution_context: ExecutionContext,
  86.     ) -> GraphComponent:
  87.         """Creates a new untrained component (see parent class for full docstring)."""
  88.         return cls(config, execution_context.node_name, model_storage, resource)
  89.  
  90.     def _set_features(self, message: Message, attribute: Text = TEXT) -> None:
  91.         """Sets the features on a single message. Utility method."""
  92.         tokens = message.get(TEXT_TOKENS)
  93.  
  94.         # If the message doesn't have tokens, we can't create features.
  95.         if not tokens:
  96.             return None
  97.  
  98.         # Make distinction between sentence and sequence features
  99.         text_vector = self.tfm.transform([message.get(TEXT)])
  100.         word_vectors = self.tfm.transform([t.text for t in tokens])
  101.  
  102.         final_sequence_features = Features(
  103.             word_vectors,
  104.             FEATURE_TYPE_SEQUENCE,
  105.             attribute,
  106.             self._config[FEATURIZER_CLASS_ALIAS],
  107.         )
  108.         message.add_features(final_sequence_features)
  109.         final_sentence_features = Features(
  110.             text_vector,
  111.             FEATURE_TYPE_SENTENCE,
  112.             attribute,
  113.             self._config[FEATURIZER_CLASS_ALIAS],
  114.         )
  115.         message.add_features(final_sentence_features)
  116.  
  117.     def process(self, messages: List[Message]) -> List[Message]:
  118.         """Processes incoming message and compute and set features."""
  119.         for message in messages:
  120.             for attribute in DENSE_FEATURIZABLE_ATTRIBUTES:
  121.                 self._set_features(message, attribute)
  122.         return messages
  123.  
  124.     def process_training_data(self, training_data: TrainingData) -> TrainingData:
  125.         """Processes the training examples in the given training data in-place."""
  126.         self.process(training_data.training_examples)
  127.         return training_data
  128.  
  129.     def persist(self) -> None:
  130.         """
  131.         Persist this model into the passed directory.
  132.  
  133.         Returns the metadata necessary to load the model again. In this case; `None`.
  134.         """
  135.         with self._model_storage.write_to(self._resource) as model_dir:
  136.             dump(self.tfm, model_dir / "tfidfvectorizer.joblib")
  137.  
  138.     @classmethod
  139.     def load(
  140.         cls,
  141.         config: Dict[Text, Any],
  142.         model_storage: ModelStorage,
  143.         resource: Resource,
  144.         execution_context: ExecutionContext,
  145.     ) -> GraphComponent:
  146.         """Loads trained component from disk."""
  147.         try:
  148.             with model_storage.read_from(resource) as model_dir:
  149.                 tfidfvectorizer = load(model_dir / "tfidfvectorizer.joblib")
  150.                 component = cls(
  151.                     config, execution_context.node_name, model_storage, resource
  152.                 )
  153.                 component.tfm = tfidfvectorizer
  154.         except (ValueError, FileNotFoundError):
  155.             logger.debug(
  156.                 f"Couldn't load metadata for component '{cls.__name__}' as the persisted "
  157.                 f"model data couldn't be loaded."
  158.             )
  159.         return component
  160.  
  161.     @classmethod
  162.     def validate_config(cls, config: Dict[Text, Any]) -> None:
  163.         """Validates that the component is configured properly."""
  164.         pass

九.NLP元学习器
??NLU Meta学习器是一个高级用例。以下部分仅适用于拥有一个基于先前分类器输出学习参数的组件的情况。对于具有手动设置参数或逻辑的组件,可以创建一个is_trainable=False的组件,而不用担心前面的分类器。
??NLU Meta学习器是意图分类器或实体提取器,它们使用其它经过训练的意图分类器或实体提取器的预测,并尝试改进其结果。Meta学习器的一个例子是平均两个先前意图分类器输出的组件,或者是一个fallback分类器,它根据意图分类器对训练示例的置信度设置阈值。
??从概念上讲,要构建可训练的fallback分类器,首先需要将该fallback分类器创建为自定义组件:

  1. from typing import Dict, Text, Any, List
  2.  
  3. from rasa.engine.graph import GraphComponent, ExecutionContext
  4. from rasa.engine.recipes.default_recipe import DefaultV1Recipe
  5. from rasa.engine.storage.resource import Resource
  6. from rasa.engine.storage.storage import ModelStorage
  7. from rasa.shared.nlu.training_data.message import Message
  8. from rasa.shared.nlu.training_data.training_data import TrainingData
  9. from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier
  10.  
  11. @DefaultV1Recipe.register(
  12.     [DefaultV1Recipe.ComponentType.INTENT_CLASSIFIER], is_trainable=True
  13. )
  14. class MetaFallback(FallbackClassifier):
  15.  
  16.     def __init__(
  17.         self,
  18.         config: Dict[Text, Any],
  19.         model_storage: ModelStorage,
  20.         resource: Resource,
  21.         execution_context: ExecutionContext,
  22.     ) -> None:
  23.         super().__init__(config)
  24.  
  25.         self._model_storage = model_storage
  26.         self._resource = resource
  27.  
  28.     @classmethod
  29.     def create(
  30.         cls,
  31.         config: Dict[Text, Any],
  32.         model_storage: ModelStorage,
  33.         resource: Resource,
  34.         execution_context: ExecutionContext,
  35.     ) -> FallbackClassifier:
  36.         """Creates a new untrained component (see parent class for full docstring)."""
  37.         return cls(config, model_storage, resource, execution_context)
  38.  
  39.     def train(self, training_data: TrainingData) -> Resource:
  40.         # Do something here with the messages
  41.         return self._resource

??接下来,需要创建一个定制的意图分类器,它也是一个特征器,因为分类器的输出需要被下游的另一个组件使用。对于定制的意图分类器组件,还需要定义如何将其预测添加到指定process_training_data方法的消息数据中。确保不要覆盖意图的真实标签。这里有一个模板,显示了如何为此目的对DIET进行子类化:

  1. from rasa.engine.recipes.default_recipe import DefaultV1Recipe
  2. from rasa.shared.nlu.training_data.training_data import TrainingData
  3. from rasa.nlu.classifiers.diet_classifier import DIETClassifier
  4.  
  5. @DefaultV1Recipe.register(
  6.     [DefaultV1Recipe.ComponentType.INTENT_CLASSIFIER,
  7.      DefaultV1Recipe.ComponentType.ENTITY_EXTRACTOR,
  8.      DefaultV1Recipe.ComponentType.MESSAGE_FEATURIZER], is_trainable=True
  9. )
  10. class DIETFeaturizer(DIETClassifier):
  11.  
  12.     def process_training_data(self, training_data: TrainingData) -> TrainingData:
  13.         # classify and add the attributes to the messages on the training data
  14.         return training_data

参考文献:
[1]Custom Graph Components:https://rasa.com/docs/rasa/custom-graph-components

原文链接:https://www.cnblogs.com/shengshengwang/p/17827809.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号