TimeSeriesCatalog.ForecastBySsa Метод

Определение

Модель сингулярного анализа спектра (SSA) для однопараметрического прогнозирования временных рядов. Подробные сведения о модели см. в http://arxiv.org/pdf/1206.6910.pdfразделе .

public static Microsoft.ML.Transforms.TimeSeries.SsaForecastingEstimator ForecastBySsa (this Microsoft.ML.ForecastingCatalog catalog, string outputColumnName, string inputColumnName, int windowSize, int seriesLength, int trainSize, int horizon, bool isAdaptive = false, float discountFactor = 1, Microsoft.ML.Transforms.TimeSeries.RankSelectionMethod rankSelectionMethod = Microsoft.ML.Transforms.TimeSeries.RankSelectionMethod.Exact, int? rank = default, int? maxRank = default, bool shouldStabilize = true, bool shouldMaintainInfo = false, Microsoft.ML.Transforms.TimeSeries.GrowthRatio? maxGrowth = default, string confidenceLowerBoundColumn = default, string confidenceUpperBoundColumn = default, float confidenceLevel = 0.95, bool variableHorizon = false);
static member ForecastBySsa : Microsoft.ML.ForecastingCatalog * string * string * int * int * int * int * bool * single * Microsoft.ML.Transforms.TimeSeries.RankSelectionMethod * Nullable<int> * Nullable<int> * bool * bool * Nullable<Microsoft.ML.Transforms.TimeSeries.GrowthRatio> * string * string * single * bool -> Microsoft.ML.Transforms.TimeSeries.SsaForecastingEstimator
<Extension()>
Public Function ForecastBySsa (catalog As ForecastingCatalog, outputColumnName As String, inputColumnName As String, windowSize As Integer, seriesLength As Integer, trainSize As Integer, horizon As Integer, Optional isAdaptive As Boolean = false, Optional discountFactor As Single = 1, Optional rankSelectionMethod As RankSelectionMethod = Microsoft.ML.Transforms.TimeSeries.RankSelectionMethod.Exact, Optional rank As Nullable(Of Integer) = Nothing, Optional maxRank As Nullable(Of Integer) = Nothing, Optional shouldStabilize As Boolean = true, Optional shouldMaintainInfo As Boolean = false, Optional maxGrowth As Nullable(Of GrowthRatio) = Nothing, Optional confidenceLowerBoundColumn As String = Nothing, Optional confidenceUpperBoundColumn As String = Nothing, Optional confidenceLevel As Single = 0.95, Optional variableHorizon As Boolean = false) As SsaForecastingEstimator

Параметры

catalog
ForecastingCatalog

Каталог.

outputColumnName
String

Имя столбца, полученного в результате преобразования inputColumnName.

inputColumnName
String

Имя преобразуемого столбца. Если задано значение null, значение будет использоваться в outputColumnName качестве источника. Вектор содержит в качестве первых трех значений оповещение, необработанную оценку, P-значение.

windowSize
Int32

Длина окна ряда для построения матрицы траектории (параметр L).

seriesLength
Int32

Длина ряда, хранящееся в буфере для моделирования (параметр N).

trainSize
Int32

Длина ряда с самого начала, используемого для обучения.

horizon
Int32

Число прогнозируемых значений.

isAdaptive
Boolean

Флаг, определяющий, является ли модель адаптивной.

discountFactor
Single

Коэффициент скидки в [0,1], используемый для онлайн-обновлений.

rankSelectionMethod
RankSelectionMethod

Метод выбора ранга.

rank
Nullable<Int32>

Требуемый ранг подпространства, используемого для проекции SSA (параметр r). Этот параметр должен находиться в диапазоне [1, windowSize]. Если задано значение NULL, ранг автоматически определяется на основе минимизации ошибок прогнозирования.

maxRank
Nullable<Int32>

Максимальный ранг, учитываемый в процессе выбора ранга. Если параметр не указан (т. е. имеет значение NULL), для него устанавливается значение windowSize - 1.

shouldStabilize
Boolean

Флаг, определяющий, следует ли стабилизировать модель.

shouldMaintainInfo
Boolean

Флаг, определяющий, требуется ли поддерживать метаданные для модели.

maxGrowth
Nullable<GrowthRatio>

Максимальный рост экспоненциального тренда.

confidenceLowerBoundColumn
String

Имя столбца нижней границы доверительного интервала. Если этот параметр не указан, доверительный интервал вычисляться не будет.

confidenceUpperBoundColumn
String

Имя верхнего граничного столбца доверительного интервала. Если этот параметр не указан, доверительный интервал вычисляться не будет.

