设置 AutoML,通过 SDK 和 CLI 训练时序预测模型

适用范围:Azure CLI ml 扩展 v2(最新版)Python SDK azure-ai-ml v2(最新版)

在本文中,你将了解如何使用 Azure 机器学习 Python SDK 中的 Azure 机器学习自动化 ML 为时序预测设置 AutoML。

为此,需要:

  • 准备要训练的数据。
  • 配置预测作业中的特定时序参数。
  • 使用组件和管道协调训练、推理和模型评估。

要获得低代码体验,请参阅教程:使用自动化机器学习预测需求,查看 Azure 机器学习工作室中使用自动化 ML 的时序预测示例。

AutoML 使用标准机器学习模型以及知名的时序模型来创建预测。 我们的方法结合了目标变量的历史信息、输入数据中用户提供的特征和经过自动工程的特征。 然后,模型搜索算法会努力查找预测准确度最佳的模型。 有关更多详细信息,请参阅有关预测方法模型搜索的文章。

先决条件

在本文中,你需要:

训练和验证数据

AutoML 预测的输入数据必须包含表格格式的有效时序。 每个变量在数据表中必须具有其自己的对应列。 AutoML 至少需要两列:表示时间轴的时间列和要预测的数量的目标列。 其他列可用作预测器。 有关更多详细信息,请参阅 AutoML 如何使用数据

重要

在训练用于预测未来值的模型时,请确保在针对预期范围运行预测时可使用训练中用到的所有特征。

例如,当前股票价格的特征可能大幅提高训练的准确度。 但是,如果你打算使用较长的时间范围进行预测,则可能没法准确预测与未来的时序点相对应的未来股价值,模型准确性也会受到影响。

AutoML 预测作业要求将训练数据表示为 MLTable 对象。 MLTable 指定了数据源和加载数据的步骤。 有关详细信息和用例,请参阅 MLTable 操作指南。 举一个简单的例子,假设你的训练数据包含在本地目录 ./train_data/timeseries_train.csv 中的 CSV 文件中。

可使用 mltable Python SDK 创建 MLTable,如以下示例所示:

import mltable

paths = [
    {'file': './train_data/timeseries_train.csv'}
]

train_table = mltable.from_delimited_files(paths)
train_table.save('./train_data')

此代码会创建一个新文件 ./train_data/MLTable,其中包含文件格式和加载说明。

现在,使用 Azure 机器学习 Python SDK 定义启动训练作业所需的输入数据对象,如下所示:

from azure.ai.ml.constants import AssetTypes
from azure.ai.ml import Input

# Training MLTable defined locally, with local data to be uploaded
my_training_data_input = Input(
    type=AssetTypes.MLTABLE, path="./train_data"
)

通过创建 MLTable 并指定输入的验证数据,用类似的方式指定验证数据。 或者,如果未提供验证数据,AutoML 将自动根据训练数据创建交叉验证拆分,以用于模型选择。 有关更多详细信息,请参阅有关预测模型选择的文章。 有关成功训练预测模型所需训练数据量的详细信息,请参阅训练数据长度要求

详细了解 autoML 如何应用交叉验证来防止过度拟合

用于运行试验的计算环境

AutoML 使用 Azure 机器学习计算(完全托管的计算资源)来运行训练作业。 在以下示例中,创建了名为 cpu-compute 的计算群集:

from azure.ai.ml.entities import AmlCompute

# specify aml compute name.
cpu_compute_target = "cpu-cluster"

try:
    ml_client.compute.get(cpu_compute_target)
except Exception:
    print("Creating a new cpu compute target...")
    compute = AmlCompute(
        name=cpu_compute_target, size="STANDARD_D2_V2", min_instances=0, max_instances=4
    )
    ml_client.compute.begin_create_or_update(compute).result()

配置试验

使用 automl 工厂函数在 Python SDK 中配置预测作业。 以下示例演示如何通过设置主要指标和对训练运行设置限制来创建预测作业

from azure.ai.ml import automl

# note that the below is a code snippet -- you might have to modify the variable values to run it successfully
forecasting_job = automl.forecasting(
    compute="cpu-compute",
    experiment_name="sdk-v2-automl-forecasting-job",
    training_data=my_training_data_input,
    target_column_name=target_column_name,
    primary_metric="normalized_root_mean_squared_error",
    n_cross_validations="auto",
)

