Qlib 记录器:实验管理

简介

Qlib 包含一个名为 QlibRecorder 的实验管理系统,旨在帮助用户高效地处理实验和分析结果。

该系统包含三个组件:

  • ExperimentManager

    管理实验的类。

  • Experiment

    实验类,每个实例负责单个实验。

  • Recorder

    记录器类,每个实例负责单个运行记录。

以下是系统结构的概览:

ExperimentManager
    - Experiment 1
        - Recorder 1
        - Recorder 2
        - ...
    - Experiment 2
        - Recorder 1
        - Recorder 2
        - ...
    - ...

此实验管理系统定义了一组接口,并提供了基于机器学习平台 MLFlow 的具体实现 MLflowExpManager (链接)。

如果用户将 ExpManager 的实现设置为 MLflowExpManager,则可以使用命令 mlflow ui 可视化和检查实验结果。有关更多信息,请参阅 此处 的相关文档。

Qlib 记录器

QlibRecorder 为用户提供了使用实验管理系统的高级 API。这些接口封装在 Qlib 中的变量 R 中,用户可以直接使用 R 与系统交互。以下命令展示了如何在 Python 中导入 R

from qlib.workflow import R

QlibRecorder 包含多个常用 API,用于在工作流中管理 实验记录器。有关更多可用 API,请参阅以下关于 实验管理器实验记录器 的部分。

以下是 QlibRecorder 的可用接口:

class qlib.workflow.__init__.QlibRecorder(exp_manager: ExpManager)

用于管理实验的全局系统。

__init__(exp_manager: ExpManager)
start(*, experiment_id: str | None = None, experiment_name: str | None = None, recorder_id: str | None = None, recorder_name: str | None = None, uri: str | None = None, resume: bool = False)

启动实验的方法。此方法只能在Python的`with`语句中调用。示例代码如下:

# 启动新实验和记录器
with R.start(experiment_name='test', recorder_name='recorder_1'):
    model.fit(dataset)
    R.log...
    ... # 其他操作

# 恢复之前的实验和记录器
with R.start(experiment_name='test', recorder_name='recorder_1', resume=True): # 如果用户想恢复记录器,必须指定完全相同的实验和记录器名称
    ... # 其他操作

参数

experiment_idstr

要启动的实验ID

experiment_namestr

要启动的实验名称

recorder_idstr

实验下要启动的记录器ID

recorder_namestr

实验下要启动的记录器名称

uristr

实验的跟踪URI,所有artifacts/metrics等将存储在此处 默认URI设置在qlib.config中。注意此uri参数不会更改配置文件中的设置 因此下次在同一实验中调用此函数时,用户必须指定相同的值,否则可能出现URI不一致

resumebool

是否恢复指定名称的记录器

start_exp(*, experiment_id=None, experiment_name=None, recorder_id=None, recorder_name=None, uri=None, resume=False)

Lower level method for starting an experiment. When use this method, one should end the experiment manually and the status of the recorder may not be handled properly. Here is the example code:

R.start_exp(experiment_name='test', recorder_name='recorder_1')
... # further operations
R.end_exp('FINISHED') or R.end_exp(Recorder.STATUS_S)
参数:
  • experiment_id (str) -- id of the experiment one wants to start.

  • experiment_name (str) -- the name of the experiment to be started

  • recorder_id (str) -- id of the recorder under the experiment one wants to start.

  • recorder_name (str) -- name of the recorder under the experiment one wants to start.

  • uri (str) -- the tracking uri of the experiment, where all the artifacts/metrics etc. will be stored. The default uri are set in the qlib.config.

  • resume (bool) -- whether to resume the specific recorder with given name under the given experiment.

返回类型:

An experiment instance being started.

end_exp(recorder_status='FINISHED')

Method for ending an experiment manually. It will end the current active experiment, as well as its active recorder with the specified status type. Here is the example code of the method:

R.start_exp(experiment_name='test')
... # further operations
R.end_exp('FINISHED') or R.end_exp(Recorder.STATUS_S)
参数:

status (str) -- The status of a recorder, which can be SCHEDULED, RUNNING, FINISHED, FAILED.

search_records(experiment_ids, **kwargs)