confidenceLevel
Single

Уровень достоверности для прогнозирования.

variableHorizon
Boolean

Присвойте этому параметру значение true, если горизонт изменится после обучения (во время прогнозирования).

Возвращаемое значение

Примеры

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.ML;
using Microsoft.ML.Transforms.TimeSeries;

namespace Samples.Dynamic
{
    public static class Forecasting
    {
        // This example creates a time series (list of Data with the i-th element
        // corresponding to the i-th time slot) and then does forecasting.
        public static void Example()
        {
            // Create a new ML context, for ML.NET operations. It can be used for
            // exception tracking and logging, as well as the source of randomness.
            var ml = new MLContext();

            // Generate sample series data with a recurring pattern.
            var data = new List<TimeSeriesData>()
            {
                new TimeSeriesData(0),
                new TimeSeriesData(1),
                new TimeSeriesData(2),
                new TimeSeriesData(3),
                new TimeSeriesData(4),

                new TimeSeriesData(0),
                new TimeSeriesData(1),
                new TimeSeriesData(2),
                new TimeSeriesData(3),
                new TimeSeriesData(4),

                new TimeSeriesData(0),
                new TimeSeriesData(1),
                new TimeSeriesData(2),
                new TimeSeriesData(3),
                new TimeSeriesData(4),
            };

            // Convert data to IDataView.
            var dataView = ml.Data.LoadFromEnumerable(data);

            // Setup arguments.
            var inputColumnName = nameof(TimeSeriesData.Value);
            var outputColumnName = nameof(ForecastResult.Forecast);

            // Instantiate the forecasting model.
            var model = ml.Forecasting.ForecastBySsa(outputColumnName,
                inputColumnName, 5, 11, data.Count, 5);

            // Train.
            var transformer = model.Fit(dataView);

            // Forecast next five values.
            var forecastEngine = transformer.CreateTimeSeriesEngine<TimeSeriesData,
                ForecastResult>(ml);

            var forecast = forecastEngine.Predict();

            Console.WriteLine($"Forecasted values:");
            Console.WriteLine("[{0}]", string.Join(", ", forecast.Forecast));
            // Forecasted values:
            // [1.977226, 1.020494, 1.760543, 3.437509, 4.266461]

            // Update with new observations.
            forecastEngine.Predict(new TimeSeriesData(0));
            forecastEngine.Predict(new TimeSeriesData(0));
            forecastEngine.Predict(new TimeSeriesData(0));
            forecastEngine.Predict(new TimeSeriesData(0));

            // Checkpoint.
            forecastEngine.CheckPoint(ml, "model.zip");

            // Load the checkpointed model from disk.
            // Load the model.
            ITransformer modelCopy;
            using (var file = File.OpenRead("model.zip"))
                modelCopy = ml.Model.Load(file, out DataViewSchema schema);

            // We must create a new prediction engine from the persisted model.
            var forecastEngineCopy = modelCopy.CreateTimeSeriesEngine<
                TimeSeriesData, ForecastResult>(ml);

            // Forecast with the checkpointed model loaded from disk.
            forecast = forecastEngineCopy.Predict();
            Console.WriteLine("[{0}]", string.Join(", ", forecast.Forecast));
            // [1.791331, 1.255525, 0.3060154, -0.200446, 0.5657795]

            // Forecast with the original model(that was checkpointed to disk).
            forecast = forecastEngine.Predict();
            Console.WriteLine("[{0}]", string.Join(", ", forecast.Forecast));
            // [1.791331, 1.255525, 0.3060154, -0.200446, 0.5657795]

        }

        class ForecastResult
        {
            public float[] Forecast { get; set; }
        }

        class TimeSeriesData
        {
            public float Value;