# Limits are all optional
forecasting_job.set_limits(
    timeout_minutes=120,
    trial_timeout_minutes=30,
    max_concurrent_trials=4,
)

预测作业设置

预测任务具有许多特定于预测的设置。 在这些设置中,最基本的是训练数据中时间列的名称以及预测范围。

使用 ForecastingJob 方法配置以下设置:

# Forecasting specific configuration
forecasting_job.set_forecast_settings(
    time_column_name=time_column_name,
    forecast_horizon=24
)

时间列名称是必需的设置,并且通常应根据预测方案设置预测范围。 如果数据包含多个时序,则可以指定时序 ID 列的名称。 这些列在分组时定义单个序列。 例如,假设数据包含不同商店和品牌的每小时销售额。 以下示例演示了如何设置时序 ID 列(假设数据包含名为“商店”和“品牌”的列):

# Forecasting specific configuration
# Add time series IDs for store and brand
forecasting_job.set_forecast_settings(
    ...,  # other settings
    time_series_id_column_names=['store', 'brand']
)

如果未指定,AutoML 会尝试自动检测数据中的时序 ID 列。

其他设置是可选的,下一部分将进行介绍。

可选的预测作业设置

可选配置可用于预测任务,例如,启用深度学习和指定目标滚动窗口聚合。 有关完整的参数列表,可查看预测参考文档

模型搜索设置

通过两个可选设置可以控制 AutoML 搜索最佳模型的模型空间,即 allowed_training_algorithmsblocked_training_algorithms。 要将搜索空间限制为一组给定的模型类,请使用 allowed_training_algorithms 参数,如以下示例所示:

# Only search ExponentialSmoothing and ElasticNet models
forecasting_job.set_training(
    allowed_training_algorithms=["ExponentialSmoothing", "ElasticNet"]
)

在这种情况下,预测作业将搜索指数平滑和弹性网络模型类。 要从搜索空间中移除一组给定的模型类,请使用blocked_training_algorithms,如以下示例所示:

# Search over all model classes except Prophet
forecasting_job.set_training(
    blocked_training_algorithms=["Prophet"]
)

现在,作业将搜索 Prophet 之外的所有模型类。 有关 allowed_training_algorithmsblocked_training_algorithms 中接受的预测模型名的列表,请查看训练属性参考文档。 allowed_training_algorithmsblocked_training_algorithms 中的任何一个(但不能是两个)都可应用于训练运行。

启用深度学习

AutoML 随附了名为 TCNForecaster 的自定义深度神经网络 (DNN) 模型。 此模型是一个时态卷积网络或 TCN,可用于将常见的图像处理任务方法应用于时序建模。 也就是说,一维“因果”卷积构成了网络的主干,使模型能够在训练历史的长时间内学习复杂的模式。 有关更多详细信息,请参阅 TCNForecaster 一文

Diagram showing major components of AutoML's TCNForecaster.

当训练历史记录中存在数千个或更多个观测时,与标准时序模型相比,TCNForecaster 通常可获得更高的准确度。 但由于其容量较高,训练和扫描 TCNForecaster 模型需要的时间也会较长。

可通过在训练配置中设置 enable_dnn_training 标志,在 AutoML 中启用 TCNForecaster,如下所示:

# Include TCNForecaster models in the model search
forecasting_job.set_training(
    enable_dnn_training=True
)

默认情况下,TCNForecaster 训练的限制是,对于每个模型试用,有一个计算节点和一个 GPU(如果可用)。 对于大型数据方案,建议将每个 TCNForecaster 试用版分发到多个核心/GPU 和节点。 有关详细信息和代码示例,请参阅分布式训练文章部分。

若要为在 Azure 机器学习工作室中创建的 AutoML 试验启用 DNN,请参阅工作室 UI 操作指南中的任务类型设置

注意

  • 为使用 SDK 创建的试验启用 DNN 时,系统会禁用最佳模型说明
  • DNN 支持在自动化机器学习中预测,但不支持在 Databricks 中启动的运行。
  • 启用 DNN 训练后,建议使用 GPU 计算类型

滞后和滚动窗口特征

