自定义模型集成

介绍

Qlib模型库 包含了一些模型,如 LightGBMMLPLSTM 等等。这些模型都是 预测模型 的例子。除了 Qlib 提供的默认模型外,用户还可以将自定义模型集成到 Qlib 中。

用户可以根据以下步骤集成他们自己的自定义模型。

  • 定义一个自定义模型类,该类应该是 qlib.model.base.Model 的子类。

  • 编写一个描述自定义模型的路径和参数的配置文件。

  • 测试自定义模型。

自定义模型类

自定义模型需要继承 qlib.model.base.Model 并重写其中的方法。

  • 重写 __init__ 方法
    • Qlib 将初始化的参数传递给 __init__ 方法。

    • 配置文件中模型的超参数必须与 __init__ 方法中定义的超参数一致。

    • 代码示例:在下面的示例中,配置文件中模型的超参数应该包含 loss:mse 等参数。

      def __init__(self, loss='mse', **kwargs):
          if loss not in {'mse', 'binary'}:
              raise NotImplementedError
          self._scorer = mean_squared_error if loss == 'mse' else roc_auc_score
          self._params.update(objective=loss, **kwargs)
          self._model = None
      
  • 重写 fit 方法
    • Qlib 调用 fit 方法来训练模型。

    • 参数必须包含训练特征 dataset,该特征是在接口中设计的。

    • 参数可以包含一些具有默认值的 可选 参数,例如使用 num_boost_round = 1000 做为 GBDT 的可选参数。

    • 代码示例:在下面的示例中,num_boost_round = 1000 是一个可选参数。

      def fit(self, dataset: DatasetH, num_boost_round = 1000, **kwargs):
      
          # prepare dataset for lgb training and evaluation
          df_train, df_valid = dataset.prepare(
              ["train", "valid"], col_set=["feature", "label"], data_key=DataHandlerLP.DK_L
          )
          x_train, y_train = df_train["feature"], df_train["label"]
          x_valid, y_valid = df_valid["feature"], df_valid["label"]
      
          # Lightgbm need 1D array as its label
          if y_train.values.ndim == 2 and y_train.values.shape[1] == 1:
              y_train, y_valid = np.squeeze(y_train.values), np.squeeze(y_valid.values)
          else:
              raise ValueError("LightGBM doesn't support multi-label training")
      
          dtrain = lgb.Dataset(x_train.values, label=y_train)
          dvalid = lgb.Dataset(x_valid.values, label=y_valid)
      
          # fit the model
          self.model = lgb.train(
              self.params,
              dtrain,
              num_boost_round=num_boost_round,
              valid_sets=[dtrain, dvalid],
              valid_names=["train", "valid"],
              early_stopping_rounds=early_stopping_rounds,
              verbose_eval=verbose_eval,
              evals_result=evals_result,
              **kwargs
          )
      
  • Override the predict method
    • The parameters must include the parameter dataset, which will be userd to get the test dataset.

    • Return the prediction score.

    • Please refer to Model API for the parameter types of the fit method.

    • Code Example: In the following example, users need to use LightGBM to predict the label(such as preds) of test data x_test and return it.

      def predict(self, dataset: DatasetH, **kwargs)-> pandas.Series:
          if self.model is None:
              raise ValueError("model is not fitted yet!")
          x_test = dataset.prepare("test", col_set="feature", data_key=DataHandlerLP.DK_I)
          return pd.Series(self.model.predict(x_test.values), index=x_test.index)
      
  • Override the finetune method (Optional)
    • This method is optional to the users. When users want to use this method on their own models, they should inherit the ModelFT base class, which includes the interface of finetune.

    • The parameters must include the parameter dataset.

    • Code Example: In the following example, users will use LightGBM as the model and finetune it.

      def finetune(self, dataset: DatasetH, num_boost_round=10, verbose_eval=20):
          # 基于现有模型进行微调并训练更多轮次
          dtrain, _ = self._prepare_data(dataset)
          self.model = lgb.train(
              self.params,
              dtrain,
              num_boost_round=num_boost_round,
              init_model=self.model,
              valid_sets=[dtrain],
              valid_names=["train"],
              verbose_eval=verbose_eval,
          )
      

配置文件

详细的配置文件说明在 Workflow 文档中。为了将自定义模型集成到 Qlib 中,用户需要修改配置文件中的”model”字段。该配置文件描述了使用哪些模型以及如何初始化它。

  • 示例:以下示例描述了上述自定义lightgbm模型的配置文件中的 model 字段,其中 module_path 是模块路径, class 是类名, args 是传递到__init__方法中的超参数。字段中的所有参数都通过 __init__ 中的 **kwargs 传递给 self._params ,除了 loss = mse

    model:
        class: LGBModel
        module_path: qlib.contrib.model.gbdt
        args:
            loss: mse
            colsample_bytree: 0.8879
            learning_rate: 0.0421
            subsample: 0.8789
            lambda_l1: 205.6999
            lambda_l2: 580.9768
            max_depth: 8
            num_leaves: 210
            num_threads: 20
    

用户可以在 examples/benchmarks 中找到 Model 的基准配置文件。不同模型的所有配置都列在相应的模型文件夹下。

模型测试

假设配置文件为 examples/benchmarks/LightGBM/workflow_config_lightgbm.yaml ,用户可以运行以下命令来测试自定义模型:

cd examples  # 避免在包含 `qlib` 的目录下运行程序
qrun benchmarks/LightGBM/workflow_config_lightgbm.yaml

备注

qrunQlib 的内置命令。

此外,Model 也可以作为一个单独的模块进行测试。在 examples/workflow_by_code.ipynb 中给出了一个示例。

参考

如需了解更多关于 Forecast Model 的信息,请参阅 Forecast Model: Model Training & PredictionModel API