Guide · Amazon Forecast · Predictor Training & AutoML

Amazon Forecast Predictor Training for MCP Servers — CreateAutoMLPredictorCommand, Accuracy Metrics, and Weather Signals

Amazon Forecast's predictor is the ML model training run that learns patterns from your imported datasets. The modern API is CreateAutoMLPredictorCommand — it automatically evaluates multiple algorithms (DeepAR+, CNN-QR, Prophet, ARIMA, ETS, NPTS) and ensembles the best combination. Training takes 20–90 minutes depending on dataset size and horizon length. After training, GetAccuracyMetricsCommand returns backtesting metrics (RMSE, WAPE, MASE, MAPE) you can use to decide whether the forecast is accurate enough to deploy to your MCP server tools.

TL;DR

CreateAutoMLPredictorCommand — full parameter reference

import { CreateAutoMLPredictorCommand } from "@aws-sdk/client-forecast";

const { PredictorArn } = await forecast.send(new CreateAutoMLPredictorCommand({
  PredictorName: "mcp-endpoint-traffic-predictor-v1",
  ForecastHorizon: 24,         // 24 hours ahead (DataFrequency is "H")
  ForecastFrequency: "H",      // must match the target dataset's DataFrequency
  ForecastDimensions: [],      // additional grouping dimensions beyond item_id — leave empty for CUSTOM domain
  DataConfig: {
    DatasetGroupArn,
    AttributeConfigs: [
      {
        AttributeName: "target_value",
        Transformations: {
          // How to fill missing time steps in target series:
          // "median" — fill with the item's historical median (best for sparse data)
          // "mean"   — fill with the item's mean
          // "zero"   — treat gaps as zero (use for count data where missing = no events)
          // "nan"    — omit the row from training (default if not specified)
          // "value"  — fill with a specific numeric value
          "filling": "zero",
          // "frontfill" and "backfill" are supported for related time series
        },
      },
    ],
    AdditionalDatasets: [
      // Optional: add AWS-managed holiday calendar (free, no schema change needed)
      {
        Name: "CALENDAR_ASSOCIATED_DATA",
        Configuration: {
          CountryCode: ["US"],    // ISO 3166-1 alpha-2; multiple codes supported
        },
      },
      // Optional: add weather signals (requires geolocation column in target schema)
      // {
      //   Name: "WEATHER_INDEX",
      //   Configuration: {
      //     Country: ["US"],
      //     TimeZone: ["UTC"],
      //   },
      // },
    ],
  },
  ExplainPredictor: true,       // generates per-feature explainability scores (adds ~10min)
  Tags: [{ Key: "project", Value: "alivemcp" }],
}));

console.log("Predictor ARN:", PredictorArn);

ForecastHorizon sizing

ForecastHorizon defines how far into the future the model predicts, expressed as a count of ForecastFrequency intervals. The relationship:

ForecastFrequencyForecastHorizon: 24ForecastHorizon: 168
"1min"24 minutes ahead2.8 hours ahead
"H"24 hours ahead7 days ahead
"D"24 days ahead24 weeks ahead

Longer horizons require more historical data and produce wider prediction intervals. Amazon Forecast requires at least 3× the horizon length of historical data for reliable predictions. For a 24-hour horizon with hourly data, you need at least 72 hours of history; for meaningful seasonality detection, 2–4 weeks minimum is recommended.

The maximum ForecastHorizon is 500 intervals. If your use case requires longer, use daily aggregation instead of hourly to extend the coverage window.

AdditionalDatasets: CALENDAR_ASSOCIATED_DATA

The holiday calendar dataset is free, requires no schema changes, and helps the model recognize that traffic spikes or drops on public holidays are systematic, not noise:

AdditionalDatasets: [{
  Name: "CALENDAR_ASSOCIATED_DATA",
  Configuration: {
    CountryCode: ["US", "GB"],  // supports multiple countries
  },
}]

Supported country codes include "US", "GB", "DE", "FR", "JP", "AU", "CA", and others. The calendar covers national holidays and regional observances. For MCP server traffic, this is particularly useful if your endpoint usage drops on public holidays (developer tools often show 30–50% traffic reduction on major holidays).

AdditionalDatasets: WEATHER_INDEX

The weather index adds temperature, precipitation, wind speed, and cloud cover as covariates — useful for applications where weather correlates with usage (e.g., travel or outdoor activity apps). It requires a geolocation attribute in the target time series schema:

// Schema must include geolocation:
Schema: {
  Attributes: [
    { AttributeName: "item_id",      AttributeType: "string" },
    { AttributeName: "timestamp",    AttributeType: "timestamp" },
    { AttributeName: "target_value", AttributeType: "float" },
    { AttributeName: "geolocation",  AttributeType: "geolocation" },
    // geolocation values in CSV: "47.6062,-122.3321" (lat,lon — NOTE: lat first here, opposite of GeoJSON)
  ],
},

// Then in AdditionalDatasets:
AdditionalDatasets: [{
  Name: "WEATHER_INDEX",
  Configuration: {
    Country: ["US"],       // ISO 3166-1 alpha-2 country codes
    TimeZone: ["UTC"],     // must match the timezone of your timestamps
  },
}]

Note: geolocation format in Forecast CSV data is "latitude,longitude" (latitude first) — this is different from GeoJSON and Amazon Location Service which use longitude-first order. Using longitude-first format in Forecast silently assigns weather from the wrong location.

Weather index is billed at $0.088/GB of weather data added. For most MCP server use cases, the holiday calendar is more impactful and cost-effective than weather signals.

Missing value fills: AttributeConfigs