Get a pandas DataFrame of records that fit the search criteria.

The arguments of this function are not set to be rigid, and they will be different with different implementation of ExpManager in Qlib. Qlib now provides an implementation of ExpManager with mlflow, and here is the example code of the method with the MLflowExpManager:

R.log_metrics(m=2.50, step=0)
records = R.search_records([experiment_id], order_by=["metrics.m DESC"])
参数:
  • experiment_ids (list) -- list of experiment IDs.

  • filter_string (str) -- filter query string, defaults to searching all runs.

  • run_view_type (int) -- one of enum values ACTIVE_ONLY, DELETED_ONLY, or ALL (e.g. in mlflow.entities.ViewType).

  • max_results (int) -- the maximum number of runs to put in the dataframe.

  • order_by (list) -- list of columns to order by (e.g., “metrics.rmse”).

返回:

  • A pandas.DataFrame of records, where each metric, parameter, and tag

  • are expanded into their own columns named metrics., params.*, and tags.**

  • respectively. For records that don't have a particular metric, parameter, or tag, their

  • value will be (NumPy) Nan, None, or None respectively.

list_experiments()

Method for listing all the existing experiments (except for those being deleted.)

exps = R.list_experiments()
返回类型:

A dictionary (name -> experiment) of experiments information that being stored.

list_recorders(experiment_id=None, experiment_name=None)

列出指定ID或名称实验的所有记录器的方法。

如果用户未提供实验ID或名称,此方法将尝试获取默认实验并列出其所有记录器。 如果默认实验不存在,方法将先创建默认实验,然后在其下创建新记录器。 (关于默认实验的更多信息请参考`此处 <../component/recorder.html#qlib.workflow.exp.Experiment>`__)。

示例代码:

recorders = R.list_recorders(experiment_name='test')

参数

experiment_idstr

实验ID

experiment_namestr

实验名称

返回

存储的记录器信息字典(id -> recorder)

get_exp(*, experiment_id=None, experiment_name=None, create: bool = True, start: bool = False) Experiment

根据ID或名称获取实验的方法。当`create`参数设为True时,如果找不到有效实验,此方法将自动创建一个;否则仅获取特定实验或抛出错误。

  • 当'create'为True时:

    • 存在`active experiment`:
      • 未指定ID或名称,返回当前活动实验

      • 指定了ID或名称,返回指定实验。若无此实验,则创建新实验

    • 不存在`active experiment`:
      • 未指定ID或名称,创建默认实验并设为活动状态

      • 指定了ID或名称,返回指定实验。若无此实验,则创建新实验或默认实验

  • 当'create'为False时:

    • 存在`active experiment`:
      • 未指定ID或名称,返回当前活动实验

      • 指定了ID或名称,返回指定实验。若无此实验,抛出错误

    • 不存在`active experiment`:
      • 未指定ID或名称。若默认实验存在则返回,否则抛出错误

      • 指定了ID或名称,返回指定实验。若无此实验,抛出错误

使用示例:

# 示例1
with R.start('test'):
    exp = R.get_exp()
    recorders = exp.list_recorders()

# 示例2
with R.start('test'):
    exp = R.get_exp(experiment_name='test1')

# 示例3
exp = R.get_exp() -> 获取默认实验

# 示例4
exp = R.get_exp(experiment_name='test')

# 示例5
exp = R.get_exp(create=False) -> 若存在则返回默认实验

参数

experiment_idstr

实验ID

experiment_namestr

实验名称

createboolean

决定当实验不存在时是否自动创建新实验

startbool

当为True时,如果实验未启动(未激活),将自动启动 专为R.log_params自动启动实验设计

返回

具有给定ID或名称的实验实例

delete_exp(experiment_id=None, experiment_name=None)

删除指定ID或名称实验的方法。必须提供至少ID或名称中的一个,否则会出错。

示例代码:

R.delete_exp(experiment_name='test')

参数

experiment_idstr

实验ID

experiment_namestr

实验名称

get_uri()

获取当前实验管理器URI的方法。

示例代码:

uri = R.get_uri()

返回

当前实验管理器的URI

set_uri(uri: str | None)

重置当前实验管理器**默认**URI的方法。