目标的最近值通常是预测模型中具有影响力的特征。 因此,AutoML 可创建时间滞后和滚动窗口聚合特征,从而可能提高模型准确度。

考虑一个提供了天气数据和历史需求的能源需求预测方案。 该表显示了最近三小时内应用窗口聚合后产生的特征工程。 根据定义的设置,在三个小时的滑动窗口上生成表示最小值、最大值、总和的列。 例如,对于 2017 年 9 月 8 日凌晨 4:00 有效的观测,使用 2017 年 9 月 8 日凌晨 1:00 至 3:00 的需求值计算最大值、最小值和总和值。 这个三小时的窗口将移位以填充其余行的数据。 有关更多详细信息和示例,请参阅滞后特征一文

target rolling window

可通过设置滚动窗口大小(在上一示例中为 3)和要创建的滞后顺序,为目标启用滞后和滚动窗口聚合特征。 还可使用 feature_lags 设置为特征启用滞后。 在以下示例中,我们将所有这些设置都设置为 auto,以便 AutoML 通过分析数据的相关结构自动确定设置:

forecasting_job.set_forecast_settings(
    ...,  # other settings
    target_lags='auto', 
    target_rolling_window_size='auto',
    feature_lags='auto'
)

短时序处理

如果数据点不足,无法执行模型开发的训练和验证阶段,自动化 ML 会将一个时序视为短时序。 有关长度要求的详细信息,请参阅训练数据长度要求

AutoML 可对短时序执行多个操作。 通过 short_series_handling_config 设置可以配置这些操作。 默认值为“auto”。下表描述了这些设置:

设置 说明
auto 短时序处理的默认值。
- 如果所有时序都是短时序,则填充数据。
- 如果并非所有时序都是短时序,则删除短时序。
pad 如果 short_series_handling_config = pad,则自动化 ML 会为找到的每个短时序添加随机值。 下面列出了列类型以及用于填充这些列的内容:
- 对象列,其中包含 NAN
- 数值列,其中包含 0
- 布尔/逻辑列,其中包含 False
- 目标列填充了白噪声。
drop 如果 short_series_handling_config = drop,则自动化 ML 会删除短时序,并且该短时序不会用于训练或预测。 对这些时序的预测将会返回 NAN。
None 不会填充或删除任何时序

在以下示例中,我们设置了短序列处理,以便将所有短时序填充到最小长度:

forecasting_job.set_forecast_settings(
    ...,  # other settings
    short_series_handling_config='pad'
)

警告

填充可能会影响生成的模型的准确度,因为我们引入人工数据来避免训练失败。 如果许多时序中都是短时序,你可能还会在可说明性结果中看到一些影响

频率和目标数据聚合

使用频率和数据聚合选项避免不规则数据导致的故障。 如果数据不遵循设定的时间节奏(例如每小时或每天),则数据是不规则的。 销售点数据是一个很好的不规则数据示例。 在这些情况下,AutoML 可以将数据聚合到所需的频率,然后根据聚合生成预测模型。

需要设置 frequencytarget_aggregate_function 设置来处理不规则的数据。 频率设置接受 Pandas DateOffset 字符串 作为输入。 聚合函数支持的值为:

函数 说明
sum  求目标值的总和
mean  求目标值的平均值
min 求目标的最小值
max 求目标的最大值
  • 目标列值将按照指定的操作进行聚合。 通常,sum 适用于大多数方案。
  • 数据中的数值预测器列会按总和、平均值、最小值和最大值进行聚合。 因此,自动 ML 会生成以聚合函数名称为后缀的新列,并应用所选的聚合运算。
  • 对于分类预测器列,数据会按模式(窗口中最醒目的类别)进行聚合。
  • 日期预测器列会按最小值、最大值和模式进行聚合。

以下示例将频率设置为每小时,并将聚合函数设置为 summation:

# Aggregate the data to hourly frequency
forecasting_job.set_forecast_settings(
    ...,  # other settings
    frequency='H',
    target_aggregate_function='sum'
)

自定义交叉验证设置

