Class STLDecomposition<T>
- Namespace
- AiDotNet.TimeSeries
- Assembly
- AiDotNet.dll
Implements Seasonal-Trend decomposition using LOESS (STL) for time series analysis.
public class STLDecomposition<T> : TimeSeriesModelBase<T>, ITimeSeriesModel<T>, IFullModel<T, Matrix<T>, Vector<T>>, IModel<Matrix<T>, Vector<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Matrix<T>, Vector<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Matrix<T>, Vector<T>>>, IGradientComputable<T, Matrix<T>, Vector<T>>, IJitCompilable<T>
Type Parameters
TThe numeric data type used for calculations (e.g., float, double).
- Inheritance
-
STLDecomposition<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
STL decomposition breaks down a time series into three components: trend, seasonal, and residual. It uses locally weighted regression (LOESS) to extract these components, making it robust to outliers and applicable to a wide range of time series data.
For Beginners: STL decomposition is like breaking down a song into its basic elements - the melody (trend), the repeating chorus (seasonal pattern), and the unique variations (residuals).
For example, if you analyze monthly sales data:
- The trend component shows the long-term increase or decrease in sales
- The seasonal component shows regular patterns that repeat (like higher sales during holidays)
- The residual component shows what's left after removing trend and seasonality (like unexpected events)
This decomposition helps you understand what's driving your time series and can improve forecasting. The model offers different algorithms (standard, robust, and fast) to handle various types of data.
Constructors
STLDecomposition(STLDecompositionOptions<T>?)
Initializes a new instance of the STLDecomposition class with optional configuration options.
public STLDecomposition(STLDecompositionOptions<T>? options = null)
Parameters
optionsSTLDecompositionOptions<T>The configuration options for STL decomposition. If null, default options are used.
Properties
SupportsJitCompilation
Gets whether this model supports JIT compilation.
public override bool SupportsJitCompilation { get; }
Property Value
- bool
Returns
truewhen the model has been trained with decomposed components. STL prediction for forecasting can be JIT compiled as it uses precomputed trend and seasonal components.
Remarks
For Beginners: While the STL decomposition itself uses iterative LOESS smoothing, the prediction/forecasting step is simple: trend + seasonal. This can be JIT compiled for efficient inference.
Methods
CreateInstance()
Creates a new instance of the STL decomposition model with the same options.
protected override IFullModel<T, Matrix<T>, Vector<T>> CreateInstance()
Returns
- IFullModel<T, Matrix<T>, Vector<T>>
A new STL decomposition model instance with the same configuration.
Remarks
This method creates a new instance of the STL decomposition model with the same configuration options as the current instance. The new instance is not trained and will need to be trained on data.
For Beginners: This method creates a fresh copy of your model with the same settings but no results.
It's useful when you want to:
- Apply the same decomposition approach to multiple datasets
- Create multiple variations of the model with slight modifications
- Share your model configuration with others
- Preserve your original settings while experimenting with new options
Think of it like copying a recipe before making modifications - you keep the original intact while creating a new version that you can change.
DeserializeCore(BinaryReader)
Deserializes the model's core parameters from a binary reader.
protected override void DeserializeCore(BinaryReader reader)
Parameters
readerBinaryReaderThe binary reader to read from.
Remarks
For Beginners: Deserialization is the process of loading a previously saved model from disk. This method reads the model's parameters from a file and reconstructs the model exactly as it was when it was saved.
This allows you to:
- Load a previously trained model without retraining
- Make predictions with consistent results
- Continue analysis from where you left off
It's like saving your work in a document and opening it later to continue editing.
EvaluateModel(Matrix<T>, Vector<T>)
Evaluates the performance of the trained model on test data.
public override Dictionary<string, T> EvaluateModel(Matrix<T> xTest, Vector<T> yTest)
Parameters
xTestMatrix<T>The input features matrix for testing.
yTestVector<T>The actual target values for testing.
Returns
- Dictionary<string, T>
A dictionary containing evaluation metrics.
Remarks
For Beginners: This method tests how well our model performs by comparing its predictions to actual values. It calculates two error metrics:
- MAE (Mean Absolute Error): The average of the absolute differences between predictions and actual values
- RMSE (Root Mean Squared Error): The square root of the average squared differences, which gives more weight to larger errors
Lower values for these metrics indicate better model performance. They help you understand how accurate your forecasts are likely to be and compare different models or parameter settings.
Exceptions
- InvalidOperationException
Thrown when the model has not been trained.
ExportComputationGraph(List<ComputationNode<T>>)
Exports the STL model as a computation graph for JIT compilation.
public override ComputationNode<T> ExportComputationGraph(List<ComputationNode<T>> inputNodes)
Parameters
inputNodesList<ComputationNode<T>>A list to which input nodes will be added.
Returns
- ComputationNode<T>
The output computation node representing the forecast.
Remarks
The computation graph represents the STL prediction formula: forecast = last_trend + seasonal[t % period]
For Beginners: This converts the STL forecasting logic into an optimized computation graph. Since prediction uses precomputed trend and seasonal components, it can be efficiently JIT compiled.
Expected speedup: 2-3x for inference after JIT compilation.
GetModelMetadata()
Gets metadata about the model, including its type, configuration, and information about the decomposed components.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
Remarks
This method returns detailed metadata about the model, including its type, configuration options, and information about the decomposed components. This metadata can be used for model selection, comparison, and documentation.
For Beginners: This method provides a summary of your model's configuration and what it has learned.
It includes information like:
- The type of model (STL Decomposition)
- The algorithm used (Standard, Robust, or Fast)
- The seasonal period and window sizes
- Details about the decomposed components (sizes, statistics)
This metadata is useful for:
- Comparing different decomposition approaches
- Documenting your analysis process
- Understanding what the model has extracted from your data
- Sharing model information with others
Think of it like getting a detailed report card for your decomposition analysis.
GetResidual()
Gets the residual component of the time series.
public Vector<T> GetResidual()
Returns
- Vector<T>
The residual component.
Remarks
For Beginners: The residual component is what remains after removing both trend and seasonal patterns. It includes random variations, noise, and any patterns not captured by the other components.
Analyzing residuals can help identify:
- Unusual events or outliers
- Additional patterns that might need modeling
- Whether the decomposition has successfully captured the main patterns in the data
Ideally, residuals should look like random noise with no obvious patterns.
Exceptions
- InvalidOperationException
Thrown when the model has not been trained.
GetSeasonal()
Gets the seasonal component of the time series.
public Vector<T> GetSeasonal()
Returns
- Vector<T>
The seasonal component.
Remarks
For Beginners: The seasonal component represents regular patterns that repeat at fixed intervals. These patterns might be related to time of day, day of week, month of year, or any other cyclical factor relevant to your data.
For example, retail sales might show a seasonal pattern with peaks in December (holiday shopping), back-to-school season, and other predictable times. The seasonal component captures these recurring patterns.
Exceptions
- InvalidOperationException
Thrown when the model has not been trained.
GetTrend()
Gets the trend component of the time series.
public Vector<T> GetTrend()
Returns
- Vector<T>
The trend component.
Remarks
For Beginners: The trend component represents the long-term direction of your time series. It shows whether your data is generally increasing, decreasing, or staying flat over time, after removing seasonal patterns and random fluctuations.
For example, in retail sales data, the trend might show steady growth over several years, even though there are seasonal peaks during holidays and random variations from month to month.
Exceptions
- InvalidOperationException
Thrown when the model has not been trained.
Predict(Matrix<T>)
Generates forecasts for future time periods based on the decomposed components.
public override Vector<T> Predict(Matrix<T> input)
Parameters
inputMatrix<T>The input features matrix specifying the forecast horizon.
Returns
- Vector<T>
A vector of forecasted values.
Remarks
For Beginners: This method predicts future values by:
- Using the last trend value (assuming the trend continues at the same level)
- Adding the appropriate seasonal pattern from the last observed season
This simple approach works well for short-term forecasts when the trend is relatively stable. For example, if we've decomposed monthly sales data and want to forecast the next few months, we'd use the most recent trend level and add the seasonal pattern from the same months in the previous year.
Exceptions
- InvalidOperationException
Thrown when the model has not been trained.
PredictSingle(Vector<T>)
Predicts a single value based on the decomposed components.
public override T PredictSingle(Vector<T> input)
Parameters
inputVector<T>The input vector containing time information.
Returns
- T
The predicted value.
Remarks
This method generates a prediction for a single future time point by combining the trend and seasonal components from the decomposition.
For Beginners: This method predicts a value for a single future time point by:
- Using the last known trend value (assuming the trend continues)
- Adding the appropriate seasonal pattern for that time point
For example, if you're forecasting sales for next January based on historical monthly data, it would:
- Use the most recent trend level (overall sales level)
- Add the January seasonal effect (how much January typically differs from average)
The input vector should contain the forecast horizon (how many steps ahead) and any other relevant information.
Exceptions
- InvalidOperationException
Thrown when the model has not been trained.
Reset()
Resets the model to its initial state.
public override void Reset()
Remarks
This method clears all decomposed components and returns the model to its initial state, as if it had just been created with the same options but not yet trained.
For Beginners: Resetting a model is like erasing the results of your analysis while keeping the settings.
This is useful when you want to:
- Reapply the decomposition to different data
- Try different algorithm types on the same data
- Compare results with different settings
- Start fresh after experimenting
For example, you might reset the model after analyzing monthly data to then analyze daily data with the same settings, or to compare the results of standard versus robust decomposition approaches on the same dataset.
SerializeCore(BinaryWriter)
Serializes the model's core parameters to a binary writer.
protected override void SerializeCore(BinaryWriter writer)
Parameters
writerBinaryWriterThe binary writer to write to.
Remarks
For Beginners: Serialization is the process of converting the model's state into a format that can be saved to disk. This allows you to save a trained model and load it later without having to retrain it.
This method saves:
- The STL configuration options (like seasonal period and window sizes)
- The decomposed components (trend, seasonal, and residual)
After serializing, you can store the model and later deserialize it to make predictions or continue analysis without repeating the decomposition process.
TrainCore(Matrix<T>, Vector<T>)
Implements the model-specific training logic for STL decomposition.
protected override void TrainCore(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>The input features matrix (not used in STL decomposition).
yVector<T>The time series data to decompose.
Remarks
This method handles the STL-specific training logic. It validates inputs and delegates to the appropriate algorithm implementation based on the configured algorithm type.
For Beginners: This is the core method that actually performs the decomposition of your time series into trend, seasonal, and residual components. It works behind the scenes to:
- Check that your data meets the required conditions (like having enough points)
- Choose the right algorithm based on your settings
- Break down your data into its components using that algorithm
The method is called automatically when you train the model, so you don't need to
call it directly. Instead, you interact with the higher-level Train method
that handles validation and preparation before calling this method.
Exceptions
- ArgumentException
Thrown when the time series is too short for the specified seasonal period.