注意:

  • 当URI引用文件路径时,请使用绝对路径而非类似"~/mlruns/"的字符串 后端不支持此类字符串

uri_context(uri: str)

临时设置exp_manager的**default_uri**为指定URI

注意: - 请参考`set_uri`中的注意事项

参数

uriText

临时URI

get_recorder(*, recorder_id=None, recorder_name=None, experiment_id=None, experiment_name=None) Recorder

获取记录器的方法。

  • 存在`active recorder`时:

    • 未指定ID或名称,返回当前活动记录器

    • 指定了ID或名称,返回指定记录器

  • 不存在`active recorder`时:

    • 未指定ID或名称,抛出错误

    • 指定了ID或名称,必须同时提供对应的experiment_name才能返回指定记录器,否则抛出错误

获取的记录器可用于后续操作如`save_object`、load_objectlog_params`log_metrics`等。

使用示例:

# 示例1
with R.start(experiment_name='test'):
    recorder = R.get_recorder()

# 示例2
with R.start(experiment_name='test'):
    recorder = R.get_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d')

# 示例3
recorder = R.get_recorder() -> 错误

# 示例4
recorder = R.get_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d') -> 错误

# 示例5
recorder = R.get_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d', experiment_name='test')

用户可能关心的问题: - 问:如果多个记录器符合查询条件(如使用experiment_name查询),会返回哪个记录器? - 答:如果使用mlflow后端,将返回具有最新`start_time`的记录器。因为MLflow的`search_runs`函数保证了这一点

参数

recorder_idstr

记录器ID

recorder_namestr

记录器名称

experiment_namestr

实验名称

返回

记录器实例

delete_recorder(recorder_id=None, recorder_name=None)

删除指定ID或名称记录器的方法。必须提供至少ID或名称中的一个,否则会出错。

示例代码:

R.delete_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d')

参数

recorder_idstr

记录器ID

recorder_namestr

记录器名称

save_objects(local_path=None, artifact_path=None, **kwargs: Dict[str, Any])

Method for saving objects as artifacts in the experiment to the uri. It supports either saving from a local file/directory, or directly saving objects. User can use valid python's keywords arguments to specify the object to be saved as well as its name (name: value).

In summary, this API is designs for saving objects to the experiments management backend path, 1. Qlib provide two methods to specify objects - Passing in the object directly by passing with **kwargs (e.g. R.save_objects(trained_model=model)) - Passing in the local path to the object, i.e. local_path parameter. 2. artifact_path represents the the experiments management backend path

  • If active recorder exists: it will save the objects through the active recorder.

  • If active recorder not exists: the system will create a default experiment, and a new recorder and save objects under it.

备注

If one wants to save objects with a specific recorder. It is recommended to first get the specific recorder through get_recorder API and use the recorder the save objects. The supported arguments are the same as this method.

Here are some use cases:

# Case 1
with R.start(experiment_name='test'):
    pred = model.predict(dataset)
    R.save_objects(**{"pred.pkl": pred}, artifact_path='prediction')
    rid = R.get_recorder().id
...
R.get_recorder(recorder_id=rid).load_object("prediction/pred.pkl")  #  after saving objects, you can load the previous object with this api

# Case 2
with R.start(experiment_name='test'):
    R.save_objects(local_path='results/pred.pkl', artifact_path="prediction")
    rid = R.get_recorder().id
...
R.get_recorder(recorder_id=rid).load_object("prediction/pred.pkl")  #  after saving objects, you can load the previous object with this api
参数:
  • local_path (str) -- if provided, them save the file or directory to the artifact URI.

  • artifact_path (str) -- the relative path for the artifact to be stored in the URI.

  • **kwargs (Dict[Text, Any]) -- the object to be saved. For example, {"pred.pkl": pred}

load_object(name: str)

从URI中实验的artifacts加载对象的方法。

log_params(**kwargs)

在实验过程中记录参数的方法。除了使用``R``外,也可以通过`get_recorder`API获取特定记录器后进行记录。

  • 存在`active recorder`:通过活动记录器记录参数

  • 不存在`active recorder`:系统将创建默认实验和新记录器,并在其下记录参数

使用示例:

# 示例1
with R.start('test'):
    R.log_params(learning_rate=0.01)

# 示例2
R.log_params(learning_rate=0.01)

参数

关键字参数:

name1=value1, name2=value2, ...

log_metrics(step=None, **kwargs)

在实验过程中记录指标的方法。除了使用``R``外,也可以通过`get_recorder`API获取特定记录器后进行记录。

  • 存在`active recorder`:通过活动记录器记录指标

  • 不存在`active recorder`:系统将创建默认实验和新记录器,并在其下记录指标

使用示例:

# 示例1
with R.start('test'):
    R.log_metrics(train_loss=0.33, step=1)

# 示例2
R.log_metrics(train_loss=0.33, step=1)

参数

关键字参数:

name1=value1, name2=value2, ...

log_artifact(local_path: str, artifact_path: str | None = None)

将本地文件或目录记录为当前活动运行的artifact

  • 存在`active recorder`:通过活动记录器设置标签

  • 不存在`active recorder`:系统将创建默认实验和新记录器,并在其下设置标签

参数

local_pathstr

要写入的文件路径

artifact_pathOptional[str]

如果提供,则为``artifact_uri``中要写入的目录

download_artifact(path: str, dst_path: str | None = None) str

Download an artifact file or directory from a run to a local directory if applicable, and return a local path for it.

参数:
  • path (str) -- Relative source path to the desired artifact.

  • dst_path (Optional[str]) -- Absolute path of the local filesystem destination directory to which to download the specified artifacts. This directory must already exist. If unspecified, the artifacts will either be downloaded to a new uniquely-named directory on the local filesystem.

返回:

Local path of desired artifact.

返回类型:

str

set_tags(**kwargs)

为记录器设置标签的方法。除了使用``R``外,也可以通过`get_recorder`API获取特定记录器后进行设置。

  • 存在`active recorder`:通过活动记录器设置标签

  • 不存在`active recorder`:系统将创建默认实验和新记录器,并在其下设置标签

使用示例:

# 示例1
with R.start('test'):
    R.set_tags(release_version="2.2.0")

# 示例2
R.set_tags(release_version="2.2.0")

参数

关键字参数:

name1=value1, name2=value2, ...

实验管理器

Qlib 中的 ExpManager 模块负责管理不同的实验。ExpManager 的大多数 API 与 QlibRecorder 相似,其中最重要的 API 是 get_exp 方法。用户可以直接参考上文文档了解如何使用 get_exp 方法的详细信息。

class qlib.workflow.expm.ExpManager(uri: str, default_exp_name: str | None)

这是用于管理实验的`ExpManager`类。API设计类似于mlflow。 (链接: https://mlflow.org/docs/latest/python_api/mlflow.html)

ExpManager`预期是一个单例(同时,我们可以有多个具有不同uri的`Experiment。用户可以从不同的uri获取不同的实验,然后比较它们的记录)。全局配置(即`C`)也是一个单例。

因此我们尝试将它们对齐。它们共享同一个变量,称为**默认uri**。有关变量共享的详细信息,请参阅`ExpManager.default_uri`。

当用户开始一个实验时,用户可能希望将uri设置为特定的uri(在此期间它将覆盖**默认uri**),然后取消设置**特定uri**并回退到**默认uri**。`ExpManager._active_exp_uri`就是那个**特定uri**。

__init__(uri: str, default_exp_name: str | None)
start_exp(*, experiment_id: str | None = None, experiment_name: str | None = None, recorder_id: str | None = None, recorder_name: str | None = None, uri: str | None = None, resume: bool = False, **kwargs) Experiment

启动一个实验。该方法首先获取或创建一个实验,然后将其设置为活动状态。

`_active_exp_uri`的维护包含在start_exp中,剩余实现应包含在子类的_end_exp中

参数

experiment_idstr

活动实验的ID

experiment_namestr

活动实验的名称

recorder_idstr

要启动的记录器ID

recorder_namestr

要启动的记录器名称

uristr

当前跟踪URI

resumeboolean

是否恢复实验和记录器

返回

一个活动实验对象

end_exp(recorder_status: str = 'SCHEDULED', **kwargs)

结束一个活动实验

