TimeSeriesSplit

Models & Types · AiDotNet.Preprocessing.TimeSeries

Provides time-series cross-validation with expanding or sliding window splits.

For Beginners

When working with time series data (like stock prices or weather), you can’t randomly split the data like you would for regular machine learning.

Why? Because predicting the future using future data is cheating! If you train on data from 2023 to predict 2022, you’re using information you wouldn’t have had.

TimeSeriesSplit creates splits like this:

Each training set includes all previous data, and the test set is always “in the future” relative to the training data.

How It Works

Time series data requires special cross-validation that respects temporal ordering. Unlike standard k-fold cross-validation, time series splits ensure that:

  • Training data always comes before validation data
  • No future information “leaks” into the training set

Example

using AiDotNet.Preprocessing.TimeSeries;
var data = new Matrix<double>(new double[,] { { 1.0, 2.0 }, { 3.0, 4.0 }, { 5.0, 6.0 }, { 7.0, 8.0 } });
var split = new TimeSeriesSplit(nSplits: 5, maxTrainSize: 1000);
            
foreach (var (trainIndices, testIndices) in split.Split(data.Rows))
{
    // trainIndices contains indices for training data
    // testIndices contains indices for test/validation data
}

Constructors

Constructor Summary
TimeSeriesSplit(int nSplits, int? maxTrainSize, int? testSize, int gap) Creates a new TimeSeriesSplit with the specified configuration.

Properties

Property Summary
int Gap { get; } Gets the gap between train and test sets, useful to avoid data leakage.
int NSplits { get; } Gets the number of splits to generate.
int? MaxTrainSize { get; } Gets the maximum training set size.
int? TestSize { get; } Gets the test set size for each split.

Methods

Method Summary
IEnumerable<ValueTuple<int[], int[]>> Split(int nSamples) Generates train/test index splits for the given number of samples.
double[] CrossValidate(TData[] data, Func<TData[], TData[], double> evaluator) Performs cross-validation on time series data using the specified evaluation function.
int GetNSplits(int nSamples) Gets the number of splits that will be generated for the given number of samples.
string GetSplitSummary(int nSamples) Creates a summary of the split configuration for diagnostics.