可以使用两个可自定义的设置来控制预测作业的交叉验证:折叠数 n_cross_validations 以及定义折叠之间的时间偏移量的步长 cv_step_size。 有关这些参数含义的详细信息,请参阅 预测模型选择。 默认情况下,AutoML 会根据数据的特征自动设置这两个设置,但高级用户可能需要手动设置它们。 例如,假设你有每日销售数据,并且希望验证设置包含五个折叠,而相邻折叠之间的偏移量为 7 天。 以下代码示例演示了如何设置以下项目:

from azure.ai.ml import automl

# Create a job with five CV folds
forecasting_job = automl.forecasting(
    ...,  # other training parameters
    n_cross_validations=5,
)

# Set the step size between folds to seven days
forecasting_job.set_forecast_settings(
    ...,  # other settings
    cv_step_size=7
)

自定义特征化

默认情况下,AutoML 使用工程特征扩充训练数据,以提高模型的准确度。 有关详细信息,请参阅自动化功能工程。 可使用预测作业的特征化方法来自定义某些预处理步骤。

下表中提供了支持的预测自定义项:

自定义 说明 选项
列用途更新 重写指定列的自动检测到的特征类型。 “Categorical”、“DateTime”、“Numeric”
转换器参数更新 更新指定的 imputer 的参数。 {"strategy": "constant", "fill_value": <value>}{"strategy": "median"}{"strategy": "ffill"}

例如,假设你有一个零售需求场景,其中数据包括价格、“特价”标志和产品类型。 以下示例演示了如何为这些功能设置自定义类型和 imputer:

from azure.ai.ml.automl import ColumnTransformer

# Customize imputation methods for price and is_on_sale features
# Median value imputation for price, constant value of zero for is_on_sale
transformer_params = {
    "imputer": [
        ColumnTransformer(fields=["price"], parameters={"strategy": "median"}),
        ColumnTransformer(fields=["is_on_sale"], parameters={"strategy": "constant", "fill_value": 0}),
    ],
}

# Set the featurization
# Ensure that product_type feature is interpreted as categorical
forecasting_job.set_featurization(
    mode="custom",
    transformer_params=transformer_params,
    column_name_and_types={"product_type": "Categorical"},
)

如果使用 Azure 机器学习工作室进行试验,请参阅如何在工作室中自定义特征化

提交预测作业

配置所有设置后,启动预测作业,如下所示:

# Submit the AutoML job
returned_job = ml_client.jobs.create_or_update(
    forecasting_job
)

print(f"Created job: {returned_job}")

# Get a URL for the job in the AML studio user interface
returned_job.services["Studio"].endpoint

提交作业后,AutoML 将预配计算资源,对输入数据应用特征化和其他准备步骤,然后开始扫描预测模型。 有关更多详细信息,请参阅有关预测方法模型搜索的文章。

使用组件和管道协调训练、推理和评估

重要

此功能目前处于公开预览状态。 此预览版在提供时没有附带服务级别协议,我们不建议将其用于生产工作负荷。 某些功能可能不受支持或者受限。

有关详细信息,请参阅适用于 Azure 预览版的补充使用条款

ML 工作流需要的可能不仅仅是训练。 可在 AzureML 中与训练作业一起协调的其他常见任务包括推理或检索对较新数据的模型预测,以及模型对具有已知目标值的测试集的准确度评估。 为了支持推理和评估任务,AzureML 提供了组件,这些组件是自包含的代码片段,在 AzureML 管道中执行一个步骤。

在以下示例中,我们从客户端注册表中检索组件代码:

from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential

# Get a credential for access to the AzureML registry
try:
    credential = DefaultAzureCredential()
    # Check if we can get token successfully.
    credential.get_token("https://management.chinacloudapi.cn/.default")
except Exception as ex:
    # Fall back to InteractiveBrowserCredential in case DefaultAzureCredential fails
    credential = InteractiveBrowserCredential()

# Create a client for accessing assets in the AzureML preview registry
ml_client_registry = MLClient(
    credential=credential,
    registry_name="azureml-preview"
)

# Create a client for accessing assets in the AzureML preview registry
ml_client_metrics_registry = MLClient(
    credential=credential,
    registry_name="azureml"
)

# Get an inference component from the registry
inference_component = ml_client_registry.components.get(
    name="automl_forecasting_inference",
    label="latest"
)

# Get a component for computing evaluation metrics from the registry
compute_metrics_component = ml_client_metrics_registry.components.get(
    name="compute_metrics",
    label="latest"
)