`_active_exp_uri`的维护包含在end_exp中,剩余实现应包含在子类的_end_exp中

参数

experiment_namestr

活动实验的名称

recorder_statusstr

实验活动记录器的状态

create_exp(experiment_name: str | None = None)

创建一个实验

参数

experiment_namestr

实验名称,必须唯一

返回

一个实验对象

raises ExpAlreadyExistError:

当实验已存在时抛出

search_records(experiment_ids=None, **kwargs)

获取符合实验搜索条件的记录DataFrame 输入为用户想要应用的搜索条件

返回

一个pandas.DataFrame记录,其中每个指标、参数和标签 分别展开到名为metrics.*、params.*和tags.*的列中 对于没有特定指标、参数或标签的记录,它们的值将分别为(NumPy)Nan、None或None

get_exp(*, experiment_id=None, experiment_name=None, create: bool = True, start: bool = False)

检索一个实验。该方法包括获取活动实验,以及获取或创建特定实验

当用户指定实验ID和名称时,方法将尝试返回特定实验 当用户未提供记录器ID或名称时,方法将尝试返回当前活动实验 `create`参数决定如果实验尚未创建,方法是否根据用户规范自动创建新实验

  • 如果`create`为True:

    • 如果`活动实验`存在:

      • 未指定ID或名称,返回活动实验

      • 如果指定了ID或名称,返回指定实验。如果未找到,则使用给定ID或名称创建新实验。如果`start`设为True,实验将被设置为活动状态

    • 如果`活动实验`不存在:

      • 未指定ID或名称,创建默认实验

      • 如果指定了ID或名称,返回指定实验。如果未找到,则使用给定ID或名称创建新实验。如果`start`设为True,实验将被设置为活动状态

  • 如果`create`为False:

    • 如果`活动实验`存在:

      • 未指定ID或名称,返回活动实验

      • 如果指定了ID或名称,返回指定实验。如果未找到,抛出错误

    • 如果`活动实验`不存在:

      • 未指定ID或名称。如果默认实验存在则返回,否则抛出错误

      • 如果指定了ID或名称,返回指定实验。如果未找到,抛出错误

参数

experiment_idstr

要返回的实验ID

experiment_namestr

要返回的实验名称

createboolean

如果实验尚未创建,是否创建它

startboolean

如果创建了新实验,是否启动它

返回

一个实验对象

delete_exp(experiment_id=None, experiment_name=None)

删除一个实验

参数

experiment_idstr

实验ID

experiment_namestr

实验名称

property default_uri

从qlib.config.C获取默认跟踪URI

property uri

获取默认跟踪URI或当前URI

返回

跟踪URI字符串

list_experiments()

列出所有现有实验

返回

存储的实验信息字典(name -> experiment)

有关其他接口(如 create_expdelete_exp),请参阅 实验管理器 API

实验

Experiment 类专门负责单个实验,它将处理与实验相关的所有操作。包括 开始结束 实验等基本方法。此外,还提供与 记录器 相关的方法:如 get_recorderlist_recorders

class qlib.workflow.exp.Experiment(id, name)