            public TimeSeriesData(float value)
            {
                Value = value;
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.ML;
using Microsoft.ML.Transforms.TimeSeries;

namespace Samples.Dynamic
{
    public static class ForecastingWithConfidenceInternal
    {
        // This example creates a time series (list of Data with the i-th element
        // corresponding to the i-th time slot) and then does forecasting.
        public static void Example()
        {
            // Create a new ML context, for ML.NET operations. It can be used for
            // exception tracking and logging, as well as the source of randomness.
            var ml = new MLContext();

            // Generate sample series data with a recurring pattern.
            var data = new List<TimeSeriesData>()
            {
                new TimeSeriesData(0),
                new TimeSeriesData(1),
                new TimeSeriesData(2),
                new TimeSeriesData(3),
                new TimeSeriesData(4),

                new TimeSeriesData(0),
                new TimeSeriesData(1),
                new TimeSeriesData(2),
                new TimeSeriesData(3),
                new TimeSeriesData(4),

                new TimeSeriesData(0),
                new TimeSeriesData(1),
                new TimeSeriesData(2),
                new TimeSeriesData(3),
                new TimeSeriesData(4),
            };

            // Convert data to IDataView.
            var dataView = ml.Data.LoadFromEnumerable(data);

            // Setup arguments.
            var inputColumnName = nameof(TimeSeriesData.Value);
            var outputColumnName = nameof(ForecastResult.Forecast);

            // Instantiate the forecasting model.
            var model = ml.Forecasting.ForecastBySsa(outputColumnName,
                inputColumnName, 5, 11, data.Count, 5,
                confidenceLevel: 0.95f,
                confidenceLowerBoundColumn: "ConfidenceLowerBound",
                confidenceUpperBoundColumn: "ConfidenceUpperBound");

            // Train.
            var transformer = model.Fit(dataView);

            // Forecast next five values.
            var forecastEngine = transformer.CreateTimeSeriesEngine<TimeSeriesData,
                ForecastResult>(ml);

            var forecast = forecastEngine.Predict();

            PrintForecastValuesAndIntervals(forecast.Forecast, forecast
                .ConfidenceLowerBound, forecast.ConfidenceUpperBound);
            // Forecasted values:
            // [1.977226, 1.020494, 1.760543, 3.437509, 4.266461]
            // Confidence intervals:
            // [0.3451088 - 3.609343] [-0.7967533 - 2.83774] [-0.058467 - 3.579552] [1.61505 - 5.259968] [2.349299 - 6.183623]

            // Update with new observations.
            forecastEngine.Predict(new TimeSeriesData(0));
            forecastEngine.Predict(new TimeSeriesData(0));
            forecastEngine.Predict(new TimeSeriesData(0));
            forecastEngine.Predict(new TimeSeriesData(0));

            // Checkpoint.
            forecastEngine.CheckPoint(ml, "model.zip");

            // Load the checkpointed model from disk.
            // Load the model.
            ITransformer modelCopy;
            using (var file = File.OpenRead("model.zip"))
                modelCopy = ml.Model.Load(file, out DataViewSchema schema);

            // We must create a new prediction engine from the persisted model.
            var forecastEngineCopy = modelCopy.CreateTimeSeriesEngine<
                TimeSeriesData, ForecastResult>(ml);

            // Forecast with the checkpointed model loaded from disk.
            forecast = forecastEngineCopy.Predict();
            PrintForecastValuesAndIntervals(forecast.Forecast, forecast
                .ConfidenceLowerBound, forecast.ConfidenceUpperBound);

            // [1.791331, 1.255525, 0.3060154, -0.200446, 0.5657795]
            // Confidence intervals:
            // [0.1592142 - 3.423448] [-0.5617217 - 3.072772] [-1.512994 - 2.125025] [-2.022905 - 1.622013] [-1.351382 - 2.482941]

            // Forecast with the original model(that was checkpointed to disk).
            forecast = forecastEngine.Predict();
            PrintForecastValuesAndIntervals(forecast.Forecast,
                forecast.ConfidenceLowerBound, forecast.ConfidenceUpperBound);

            // [1.791331, 1.255525, 0.3060154, -0.200446, 0.5657795]
            // Confidence intervals:
            // [0.1592142 - 3.423448] [-0.5617217 - 3.072772] [-1.512994 - 2.125025] [-2.022905 - 1.622013] [-1.351382 - 2.482941]
        }

        static void PrintForecastValuesAndIntervals(float[] forecast, float[]
            confidenceIntervalLowerBounds, float[] confidenceIntervalUpperBounds)
        {
            Console.WriteLine($"Forecasted values:");
            Console.WriteLine("[{0}]", string.Join(", ", forecast));
            Console.WriteLine($"Confidence intervals:");
            for (int index = 0; index < forecast.Length; index++)
                Console.Write($"[{confidenceIntervalLowerBounds[index]} -" +
                    $" {confidenceIntervalUpperBounds[index]}] ");
            Console.WriteLine();
        }

        class ForecastResult
        {
            public float[] Forecast { get; set; }
            public float[] ConfidenceLowerBound { get; set; }
            public float[] ConfidenceUpperBound { get; set; }
        }

        class TimeSeriesData
        {
            public float Value;

            public TimeSeriesData(float value)
            {
                Value = value;
            }
        }
    }
}

Применяется к