適用於: Azure CLI ml extension v2 (目前版本) Python SDK azure-ai-ml v2 (目前版本)

Azure 機器學習中的自動化機器學習(AutoML)結合標準機器學習模型與知名時間序列模型來產生預測。 此方法將目標變數的歷史資訊與使用者提供的輸入資料特徵以及自動生成的特徵整合在一起。 模型搜尋演算法可協助識別具有最佳預測準確度的模型。 如需更多資訊,請參閱 預測方法 模型掃描與選擇

本文說明如何利用 Azure Machine Learning Python SDK Azure CLI 設定 AutoML 以進行時間序列預測。 此過程包括準備訓練資料及在 預測工作(類別參考) 中設定時間序列參數。 接著,您可以使用組件與管線進行模型的訓練、推論及評估。

如需低程式碼體驗,請參閱 教學課程:使用自動化機器學習預測需求 。 本文提供了一個使用 Azure Machine Learning Studio 中 AutoML 的時間序列預測範例。

  • Azure Machine Learning 工作區。 如需詳細資訊,請參閱 建立工作區資源
  • 能夠啟動 AutoML 訓練工作。 如需更多資訊,請參閱 使用 Azure Machine Learning CLI 與 Python SDK 設定表格式資料的 AutoML 訓練
  • 準備訓練與驗證資料

    AutoML 預測的輸入資料必須包含有效的表格式時間序列。 每個變數在資料表中必須有對應的欄位。 AutoML 至少需要兩個欄位:一個 時間 欄位表示時間軸,及一個 目標 欄位表示要預測的數量。 其他欄位可作為預測變數。 如需更多資訊,請參閱 AutoML 如何使用您的資料

    當你訓練模型預測未來值時,請確保所有訓練中使用的特徵也能用於預測你預期的視界。

    考慮一項關於目前股價的功能,這能提升訓練的準確性。 如果你用長遠視野來預測,可能無法準確預測對應於未來時間序列點的未來股價。 此方法可能降低模型準確度。

    AutoML 預測工作要求您的訓練資料以 MLTable 物件表示。 MLTable 物件指定資料來源及載入資料的步驟。 欲了解更多資訊與使用案例,請參閱 「與資料表合作 」。

    以下範例假設你的訓練資料包含在本地目錄中的 CSV 檔案中: ./train_data/timeseries_train.csv

    此程式碼會建立新的檔案 ./train_data/MLTable ,其中包含檔案格式和載入指示。

    要開始訓練工作,請使用 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"
    

    你可以透過將以下 YAML 片段複製到新檔案 MLTable 來定義新物件。

    $schema: https://azuremlschemas.azureedge.net/latest/MLTable.schema.json
    type: mltable
    paths:
        - file: ./timeseries_train.csv
    transformations:
        - read_delimited:
            delimiter: ','
            encoding: ascii
    

    開始建立 AutoML 工作的 YAML 組態,訓練資料指定如下範例所示:

    $schema: https://azuremlsdk2.blob.core.windows.net/preview/0.0.1/autoMLJob.schema.json
    type: automl
    experiment_name: cli-v2-automl-forecasting-job
    description: A time-series forecasting AutoML job
    task: forecasting
    # Training data MLTable for the AutoML job.
    training_data:
        path: "./train_data"
        type: mltable
    validation_data:
        # Optional validation data.
    compute: # Compute for training job.
    primary_metric: # Primary metric.  
    target_column_name: # Target column name.
    n_cross_validations: # Cross-validation setting.
    limits:
        # Limit settings.
    forecasting:
        # Forecasting-specific settings.
    training:
        # Training settings. 
    

    你會在本文後續章節中補充更多的設定細節。 在此範例中,位置為 ./automl-forecasting-job.yml

    您可以以類似方式指定驗證資料。 建立 MLTable 物件並指定驗證資料輸入。 或者,如果未提供驗證資料,AutoML 將自動從訓練資料建立交叉驗證分割,用於模型選擇。 如需詳細資訊,請參閱下列資源:

    選擇預測模型 設定訓練資料長度需求 使用交叉驗證避免過度擬合

    建立計算來執行實驗

    AutoML 使用 Azure Machine Learning 運算,這是一個完全受控的運算資源,來執行訓練工作。

    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()

    您可以使用以下 Azure CLI 指令建立一個新的 cpu-compute 計算:

    az ml compute create -n cpu-compute --type amlcompute --min-instances 0 --max-instances 4
    

    在工作定義中參考該計算資源如下:

    $schema: https://azuremlsdk2.blob.core.windows.net/preview/0.0.1/autoMLJob.schema.json
    type: automl
    experiment_name: cli-v2-automl-forecasting-job
    description: A time-series forecasting AutoML job
    task: forecasting
    # Set training data MLTable for the AutoML job.
    training_data:
        path: "./train_data"
        type: mltable
    # Set compute for the training job to use. 
    compute: azureml:cpu-compute
    primary_metric: # Primary metric.  
    target_column_name: # Target column name.
    n_cross_validations: # Cross-validation setting.
    limits:
        # Limit settings.
    forecasting:
        # Forecasting-specific settings.
    training:
        # Training settings.
    

    以下範例示範如何設定實驗。

    您可以使用 Python SDK 的 AutoML 工廠函數設定預測工作。 以下範例示範如何透過設定主要指標並限制訓練執行,建立預測工作

    from azure.ai.ml import automl
    # Set forecasting variables.
    # As needed, modify the variable values to run the snippet 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",
    # Set optional limits.
    forecasting_job.set_limits(
        timeout_minutes=120,
        trial_timeout_minutes=30,
        max_concurrent_trials=4,
    

    如需更多資訊,請參閱預測命令工作 YAML 結構描述訓練參數限制

    $schema: https://azuremlsdk2.blob.core.windows.net/preview/0.0.1/autoMLJob.schema.json
    type: automl
    experiment_name: cli-v2-automl-forecasting-job
    description: A time-series forecasting AutoML job
    task: forecasting
    training_data:
        path: "./train_data"
        type: mltable
    compute: azureml:cpu-compute
    # Settings for primary metric, target/label column name, cross validation.
    primary_metric: normalized_root_mean_squared_error
    target_column_name: <target_column_name>
    n_cross_validations: auto
    # Settings for training job limits on time, concurrency, and others.
    limits:
        timeout_minutes: 120
        trial_timeout_minutes: 30
        max_concurrent_trials: 4
    forecasting:
        # Forecasting-specific settings.
    training:
        # Training settings.
    

    預測工作設定

    預測任務有許多專屬於預測的設定。 這些設定中最基本的是訓練資料中時間欄位的名稱以及預測期。

    使用 ForecastingJob 方法設定這些設定:

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

    這些設定在工作 YAML 組態的 forecasting 區段中設定:

    $schema: https://azuremlsdk2.blob.core.windows.net/preview/0.0.1/autoMLJob.schema.json
    type: automl
    experiment_name: cli-v2-automl-forecasting-job
    description: A time-series forecasting AutoML job
    task: forecasting
    training_data:
        path: "./train_data"
        type: mltable
    compute: azureml:cpu-compute
    primary_metric: normalized_root_mean_squared_error
    target_column_name: <target_column_name>
    n_cross_validations: auto
    limits:
        timeout_minutes: 120
        trial_timeout_minutes: 30
        max_concurrent_trials: 4
    # Forecasting-specific settings.
    # Set the horizon to 24 for this example. The horizon generally depends on the business scenario.
    forecasting:
        time_column_name: <time_column_name>
        forecast_horizon: 24
    training:
        # Training settings.
    
    # 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']
    
    # Only search ExponentialSmoothing and ElasticNet models.
    forecasting_job.set_training(
        allowed_training_algorithms=["ExponentialSmoothing", "ElasticNet"]
    
    $schema: https://azuremlsdk2.blob.core.windows.net/preview/0.0.1/autoMLJob.schema.json
    type: automl
    experiment_name: cli-v2-automl-forecasting-job
    description: A time-series forecasting AutoML job
    task: forecasting
    training_data:
        path: "./train_data"
        type: mltable
    compute: azureml:cpu-compute
    primary_metric: normalized_root_mean_squared_error
    target_column_name: <target_column_name>
    n_cross_validations: auto
    limits:
        timeout_minutes: 120
        trial_timeout_minutes: 30
        max_concurrent_trials: 4
    forecasting:
        time_column_name: <time_column_name>
        forecast_horizon: 24
    # Training settings.
    # Only search ExponentialSmoothing and ElasticNet models.
    training:
        allowed_training_algorithms: ["ExponentialSmoothing", "ElasticNet"]
        # Other training settings.
    
    # Search over all model classes except Prophet.
    forecasting_job.set_training(
        blocked_training_algorithms=["Prophet"]
    # Search over all model classes except Prophet.
    training:
        blocked_training_algorithms: ["Prophet"]
        # Other training settings.
    

    工作會搜尋所有模型類別,除了 Prophet。 如需 allowed_training_algorithmsblocked_training_algorithms 可接受的預測模型名稱清單,請參閱訓練屬性。 您可以套用其中之一,但不能同時套用 allowed_training_algorithmsblocked_training_algorithms 至一次訓練執行。

    啟用深度神經網路學習

    AutoML 隨附一個名為 TCNForecaster 的自訂深度神經網路 (DNN) 模型。 此模型為時間卷積網路 (TCN),將常見影像任務方法應用於時間序列建模。 一維「因果」卷積構成網路主體,使模型能從訓練歷史中學習長時間範圍的複雜模式。 如需更多資訊,請參閱 TCNForecaster 簡介

    當訓練歷史中有數千次觀測或更多時,TCNForecaster 通常能達到比標準時間序列模型更高的準確度。 然而,由於其較高的容量,TCNForecaster 訓練與掃描所需時間也較長。

    你可以在 AutoML 中啟用 TCNForecaster,方法是在訓練設定中設定 enable_dnn_training 旗標,方法如下:

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

    預設情況下,TCNForecaster 訓練限制為每個模型試驗使用單一計算節點及單一 GPU (若可用)。 對於大量資料情境,建議將每個 TCNForecaster 試驗分散到多核心/GPU 與多節點。 如需更多資訊與程式碼範例,請參閱分散式訓練

    要在 Azure Machine Learning Studio 中為建立的 AutoML 實驗啟用 DNN,請參考 Studio UI 文章中的任務類型設定

  • 當您為使用 SDK 建立的實驗啟用 DNN 時,系統會停用最佳模型解釋
  • 啟動於 Azure Databricks 的執行不支援自動化機器學習中的深度神經網絡 (DNN) 預測功能。
  • 建議在啟用 DNN 訓練時使用 GPU 計算類型。
  • 延遲與滾動視窗特徵

    目標的近期值通常是預測模型中有影響力的特徵。 因此,AutoML 能建立時間延遲與滾動視窗聚合功能,以提升模型準確度。

    考慮一個能源需求預測情境,其中有天氣資料與歷史需求資料可用。 下表顯示當對最近三小時套用視窗彙總時所產生的特徵工程結果。 最小值最大值總和欄位會基於定義的設定,在三小時的滑動視窗上生成。 例如,對於2017年9月8日凌晨4點有效的觀察值,最大值、最小值和和值是利用2017年9月8日凌晨1點至3點 的需求值 計算得出。 這三小時的視窗會沿時間移動以填充其餘列的資料。 如需更多資訊與範例,請參閱 AutoML 中時間序列預測的延遲特徵

    # Forecasting-specific settings.
    # Auto configure lags and rolling-window features.
    forecasting:
        target_lags: auto
        target_rolling_window_size: auto
        feature_lags: auto
        # Other settings.
    

    短序列處理

    若時間序列的資料點不足以進行模型開發的訓練與驗證階段,AutoML 會將其視為短序列。 如需更多資訊,請參閱訓練資料長度需求

    AutoML 對短序列有數種處理方式。 你可以透過設定 short_series_handling_config 來設定這些動作。 預設值是 auto。 下表描述了各設定:

    若使用 short_series_handling_config = pad 設定,AutoML 會對每個找到的短序列加入隨機值。 AutoML 會使用白噪音填補目標欄位。 您可以對以下欄位類型使用指定的填補方式:
    - 物件欄位,填補 NaN
    - 數值欄位,以0(零)填充。
    - 布林值/邏輯欄位,用False填充。 若使用 short_series_handling_config = drop 設定,AutoML 會刪除短序列,且不會用於訓練或預測。 這些序列的預測結果會傳回 NaN。 不會填補或刪除序列。
    forecasting_job.set_forecast_settings(
        ...,  # Other settings.
        short_series_handling_config='pad'
    
    # Forecasting-specific settings.
    # Auto configure lags and rolling-window features.
    forecasting:
        short_series_handling_config: pad
        # Other settings.
    

    頻率與目標資料彙總

    使用頻率與資料彙總選項可避免因資料不規則而造成的錯誤。 若資料沒有遵循固定時間間隔,例如每小時或每日,則視為不規則資料。 銷售點資料就是不規則資料的好例子。 在這些情境中,AutoML 可以將您的資料彙總到所需頻率,然後從彙總資料建立預測模型。

    您需要設定 frequencytarget_aggregate_function 以處理不規則資料。 填補設定接受 Pandas DateOffset 字串作為輸入。 下表顯示彙總函數支援的值:

    類別型預測變數 AutoML 使用 forecast_mode 參數的值來彙總資料。 這是視窗中最顯著的類別。 欲了解更多資訊,請參閱 多模型管線HTS 管線 章節中的參數說明。 資料型預測變數 AutoML 使用最小目標值 (min)、最大目標值 (max) 及 forecast_mode 參數設定來彙總資料。 AutoML 會根據指定的操作彙總數值。 通常,sum 函數適用於大多數情境。

    以下範例將頻率設定為每小時,彙總函數設定為求和:

    # Aggregate the data to hourly frequency.
    forecasting_job.set_forecast_settings(
        ...,  # Other settings.
        frequency='H',
        target_aggregate_function='sum'
    
    # Forecasting-specific settings.
    # Auto-configure lags and rolling-window features.
    forecasting:
        frequency: H
        target_aggregate_function: sum
        # Other settings.
    

    自訂交叉驗證設定

    有兩個可自訂設定可控制預測工作的交叉驗證。 可利用 n_cross_validations 參數自訂摺疊次數,並設定 cv_step_size 參數以定義摺疊間的時間偏移。 如需更多資訊,請參閱預測模型選擇

    預設情況下,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
    $schema: https://azuremlsdk2.blob.core.windows.net/preview/0.0.1/autoMLJob.schema.json
    type: automl
    experiment_name: cli-v2-automl-forecasting-job
    description: A time-series forecasting AutoML job
    task: forecasting
    training_data:
        path: "./train_data"
        type: mltable
    compute: azureml:cpu-compute
    primary_metric: normalized_root_mean_squared_error
    target_column_name: <target_column_name>
    n_cross_validations: auto
    # Use five CV folds.
    n_cross_validations: 5
    # Set the step size between folds to seven days.
    forecasting:
        cv_step_size: 7
        # Other settings.
    limits:
        # Limit settings.
    training:
        # Training settings.
    

    自訂特徵工程

    預設情況下,AutoML 會對訓練資料增加工程特徵,以提升模型準確度。 欲了解更多資訊,請參閱 自動化特徵工程。 你可以透過預測作業的 特徵化 設定,自訂部分前處理步驟。

    下表列出預測支援的自訂化功能:

    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 product_type feature is interpreted as categorical.
    forecasting_job.set_featurization(
        mode="custom",
        transformer_params=transformer_params,
        column_name_and_types={"product_type": "Categorical"},
    
    $schema: https://azuremlsdk2.blob.core.windows.net/preview/0.0.1/autoMLJob.schema.json
    type: automl
    experiment_name: cli-v2-automl-forecasting-job
    description: A time-series forecasting AutoML job
    task: forecasting
    training_data:
        path: "./train_data"
        type: mltable
    compute: azureml:cpu-compute
    primary_metric: normalized_root_mean_squared_error
    target_column_name: <target_column_name>
    n_cross_validations: auto
    # Customize imputation methods for price and is_on_sale features.
    # Median value imputation for price, constant value of zero for is_on_sale.
    featurization:
        mode: custom
        column_name_and_types:
            product_type: Categorical
        transformer_params:
            imputer:
                - fields: ["price"]
                parameters:
                    strategy: median
                - fields: ["is_on_sale"]
                parameters:
                    strategy: constant
                    fill_value: 0
    forecasting:
        # Forecasting-specific settings.
    limits:
        # Limit settings.
    training:
        # Training settings.
    

    在執行 Azure CLI 指令後,作業 YAML 設定會位於目前的工作目錄路徑 ./automl-forecasting-job.yml。 如果您從不同目錄執行命令,需相應變更路徑。

    run_id=$(az ml job create --file automl-forecasting-job.yml)
    

    您可以使用預存的執行識別碼來傳回作業的相關資訊。 這個 --web 參數會開啟 Azure Machine Learning Studio 的網頁介面,您可以在那裡查看該工作的詳細資訊:

    az ml job show -n $run_id --web
    

    提交工作後,AutoML 會佈建計算資源,對輸入資料應用特徵工程及其他準備步驟,並開始對預測模型進行掃描。 欲了解更多資訊,請參閱 AutoML 中的預測方法論AutoML 中預測的模型掃頻與選擇

    透過元件與流程協調訓練、推論與評估

    你的機器學習工作流程可能需要的不僅僅是訓練。 推論或取得模型對新資料的預測,以及對具有已知目標值的測試集進行模型準確度評估,是您可以在 Azure Machine Learning 中與訓練工作一同協調的其他常見工作。 為了支援推論與評估工作,Azure Machine Learning 提供元件,這些元件是自包含程式碼片段,可在 Azure Machine Learning 管道中執行單一步驟。

    以下範例從用戶端登錄檔擷取元件程式碼:

    from azure.ai.ml import MLClient
    from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential
    # Get credential to access azureml registry.
        credential = DefaultAzureCredential()
        # Check if token can be obtained successfully.
        credential.get_token("https://management.azure.com/.default")
    except Exception as ex:
        # Fall back to InteractiveBrowserCredential in case DefaultAzureCredential fails.
        credential = InteractiveBrowserCredential()
    # Create client to access assets in azureml-preview registry.
    ml_client_registry = MLClient(
        credential=credential,
        registry_name="azureml-preview"
    # Create client to access assets in azureml registry.
    ml_client_metrics_registry = MLClient(
        credential=credential,
        registry_name="azureml"
    # Get inference component from registry.
    inference_component = ml_client_registry.components.get(
        name="automl_forecasting_inference",
        label="latest"
    # Get component to compute evaluation metrics from 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 training node of 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 inference node to make rolling forecasts on 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',
            step=1
        # Configure 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 dictionary with evaluation metrics and 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 pipeline job.
    returned_pipeline_job = ml_client.jobs.create_or_update(
        pipeline_job,
        experiment_name=experiment_name
    returned_pipeline_job
    
    $schema: https://azuremlschemas.azureedge.net/latest/pipelineJob.schema.json
    type: pipeline
    description: AutoML Forecasting Pipeline
    experiment_name: cli-v2-automl-forecasting-pipeline
    # Set default compute for pipeline steps.
    settings:
        default_compute: cpu-compute
    # Pipeline inputs.
    inputs:
        train_data_input:
            type: mltable
            path: "./train_data"
        test_data_input:
            type: uri_folder
            path: "./test_data"
        target_column_name: <target column name>
        time_column_name: <time column name>
        forecast_horizon: <forecast horizon>
        primary_metric: normalized_root_mean_squared_error
        cv_folds: auto
    # Set pipeline outputs.
    # Output the evaluation metrics and raw test set rolling forecasts.
    outputs: 
        metrics_result:
            type: uri_file
            mode: upload
        rolling_fcst_result:
            type: uri_file
            mode: upload
    jobs:
      # Configure automl training node of pipeline.
        training_node:
            type: automl
            task: forecasting
            primary_metric: ${{parent.inputs.primary_metric}}
            target_column_name: ${{parent.inputs.target_column_name}}
            training_data: ${{parent.inputs.train_data_input}}
            n_cross_validations: ${{parent.inputs.cv_folds}}
            training:
                # Training settings.
            forecasting:
                time_column_name: ${{parent.inputs.time_column_name}}
                forecast_horizon: ${{parent.inputs.forecast_horizon}}
                # Other forecasting-specific settings.
            limits:
                # Limit settings.
            outputs:
                best_model:
                    type: mlflow_model
        # Configure inference node to make rolling forecasts on test set.
        inference_node:
            type: command
            component: azureml://registries/azureml-preview/components/automl_forecasting_inference
            inputs:
                target_column_name: ${{parent.inputs.target_column_name}}
                forecast_mode: rolling
                step: 1
                test_data: ${{parent.inputs.test_data_input}}
                model_path: ${{parent.jobs.training_node.outputs.best_model}}
            outputs:
                inference_output_file: ${{parent.outputs.rolling_fcst_result}}
                evaluation_config_output_file:
                    type: uri_file
        # Configure metrics calculation node.
        compute_metrics:
            type: command
            component: azureml://registries/azureml/compute_metrics
            inputs:
                task: "tabular-forecasting"
                ground_truth: ${{parent.jobs.inference_node.outputs.inference_output_file}}
                prediction: ${{parent.jobs.inference_node.outputs.inference_output_file}}
                evaluation_config: ${{parent.jobs.inference_node.outputs.evaluation_config_output_file}}
            outputs:
                evaluation_result: ${{parent.outputs.metrics_result}}
    

    AutoML 需要以 MLTable 格式的訓練資料。

    開始執行管線運行,請使用以下命令。 管道組態位於路徑 ./automl-forecasting-pipeline.yml

    run_id=$(az ml job create --file automl-forecasting-pipeline.yml -w <Workspace> -g <Resource Group> --subscription <Subscription>)
    
    # Download metrics JSON.
    ml_client.jobs.download(returned_pipeline_job.name, download_path=".", output_name='metrics_result')
    # Download 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 Lines 格式)
  • 如需更多滾動評估資訊,請參閱預測模型的推論與評估

    大規模預測:多模型

    AutoML 中的多模型元件讓你能同時訓練和管理數百萬個模型。 欲了解更多資訊,請參閱 「多模型」。

    多模型訓練配置

    多模型訓練元件接受 AutoML 訓練設定的 YAML 格式設定檔。 元件會將這些設定套用到它啟動的每個 AutoML 實例上。 YAML 檔案的規格與 Forecasting 指令工作相同,還有partition_column_namesallow_multi_partitions參數。

    以下是 YAML 設定範例:

    $schema: https://azuremlsdk2.blob.core.windows.net/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_concurrency_per_node 每個節點上要執行的 AutoML 處理程序數量。 多模型作業的總並行性為 max_nodes * max_concurrency_per_nodeparallel_step_timeout_in_seconds 多模型元件逾時,以秒為單位指定。 retrain_failed_models 啟用失敗模型重新訓練的旗標。 如果你之前進行過多個模型的運行,導致某些資料分割區的 AutoML 作業失敗,此值可以幫助解決這類問題。 啟用此標記後,許多模型只會執行先前失敗的分割區訓練工作。 forecast_mode 模型評估的推論模式。 有效值為 recursive (預設) 和 rolling。 有關更多資訊,請參閱預測模型的推論與評估以及 ManyModelsInferenceParameters 類別參考。 滾動預報的步長。 預設值為 1。 有關更多資訊,請參閱預測模型的推論與評估以及 ManyModelsInferenceParameters 類別參考。

    以下範例展示了一種工廠方法,用於建構多模型訓練和模型評估的流程:

    from azure.ai.ml import MLClient
    from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential
    # Get credential to access azureml registry.
        credential = DefaultAzureCredential()
        # Check whether token can be obtained.
        credential.get_token("https://management.azure.com/.default")
    except Exception as ex:
        # Fall back to InteractiveBrowserCredential if DefaultAzureCredential fails.
        credential = InteractiveBrowserCredential()
    # Get many-models training component.
    mm_train_component = ml_client_registry.components.get(
        name='automl_many_models_training',
        version='latest'
    # Get many-models inference component.
    mm_inference_component = ml_client_registry.components.get(
        name='automl_many_models_inference',
        version='latest'
    # Get component to compute 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,
            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 metrics results from 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)
    
    $schema: https://azuremlschemas.azureedge.net/latest/pipelineJob.schema.json
    type: pipeline
    description: AutoML Many Models Forecasting Pipeline
    experiment_name: cli-v2-automl-mm-forecasting-pipeline
    # Set default compute for pipeline steps.
    settings:
        default_compute: azureml:cpu-compute
    # Set pipeline inputs.
    inputs:
        train_data_input:
            type: uri_folder
            path: "./train_data"
            mode: direct
        test_data_input:
            type: uri_folder
            path: "./test_data"
        automl_config_input:
            type: uri_file
            path: "./automl_settings_mm.yml"
        max_nodes: 4
        max_concurrency_per_node: 4
        parallel_step_timeout_in_seconds: 3700
        forecast_mode: rolling
        step: 1
        retrain_failed_model: False
    # Set pipeline outputs.
    # Output the evaluation metrics and raw test set rolling forecasts.
    outputs: 
        metrics_result:
            type: uri_file
            mode: upload
    jobs:
        # Configure AutoML many-models training component.
        mm_train_node:
            type: command
            component: azureml://registries/azureml-preview/components/automl_many_models_training
            inputs:
                raw_data: ${{parent.inputs.train_data_input}}
                automl_config: ${{parent.inputs.automl_config_input}}
                max_nodes: ${{parent.inputs.max_nodes}}
                max_concurrency_per_node: ${{parent.inputs.max_concurrency_per_node}}
                parallel_step_timeout_in_seconds: ${{parent.inputs.parallel_step_timeout_in_seconds}}
                retrain_failed_model: ${{parent.inputs.retrain_failed_model}}
            outputs:
                run_output:
                    type: uri_folder
        # Configure inference node to make rolling forecasts on test set.
        mm_inference_node:
            type: command
            component: azureml://registries/azureml-preview/components/automl_many_models_inference
            inputs:
                raw_data: ${{parent.inputs.test_data_input}}
                max_concurrency_per_node: ${{parent.inputs.max_concurrency_per_node}}
                parallel_step_timeout_in_seconds: ${{parent.inputs.parallel_step_timeout_in_seconds}}
                forecast_mode: ${{parent.inputs.forecast_mode}}
                step: ${{parent.inputs.step}}
                max_nodes: ${{parent.inputs.max_nodes}}
                optional_train_metadata: ${{parent.jobs.mm_train_node.outputs.run_output}}
            outputs:
                run_output:
                    type: uri_folder
                evaluation_configs:
                    type: uri_file
                evaluation_data:
                    type: uri_file
        # Configure metrics calculation node.
        compute_metrics:
            type: command
            component: azureml://registries/azureml/components/compute_metrics
            inputs:
                task: "tabular-forecasting"
                ground_truth: ${{parent.jobs.mm_inference_node.outputs.evaluation_data}}
                prediction: ${{parent.jobs.mm_inference_node.outputs.evaluation_data}}
                evaluation_config: ${{parent.jobs.mm_inference_node.outputs.evaluation_configs}}
            outputs:
                evaluation_result: ${{parent.outputs.metrics_result}}
    

    你用以下指令啟動管線工作。 多模型管線配置位於路徑 ./automl-mm-forecasting-pipeline.yml

    az ml job create --file automl-mm-forecasting-pipeline.yml -w <Workspace> -g <Resource Group> --subscription <Subscription>
    

    多模型運行的訓練考量

  • 多模型訓練與推論元件會根據partition_column_names的設定有條件地劃分資料。 此流程會使每個分割都存放在自己的檔案中。 當資料量龐大時,這個過程可能會很慢甚至失敗。 我們建議您在執行多模型訓練或推論前,先手動分割資料。

  • 在多模型訓練過程中,模型會自動註冊在工作區,因此不需要手動註冊模型。 模型名稱是根據它們訓練的分區來命名,這些名稱無法自訂。 標籤也無法自訂。 這些特性用於在推論過程中自動偵測模型。

  • 單一模型部署無法擴展,但你可以用 PipelineComponentBatchDeployment 來讓部署過程更簡單。 舉例來說,請參閱《 使用多模型需求預測》筆記本

  • 在推論過程中,會根據推論資料中傳送的分割自動選擇適當的模型(最新版本)。 預設情況下,使用 training_experiment_name時會使用最新的模型,但你也可以透過提供 train_run_id來覆蓋此行為,從特定訓練執行中選擇模型。

    訂閱制中多模型運行的預設平行限制為 320。 如果您的工作負載需要更高限制,您可以聯絡 Microsoft 支援。

    大規模預測:分層時間序列

    AutoML 中的階層時間序列(HTS)元件,使您能在具有階層結構的數據上訓練大量模型。 有關更多資訊,請參閱階層式時間序列預測

    HTS 訓練組態

    HTS 訓練元件接受 AutoML 訓練設定的 YAML 格式組態檔案。 元件會將這些設定套用到它執行的每個 AutoML 實例上。 此 YAML 檔案與 預測指令工作相同規範,但包含其他與階層資訊相關的參數:

    hierarchy_column_names 資料中定義層級結構的欄位名稱清單。 此清單中欄位的順序決定層級。 彙總程度隨清單索引下降。 也就是說,清單中的最後一個欄位定義了葉節點或層級中最細的級別。 hierarchy_training_level 用於預測模型訓練的層級。

    以下是 YAML 設定範例:

    $schema: https://azuremlsdk2.blob.core.windows.net/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 訓練、推論及度量計算編排的流水線。 下表說明此工廠函數的參數:

    allocation_method 當預測被拆分時所使用的分配方法。 有效值為 proportions_of_historical_averageaverage_historical_proportionsmax_nodes 訓練工作中要使用的運算節點數量。 max_concurrency_per_node 每個節點上可執行的 AutoML 程序數量。 HTS 作業的總並發性為 max_nodes * max_concurrency_per_nodeparallel_step_timeout_in_seconds 多模型元件逾時,以秒為單位指定。 forecast_mode 模型評估的推論模式。 有效值為 recursiverolling。 有關更多資訊,請參閱預測模型的推論與評估以及 HTSInferenceParameters 類別參考。 滾動預報的步長。 預設值為 1。 有關更多資訊,請參閱預測模型的推論與評估以及 HTSInferenceParameters 類別參考。
    from azure.ai.ml import MLClient
    from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential
    # Get credential to access azureml registry.
        credential = DefaultAzureCredential()
        # Check whether token can be obtained.
        credential.get_token("https://management.azure.com/.default")
    except Exception as ex:
        # Fall back to InteractiveBrowserCredential if DefaultAzureCredential fails.
        credential = InteractiveBrowserCredential()
    # Get HTS training component.
    hts_train_component = ml_client_registry.components.get(
        name='automl_hts_training',
        version='latest'
    # Get HTS inference component.
    hts_inference_component = ml_client_registry.components.get(
        name='automl_hts_inference',
        version='latest'
    # Get component to compute 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,
            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 metrics results from 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)
    
    $schema: https://azuremlschemas.azureedge.net/latest/pipelineJob.schema.json
    type: pipeline
    description: AutoML Many Models Forecasting Pipeline
    experiment_name: cli-v2-automl-mm-forecasting-pipeline
    # Set the default compute for pipeline steps.
    settings:
        default_compute: cpu-compute
    # Set pipeline inputs.
    inputs:
        train_data_input:
            type: uri_folder
            path: "./train_data"
            mode: direct
        test_data_input:
            type: uri_folder
            path: "./test_data"
        automl_config_input:
            type: uri_file
            path: "./automl_settings_hts.yml"
        max_concurrency_per_node: 4
        parallel_step_timeout_in_seconds: 3700
        max_nodes: 4
        forecast_mode: rolling
        step: 1
        allocation_method: proportions_of_historical_average
        forecast_level: # forecast level
    # Set pipeline outputs.
    # Output evaluation metrics and raw test set rolling forecasts.
    outputs: 
        metrics_result:
            type: uri_file
            mode: upload
    jobs:
        # Configure AutoML many-models training component.
        hts_train_node:
            type: command
            component: azureml://registries/azureml-preview/components/automl_hts_training
            inputs:
                raw_data: ${{parent.inputs.train_data_input}}
                automl_config: ${{parent.inputs.automl_config_input}}
                max_nodes: ${{parent.inputs.max_nodes}}
                max_concurrency_per_node: ${{parent.inputs.max_concurrency_per_node}}
                parallel_step_timeout_in_seconds: ${{parent.inputs.parallel_step_timeout_in_seconds}}
            outputs:
                run_output:
                    type: uri_folder
        # Configure inference node to make rolling forecasts on test set.
        hts_inference_node:
            type: command
            component: azureml://registries/azureml-preview/components/automl_hts_inference
            inputs:
                raw_data: ${{parent.inputs.test_data_input}}
                max_concurrency_per_node: ${{parent.inputs.max_concurrency_per_node}}
                parallel_step_timeout_in_seconds: ${{parent.inputs.parallel_step_timeout_in_seconds}}
                forecast_mode: ${{parent.inputs.forecast_mode}}
                step: ${{parent.inputs.step}}
                max_nodes: ${{parent.inputs.max_nodes}}
                optional_train_metadata: ${{parent.jobs.hts_train_node.outputs.run_output}}
                forecast_level: ${{parent.inputs.forecast_level}}
                allocation_method: ${{parent.inputs.allocation_method}}
            outputs:
                run_output:
                    type: uri_folder
                evaluation_configs:
                    type: uri_file
                evaluation_data:
                    type: uri_file
        # Configure metrics calculation node.
        compute_metrics:
            type: command
            component: azureml://registries/azureml/components/compute_metrics
            inputs:
                task: "tabular-forecasting"
                ground_truth: ${{parent.jobs.hts_inference_node.outputs.evaluation_data}}
                prediction: ${{parent.jobs.hts_inference_node.outputs.evaluation_data}}
                evaluation_config: ${{parent.jobs.hts_inference_node.outputs.evaluation_configs}}
            outputs:
                evaluation_result: ${{parent.outputs.metrics_result}}
    

    你可以使用以下指令啟動管線工作。 多模型管線配置位於路徑 ./automl-hts-forecasting-pipeline.yml

    az ml job create --file automl-hts-forecasting-pipeline.yml -w <Workspace> -g <Resource Group> --subscription <Subscription>
    

    欲了解更多詳細範例,請參閱《 利用 HTS 需求預測筆記本》。

    HTS 運行的訓練考量

    HTS 訓練和推論元件會根據設定條件地將資料 hierarchy_column_names 分割,使每個分割區都獨立於獨立檔案中。 當你有大量資料時,這個過程可能會很慢甚至失敗。 我們建議您在執行 HTS 訓練或推論前,先手動分割資料。

    訂閱中 HTS 運行的預設平行處理上限為 320。 如果您的工作負載需要更高限制,您可以聯絡 Microsoft 支援。

    大規模預測:分散式 DNN 訓練

    如本文前面所述,您可以啟用深度神經網路 (DNN) 學習。 要了解分散式訓練如何應用於 DNN 預測任務,請參閱分散式深度神經網路訓練 (預覽版)

    對於需要大量資料的情境,針對有限模型集,提供 AutoML 分散式訓練。 您可以在大規模 AutoML:分散式訓練中找到更多資訊和程式範例。

    探索範例筆記本

    提供詳細程式範例,展示進階的預測組態,這些範例可在 AutoML 預測範例筆記本 GitHub 儲存庫中找到。 以下是一些範例筆記本:

    建立需求預測管線(HTS 及多種模型)
  • 在 GitHub 資料集上訓練 TCNForecaster (DNN) 模型 使用假期檢測和特徵化進行預測 (共享單車資料集) 手動設定滯後與滑動視窗彙總 將 AutoML 模型部署到線上端點 Python SDK 的模型可解讀性 選擇建模組態