When your target time series has gaps (some timestamps missing for some items), Forecast needs a strategy for handling them during training. The AttributeConfigs Transformations map controls this:

Fill strategyBest forAvoid when
"zero"Count data where missing = no events (request counts during maintenance windows)Latency metrics — zero latency is physically impossible and corrupts training
"median"Sparse metrics where gaps represent "no change" rather than zeroHigh-volume data where median fill would mask real seasonality
"mean"Dense data with occasional gapsSkewed distributions where mean is misleading
"nan"Items with intentional gaps (endpoint was offline, monitoring paused)Items with frequent gaps — too many NaN rows degrade model quality
"value"Latency metrics where you want to fill with a known baseline (e.g., 500ms timeout)When a sensible default value isn't known

Polling for training completion

import { DescribeAutoPredictorCommand } from "@aws-sdk/client-forecast";

// IMPORTANT: use DescribeAutoPredictorCommand, NOT DescribePredictorCommand
// for predictors created with CreateAutoMLPredictorCommand

async function waitForPredictor(PredictorArn) {
  while (true) {
    const { Status, Message, OptimizationMetric } = await forecast.send(
      new DescribeAutoPredictorCommand({ PredictorArn })
    );
    console.log(`Predictor status: ${Status}`);
    if (Status === "ACTIVE") {
      console.log("Optimization metric:", OptimizationMetric);
      return;
    }
    if (Status === "CREATE_FAILED") {
      throw new Error(`Predictor training failed: ${Message}`);
    }
    // Training takes 20–90 minutes — poll every 2 minutes
    await new Promise(r => setTimeout(r, 120_000));
  }
}

await waitForPredictor(PredictorArn);

Reading accuracy metrics

After training completes, Forecast runs backtesting: it withholds the most recent ForecastHorizon data points and measures how well the model predicted them. Access these metrics with GetAccuracyMetricsCommand:

import { GetAccuracyMetricsCommand } from "@aws-sdk/client-forecast";

const { PredictorEvaluationResults } = await forecast.send(
  new GetAccuracyMetricsCommand({ PredictorArn })
);

for (const result of PredictorEvaluationResults) {
  console.log("Algorithm:", result.AlgorithmArn);
  for (const window of result.TestWindows) {
    const m = window.Metrics;
    console.log({
      RMSE: m.RMSE,       // Root Mean Square Error — absolute error in target units
      WAPE: m.WAPE,       // Weighted Absolute Percentage Error — relative accuracy (0.1 = 10% error)
      MASE: m.MASE,       // Mean Absolute Scaled Error — relative to naïve seasonal baseline (1.0 = no better than naive)
      MAPE: m.MAPE,       // Mean Absolute Percentage Error — alternative to WAPE, sensitive to near-zero values
    });
    // Quantile losses per ForecastType requested:
    for (const q of m.WeightedQuantileLosses) {
      console.log(`p${Math.round(q.Quantile * 100)} loss:`, q.LossValue);
    }
  }
}

Interpreting the metrics

MetricGood rangeNotes
WAPE< 0.20 (20%)Primary metric for most time series; 0.10–0.15 is excellent for MCP traffic
RMSEContext-dependentIn target-value units; useful for capacity planning (can compare to max daily range)
MASE< 1.0Values > 1.0 mean the model is worse than a naïve seasonal baseline — retrain with more data or longer history
MAPE< 0.20Can be misleading when target_value has near-zero values; prefer WAPE for sparse data

If MASE > 1.0, the AutoPredictor has not found a meaningful pattern. Common causes: insufficient history (less than 2–4 seasonal cycles), very noisy data (random failures with no pattern), or a data quality problem in the import (verify row counts via FieldStatistics as described in the dataset import guide).

Explainability scores

Setting ExplainPredictor: true causes Forecast to generate a PredictorExplainability resource that ranks which input features (columns in your schema, or built-in signals like holidays) have the most influence on the forecast. This adds ~10 minutes to training but is valuable for debugging unexpectedly wide prediction intervals:

import { DescribePredictorBacktestExportJobCommand, ListExplainabilityExportsCommand } from "@aws-sdk/client-forecast";

// List explainability resources for this predictor
const { Explainabilities } = await forecast.send(
  new ListExplainabilityExportsCommand({
    Filters: [{ Condition: "IS", Key: "PredictorArn", Value: PredictorArn }],
  })
);

Automatic retraining (RetrainingFrequency)

AutoPredictors support scheduled retraining so your forecast stays fresh as new data arrives:

const { PredictorArn } = await forecast.send(new CreateAutoMLPredictorCommand({
  PredictorName: "mcp-endpoint-auto-retrain",
  ForecastHorizon: 24,
  ForecastFrequency: "H",
  DataConfig: { DatasetGroupArn },
  // Retrain monthly on new data:
  // RetrainingFrequency: "M",   // "Y" | "M" | "W" | "D"
}));

When a retraining cycle completes, the new predictor version is automatically used for any CreateForecastCommand calls that reference PredictorArn. Existing forecast artifacts (created from the old predictor) remain valid until explicitly deleted.

Deleting a predictor

import { DeletePredictorCommand } from "@aws-sdk/client-forecast";

// Must delete all forecast artifacts that reference this predictor first
// (CreateForecastCommand outputs) — see the forecast query guide

await forecast.send(new DeletePredictorCommand({ PredictorArn }));

Deletion is asynchronous. Poll DescribeAutoPredictorCommand until the resource returns ResourceNotFoundException to confirm deletion is complete before deleting the dataset group.

Continue in this series

Related guides: SageMaker endpoints with MCP servers · CloudWatch metrics for MCP servers