接下来,我们定义一个工厂函数,用于创建协调训练、推理和指标计算的管道。 有关训练设置的更多详细信息,请参阅训练配置部分。

from azure.ai.ml import automl
from azure.ai.ml.constants import AssetTypes
from azure.ai.ml.dsl import pipeline

@pipeline(description="AutoML Forecasting Pipeline")
def forecasting_train_and_evaluate_factory(
    train_data_input,
    test_data_input,
    target_column_name,
    time_column_name,
    forecast_horizon,
    primary_metric='normalized_root_mean_squared_error',
    cv_folds='auto'
):
    # Configure the training node of the pipeline
    training_node = automl.forecasting(
        training_data=train_data_input,
        target_column_name=target_column_name,
        primary_metric=primary_metric,
        n_cross_validations=cv_folds,
        outputs={"best_model": Output(type=AssetTypes.MLFLOW_MODEL)},
    )

    training_node.set_forecasting_settings(
        time_column_name=time_column_name,
        forecast_horizon=max_horizon,
        frequency=frequency,
        # other settings
        ... 
    )
    
    training_node.set_training(
        # training parameters
        ...
    )
    
    training_node.set_limits(
        # limit settings
        ...
    )

    # Configure the inference node to make rolling forecasts on the test set
    inference_node = inference_component(
        test_data=test_data_input,
        model_path=training_node.outputs.best_model,
        target_column_name=target_column_name,
        forecast_mode='rolling',
        forecast_step=1
    )

    # Configure the metrics calculation node
    compute_metrics_node = compute_metrics_component(
        task="tabular-forecasting",
        ground_truth=inference_node.outputs.inference_output_file,
        prediction=inference_node.outputs.inference_output_file,
        evaluation_config=inference_node.outputs.evaluation_config_output_file
    )

    # return a dictionary with the evaluation metrics and the raw test set forecasts
    return {
        "metrics_result": compute_metrics_node.outputs.evaluation_result,
        "rolling_fcst_result": inference_node.outputs.inference_output_file
    }

现在,我们定义训练和测试数据输入,假定它们包含在本地文件夹 ./train_data./test_data 中:

my_train_data_input = Input(
    type=AssetTypes.MLTABLE,
    path="./train_data"
)

my_test_data_input = Input(
    type=AssetTypes.URI_FOLDER,
    path='./test_data',
)

最后,我们构造管道,设置其默认计算并提交作业:

pipeline_job = forecasting_train_and_evaluate_factory(
    my_train_data_input,
    my_test_data_input,
    target_column_name,
    time_column_name,
    forecast_horizon
)

# set pipeline level compute
pipeline_job.settings.default_compute = compute_name

# submit the pipeline job
returned_pipeline_job = ml_client.jobs.create_or_update(
    pipeline_job,
    experiment_name=experiment_name
)
returned_pipeline_job

提交后,管道将按顺序运行 AutoML 训练、滚动评估推理和指标计算。 可以在工作室 UI 中监视和检查运行。 运行完成后,可将滚动预测和评估指标下载到本地工作目录:

# Download the metrics json
ml_client.jobs.download(returned_pipeline_job.name, download_path=".", output_name='metrics_result')

# Download the rolling forecasts
ml_client.jobs.download(returned_pipeline_job.name, download_path=".", output_name='rolling_fcst_result')

然后,可在 ./named-outputs/metrics_results/evaluationResult/metrics.json 中找到指标结果,在 ./named-outputs/rolling_fcst_result/inference_output_file 中找到 JSON 行格式的预测。

有关滚动评估的更多详细信息,请参阅预测模型评估一文

大规模预测:多模型

重要

此功能目前处于公开预览状态。 此预览版在提供时没有附带服务级别协议,我们不建议将其用于生产工作负荷。 某些功能可能不受支持或者受限。

有关详细信息,请参阅适用于 Azure 预览版的补充使用条款

AutoML 中的许多模型组件使你能够并行训练和管理数百万个模型。 有关许多模型概念的详细信息,请参阅“多模型”文章部分

多模型训练配置

多模型训练组件接受 AutoML 训练设置的 YAML 格式配置文件。 该组件将这些设置应用于它启动的每个 AutoML 实例。 此 YAML 文件具有与预测作业相同的规范,还具有附加参数 partition_column_namesallow_multi_partitions