这是用于运行每个实验的`Experiment`类。API设计类似于mlflow。 (链接: https://mlflow.org/docs/latest/python_api/mlflow.html)

__init__(id, name)
start(*, recorder_id=None, recorder_name=None, resume=False)

开始实验并设置为活动状态。此方法还将启动一个新的记录器。

参数

recorder_idstr

要创建的记录器ID

recorder_namestr

要创建的记录器名称

resumebool

是否恢复第一个记录器

返回

一个活动的记录器。

end(recorder_status='SCHEDULED')

结束实验。

参数

recorder_statusstr

结束时记录器要设置的状态(SCHEDULED, RUNNING, FINISHED, FAILED)。

create_recorder(recorder_name=None)

为每个实验创建记录器

参数:

recorder_name (str) -- 要创建记录器的名称

返回类型:

记录器对象

search_records(**kwargs)

获取符合实验搜索条件的记录DataFrame 输入为用户想要应用的搜索条件

返回:

  • 包含记录的pandas.DataFrame,其中每个指标、参数和标签

  • 都被展开到名为metrics.、params.*和tags.*的列中*

  • 对于没有特定指标、参数或标签的记录,它们的值将分别为(NumPy)Nan、None或None

delete_recorder(recorder_id)

为每个实验创建记录器。

参数

recorder_idstr

要删除的记录器ID。

get_recorder(recorder_id=None, recorder_name=None, create: bool = True, start: bool = False) Recorder

为用户检索记录器。当用户指定记录器ID和名称时,该方法会尝试返回特定的记录器。 当用户未提供记录器ID或名称时,该方法会尝试返回当前活动记录器。 `create`参数决定如果记录器尚未创建,该方法是否会根据用户规范自动创建新记录器。

  • 如果`create`为True:

    • 如果`活动记录器`存在:

      • 未指定ID或名称,返回活动记录器。

      • 如果指定了ID或名称,返回指定的记录器。如果未找到对应实验,则使用给定的ID或名称创建新记录器。如果`start`设为True,则将记录器设为活动状态。

    • 如果`活动记录器`不存在:

      • 未指定ID或名称,创建新记录器。

      • 如果指定了ID或名称,返回指定的实验。如果未找到对应实验,则使用给定的ID或名称创建新记录器。如果`start`设为True,则将记录器设为活动状态。

  • 如果`create`为False:

    • 如果`活动记录器`存在:

      • 未指定ID或名称,返回活动记录器。

      • 如果指定了ID或名称,返回指定的记录器。如果未找到对应实验,则抛出错误。

    • 如果`活动记录器`不存在:

      • 未指定ID或名称,抛出错误。

      • 如果指定了ID或名称,返回指定的记录器。如果未找到对应实验,则抛出错误。

参数

recorder_idstr

要删除的记录器ID。

recorder_namestr

要删除的记录器名称。

createboolean

如果记录器尚未创建,则创建它。

startboolean

如果创建了新记录器,则启动它。

返回

记录器对象。

list_recorders(rtype: Literal['dict', 'list'] = 'dict', **flt_kwargs) List[Recorder] | Dict[str, Recorder]

列出本实验的所有现有记录器。调用此方法前请先获取实验实例。 如果想使用`R.list_recorders()`方法,请参考`QlibRecorder`中的相关API文档。

flt_kwargsdict

按条件过滤记录器 例如:list_recorders(status=Recorder.STATUS_FI)

返回

返回类型取决于`rtype`
如果`rtype` == "dict":

存储的记录器信息的字典(id -> recorder)。

如果`rtype` == "list":

记录器列表。

有关其他接口(如 search_recordsdelete_recorder),请参阅 实验 API

Qlib 还提供了一个默认的 Experiment,当用户使用 log_metricsget_exp 等 API 时,会在特定情况下创建和使用该默认实验。如果使用默认 Experiment,运行 Qlib 时会记录相关信息。用户可以在 Qlib 的配置文件中或 Qlib初始化 过程中更改默认 Experiment 的名称,默认名称为 'Experiment'。

记录器

Recorder 类负责单个记录器。它将处理单个运行的详细操作,如 log_metricslog_params。它旨在帮助用户轻松跟踪运行过程中生成的结果和内容

以下是一些未包含在 QlibRecorder 中的重要 API:

class qlib.workflow.recorder.Recorder(experiment_id, name)

This is the Recorder class for experiment recording, with API design similar to mlflow. (Link: https://mlflow.org/docs/latest/python_api/mlflow.html)

The recorder's status can be SCHEDULED, RUNNING, FINISHED or FAILED.

__init__(experiment_id, name)
save_objects(local_path=None, artifact_path=None, **kwargs)

保存对象如预测文件或模型检查点到artifact URI。用户 可以通过关键字参数(name:value)保存对象。

请参考qlib.workflow:R.save_objects的文档

参数

local_pathstr

如果提供,则将文件或目录保存到artifact URI。

artifact_path=Nonestr

存储在URI中的artifact的相对路径。

load_object(name)

加载对象如预测文件或模型检查点。

参数

namestr

要加载的文件名。

返回

保存的对象。

start_run()

启动或恢复记录器。返回值可用作`with`块中的上下文管理器; 否则必须调用end_run()来终止当前运行。(参见mlflow中的`ActiveRun`类)

返回

一个活动运行对象(例如mlflow.ActiveRun对象)。

end_run()

结束一个活动的记录器。

log_params(**kwargs)

为当前运行记录一批参数。

参数

关键字参数

要记录为参数的键值对。

log_metrics(step=None, **kwargs)

为当前运行记录多个指标。

参数

关键字参数

要记录为指标的键值对。

log_artifact(local_path: str, artifact_path: str | None = None)

将本地文件或目录记录为当前活动运行的artifact。

参数

local_pathstr

要写入的文件路径。

artifact_pathOptional[str]

如果提供,则写入到``artifact_uri``中的目录。

set_tags(**kwargs)

为当前运行记录一批标签。

参数

关键字参数

要记录为标签的键值对。

delete_tags(*keys)

从运行中删除一些标签。

参数

keys键的字符串序列

要删除的所有标签名称。

list_artifacts(artifact_path: str = None)

列出记录器的所有artifacts。

参数

artifact_pathstr

artifact存储在URI中的相对路径。

返回

存储的artifacts信息列表(名称、路径等)。

download_artifact(path: str, dst_path: str | None = None) str

从运行中下载artifact文件或目录到本地目录(如果适用), 并返回其本地路径。

参数

pathstr

目标artifact的相对源路径。

dst_pathOptional[str]

本地文件系统目标目录的绝对路径,用于 下载指定的artifacts。该目录必须已存在。 如果未指定,artifacts将被下载到本地文件系统上 一个唯一命名的新目录中。

返回

str

目标artifact的本地路径。

list_metrics()

列出记录器的所有指标。

返回

存储的指标字典。

list_params()

列出记录器的所有参数。

返回

存储的参数字典。

list_tags()

列出记录器的所有标签。

返回

存储的标签字典。

有关其他接口(如 save_objectsload_object),请参阅 记录器 API

记录模板

RecordTemp 类用于以特定格式生成实验结果,如 IC 和回测结果。我们提供了三种不同的 记录模板 类:

  • SignalRecord:此类生成模型的 预测 结果。

  • SigAnaRecord:此类生成模型的 ICICIRRank ICRank ICIR

以下是 SigAnaRecord 中实现的简单示例,用户如果想使用自己的预测和标签计算 IC、Rank IC、多空收益,可以参考此示例。

from qlib.contrib.eva.alpha import calc_ic, calc_long_short_return

ic, ric = calc_ic(pred.iloc[:, 0], label.iloc[:, 0])
long_short_r, long_avg_r = calc_long_short_return(pred.iloc[:, 0], label.iloc[:, 0])
  • PortAnaRecord:此类生成 回测 结果。有关 回测 以及可用 策略 的详细信息,用户可以参考 策略回测

以下是 PortAnaRecord 中实现的简单示例,用户如果想基于自己的预测和标签进行回测,可以参考此示例。

from qlib.contrib.strategy.strategy import TopkDropoutStrategy
from qlib.contrib.evaluate import (
    backtest as normal_backtest,
    risk_analysis,
)

# 回测
STRATEGY_CONFIG = {
    "topk": 50,
    "n_drop": 5,
}
BACKTEST_CONFIG = {
    "limit_threshold": 0.095,
    "account": 100000000,
    "benchmark": BENCHMARK,
    "deal_price": "close",
    "open_cost": 0.0005,
    "close_cost": 0.0015,
    "min_cost": 5,
}

strategy = TopkDropoutStrategy(**STRATEGY_CONFIG)
report_normal, positions_normal = normal_backtest(pred_score, strategy=strategy,** BACKTEST_CONFIG)

# 分析
analysis = dict()
analysis["excess_return_without_cost"] = risk_analysis(report_normal["return"] - report_normal["bench"])
analysis["excess_return_with_cost"] = risk_analysis(report_normal["return"] - report_normal["bench"] - report_normal["cost"])
analysis_df = pd.concat(analysis)  # type: pd.DataFrame
print(analysis_df)

有关 API 的更多信息,请参阅 记录模板 API

已知限制

  • Python 对象基于 pickle 保存,当转储对象和加载对象的环境不同时可能会导致问题。