参数 说明
partition_column_names 数据中的列名,分组后定义数据分区。 多模型训练组件在每个分区上启动独立的训练作业。
allow_multi_partitions 一个可选标志,允许在每个分区包含多个唯一时序时为每个分区训练一个模型。 默认值为 False。

以下示例提供配置模板:

$schema: https://azuremlsdk2.blob.core.chinacloudapi.cn/preview/0.0.1/autoMLJob.schema.json
type: automl

description: A time series forecasting job config
compute: azureml:<cluster-name>
task: forecasting
primary_metric: normalized_root_mean_squared_error
target_column_name: sales
n_cross_validations: 3

forecasting:
  time_column_name: date
  time_series_id_column_names: ["state", "store"]
  forecast_horizon: 28

training:
  blocked_training_algorithms: ["ExtremeRandomTrees"]

limits:
  timeout_minutes: 15
  max_trials: 10
  max_concurrent_trials: 4
  max_cores_per_trial: -1
  trial_timeout_minutes: 15
  enable_early_termination: true
  
partition_column_names: ["state", "store"]
allow_multi_partitions: false

在后续示例中,我们假设配置存储在路径 ./automl_settings_mm.yml 中。

多模型管道

接下来,我们定义一个工厂函数,用于创建协调多模型训练、推理和指标计算的管道。 下表详细介绍了此工厂函数的参数:

参数 说明
max_nodes 要在训练作业中使用的计算节点数
max_concurrency_per_node 要在每个节点上运行的 AutoML 进程数。 因此,多模型作业的总并发性为 max_nodes * max_concurrency_per_node
parallel_step_timeout_in_seconds 以秒数表示的多模型组件超时。
retrain_failed_models 用于为失败的模型启用重新训练的标志。 如果之前进行了多模型运行,结果是 AutoML 作业在某些数据分区中失败,则此标志很有用。 启用此标志后,许多模型将仅针对之前失败的分区启动训练作业。
forecast_mode 模型评估的推理模式。 有效值为 "recursive" 和“rolling”。 有关详细信息,请参阅模型评估一文
forecast_step 滚动预测的步长。 有关详细信息,请参阅模型评估一文

以下示例演示了用于构造多模型训练和模型评估管道的工厂方法:

from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential

# Get a credential for access to the AzureML registry
try:
    credential = DefaultAzureCredential()
    # Check if we can get token successfully.
    credential.get_token("https://management.chinacloudapi.cn/.default")
except Exception as ex:
    # Fall back to InteractiveBrowserCredential in case DefaultAzureCredential fails
    credential = InteractiveBrowserCredential()

# Get a many models training component
mm_train_component = ml_client_registry.components.get(
    name='automl_many_models_training',
    version='latest'
)

# Get a many models inference component
mm_inference_component = ml_client_registry.components.get(
    name='automl_many_models_inference',
    version='latest'
)

# Get a component for computing evaluation metrics
compute_metrics_component = ml_client_metrics_registry.components.get(
    name="compute_metrics",
    label="latest"
)
@pipeline(description="AutoML Many Models Forecasting Pipeline")
def many_models_train_evaluate_factory(
    train_data_input,
    test_data_input,
    automl_config_input,
    compute_name,
    max_concurrency_per_node=4,
    parallel_step_timeout_in_seconds=3700,
    max_nodes=4,
    retrain_failed_model=False,
    forecast_mode="rolling",
    forecast_step=1
):
    mm_train_node = mm_train_component(
        raw_data=train_data_input,
        automl_config=automl_config_input,
        max_nodes=max_nodes,
        max_concurrency_per_node=max_concurrency_per_node,
        parallel_step_timeout_in_seconds=parallel_step_timeout_in_seconds,
        retrain_failed_model=retrain_failed_model,
        compute_name=compute_name
    )

    mm_inference_node = mm_inference_component(
        raw_data=test_data_input,
        max_nodes=max_nodes,
        max_concurrency_per_node=max_concurrency_per_node,
        parallel_step_timeout_in_seconds=parallel_step_timeout_in_seconds,
        optional_train_metadata=mm_train_node.outputs.run_output,
        forecast_mode=forecast_mode,
        forecast_step=forecast_step,
        compute_name=compute_name
    )

    compute_metrics_node = compute_metrics_component(
        task="tabular-forecasting",
        prediction=mm_inference_node.outputs.evaluation_data,
        ground_truth=mm_inference_node.outputs.evaluation_data,
        evaluation_config=mm_inference_node.outputs.evaluation_configs
    )

    # Return the metrics results from the rolling evaluation
    return {
        "metrics_result": compute_metrics_node.outputs.evaluation_result
    }

现在,我们通过工厂函数构造管道,假定训练数据和测试数据分别位于本地文件夹 ./data/train./data/test 中。 最后,设置默认计算并提交作业,如以下示例所示:

pipeline_job = many_models_train_evaluate_factory(
    train_data_input=Input(
        type="uri_folder",
        path="./data/train"
    ),
    test_data_input=Input(
        type="uri_folder",
        path="./data/test"
    ),
    automl_config=Input(
        type="uri_file",
        path="./automl_settings_mm.yml"
    ),
    compute_name="<cluster name>"
)
pipeline_job.settings.default_compute = "<cluster name>"

returned_pipeline_job = ml_client.jobs.create_or_update(
    pipeline_job,
    experiment_name=experiment_name,
)
ml_client.jobs.stream(returned_pipeline_job.name)

作业完成后,可按照与在单个训练运行管道中相同的过程,在本地下载评估指标。

有关更详细的示例,另请参阅“使用多模型预测需求”笔记本

注意

多模型训练和推理组件根据 partition_column_names 设置有条件地对数据进行分区,以便每个分区都在其自己的文件中。 当数据非常大时,此过程可能会非常缓慢或者会失败。 在这种情况下,建议在运行多模型训练或推理之前,手动对数据进行分区。

大规模预测:分层时序

重要

此功能目前处于公开预览状态。 此预览版在提供时没有附带服务级别协议,我们不建议将其用于生产工作负荷。 某些功能可能不受支持或者受限。

有关详细信息,请参阅适用于 Azure 预览版的补充使用条款

AutoML 中的分层时序 (HTS) 组件使你能够基于具有分层结构的数据训练大量模型。 有关详细信息,请参阅 HTS 文章部分

HTS 训练配置

HTS 训练组件接受 AutoML 训练设置的 YAML 格式配置文件。 该组件将这些设置应用于它启动的每个 AutoML 实例。 此 YAML 文件具有与预测作业相同的规范,还具有其他与层次结构信息相关的参数:

参数 说明
hierarchy_column_names 数据中的列名列表,这些列名定义了数据的分层结构。 此列表中列的顺序决定了层次结构级别,聚合度随列表索引的增加而减小。 也就是说,列表中的最后一列定义层次结构中的叶(聚合度最低)。
hierarchy_training_level 用于预测模型训练的层次结构级别。

下面显示了示例配置:

$schema: https://azuremlsdk2.blob.core.chinacloudapi.cn/preview/0.0.1/autoMLJob.schema.json
type: automl

description: A time series forecasting job config
compute: azureml:cluster-name
task: forecasting
primary_metric: normalized_root_mean_squared_error
log_verbosity: info
target_column_name: sales
n_cross_validations: 3

forecasting:
  time_column_name: "date"
  time_series_id_column_names: ["state", "store", "SKU"]
  forecast_horizon: 28

training:
  blocked_training_algorithms: ["ExtremeRandomTrees"]

limits:
  timeout_minutes: 15
  max_trials: 10
  max_concurrent_trials: 4
  max_cores_per_trial: -1
  trial_timeout_minutes: 15
  enable_early_termination: true
  
hierarchy_column_names: ["state", "store", "SKU"]
hierarchy_training_level: "store"

在后续示例中,我们假设配置存储在路径 ./automl_settings_hts.yml 中。

HTS 管道

接下来,我们定义一个工厂函数,用于创建协调 HTS 训练、推理和指标计算的管道。 下表详细介绍了此工厂函数的参数:

参数 说明
forecast_level 要检索其预测的层次结构的级别
allocation_method 分解预测时要使用的分配方法。 有效值为 "proportions_of_historical_average""average_historical_proportions"
max_nodes 要在训练作业中使用的计算节点数
max_concurrency_per_node 要在每个节点上运行的 AutoML 进程数。 因此,HTS 作业的总并发性为 max_nodes * max_concurrency_per_node
parallel_step_timeout_in_seconds 以秒数表示的多模型组件超时。
forecast_mode 模型评估的推理模式。 有效值为 "recursive" 和“rolling”。 有关详细信息,请参阅模型评估一文
forecast_step 滚动预测的步长。 有关详细信息,请参阅模型评估一文
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential

# Get a credential for access to the AzureML registry
try:
    credential = DefaultAzureCredential()
    # Check if we can get token successfully.
    credential.get_token("https://management.chinacloudapi.cn/.default")
except Exception as ex:
    # Fall back to InteractiveBrowserCredential in case DefaultAzureCredential fails
    credential = InteractiveBrowserCredential()

# Get a HTS training component
hts_train_component = ml_client_registry.components.get(
    name='automl_hts_training',
    version='latest'
)

# Get a HTS inference component
hts_inference_component = ml_client_registry.components.get(
    name='automl_hts_inference',
    version='latest'
)

# Get a component for computing evaluation metrics
compute_metrics_component = ml_client_metrics_registry.components.get(
    name="compute_metrics",
    label="latest"
)
@pipeline(description="AutoML HTS Forecasting Pipeline")
def hts_train_evaluate_factory(
    train_data_input,
    test_data_input,
    automl_config_input,
    max_concurrency_per_node=4,
    parallel_step_timeout_in_seconds=3700,
    max_nodes=4,
    forecast_mode="rolling",
    forecast_step=1,
    forecast_level="SKU",
    allocation_method='proportions_of_historical_average'
):
    hts_train = hts_train_component(
        raw_data=train_data_input,
        automl_config=automl_config_input,
        max_concurrency_per_node=max_concurrency_per_node,
        parallel_step_timeout_in_seconds=parallel_step_timeout_in_seconds,
        max_nodes=max_nodes
    )
    hts_inference = hts_inference_component(
        raw_data=test_data_input,
        max_nodes=max_nodes,
        max_concurrency_per_node=max_concurrency_per_node,
        parallel_step_timeout_in_seconds=parallel_step_timeout_in_seconds,
        optional_train_metadata=hts_train.outputs.run_output,
        forecast_level=forecast_level,
        allocation_method=allocation_method,
        forecast_mode=forecast_mode,
        forecast_step=forecast_step
    )
    compute_metrics_node = compute_metrics_component(
        task="tabular-forecasting",
        prediction=hts_inference.outputs.evaluation_data,
        ground_truth=hts_inference.outputs.evaluation_data,
        evaluation_config=hts_inference.outputs.evaluation_configs
    )

    # Return the metrics results from the rolling evaluation
    return {
        "metrics_result": compute_metrics_node.outputs.evaluation_result
    }

现在,我们通过工厂函数构造管道,假定训练数据和测试数据分别位于本地文件夹 ./data/train./data/test 中。 最后,设置默认计算并提交作业,如以下示例所示:

pipeline_job = hts_train_evaluate_factory(
    train_data_input=Input(
        type="uri_folder",
        path="./data/train"
    ),
    test_data_input=Input(
        type="uri_folder",
        path="./data/test"
    ),
    automl_config=Input(
        type="uri_file",
        path="./automl_settings_hts.yml"
    )
)
pipeline_job.settings.default_compute = "cluster-name"

returned_pipeline_job = ml_client.jobs.create_or_update(
    pipeline_job,
    experiment_name=experiment_name,
)
ml_client.jobs.stream(returned_pipeline_job.name)

作业完成后,可按照与在单个训练运行管道中相同的过程,在本地下载评估指标。

有关更详细的示例,另请参阅“使用分层时序预测需求”笔记本

注意

HTS 训练和推理组件根据 hierarchy_column_names 设置有条件地对数据进行分区,以便每个分区都在其自己的文件中。 当数据非常大时,此过程可能会非常缓慢或者会失败。 在这种情况下,建议在运行 HTS 训练或推理之前,手动对数据进行分区。

大规模预测:分布式 DNN 训练

示例笔记本

请参阅预测示例笔记本,了解高级预测配置的详细代码示例,其中包括:

后续步骤