Class BayesianStructuralTimeSeriesModel<T>
- Namespace
- AiDotNet.TimeSeries
- Assembly
- AiDotNet.dll
Implements a Bayesian Structural Time Series model for flexible time series forecasting.
public class BayesianStructuralTimeSeriesModel<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 type used for calculations (e.g., float, double, decimal).
- Inheritance
-
BayesianStructuralTimeSeriesModel<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
The Bayesian Structural Time Series (BSTS) model is a powerful and flexible approach for analyzing and forecasting time series data. It decomposes a time series into interpretable components including level, trend, seasonality, and regression effects, using Bayesian methods to handle uncertainty and combine information from different sources.
For Beginners: A Bayesian Structural Time Series model is like having a flexible toolkit for forecasting time series data. Unlike simpler models like AR or ARIMA that use fixed patterns, BSTS breaks down your data into meaningful components:
- Level: The current "baseline" value of your series
- Trend: Whether your data is generally increasing or decreasing over time
- Seasonal patterns: Regular cycles in your data (daily, weekly, yearly, etc.)
- Effects of external factors: How other variables influence your data
The "Bayesian" part means the model handles uncertainty well. Instead of making single point predictions, it gives you a range of possible outcomes with probabilities attached. It uses something called a "Kalman filter" to continually update its understanding as new data arrives.
BSTS models are especially powerful because they:
- Can handle missing data
- Allow you to incorporate external information
- Provide predictions with uncertainty ranges
- Let you see which components are driving your forecast
This makes them ideal for analyzing complex time series where you want to understand what's driving changes in addition to making predictions.
Constructors
BayesianStructuralTimeSeriesModel(BayesianStructuralTimeSeriesOptions<T>?)
Creates a new Bayesian Structural Time Series model with the specified options.
public BayesianStructuralTimeSeriesModel(BayesianStructuralTimeSeriesOptions<T>? options = null)
Parameters
optionsBayesianStructuralTimeSeriesOptions<T>Options for configuring the BSTS model. If null, default options are used.
Remarks
For Beginners: This constructor creates a new BSTS model, initializing all its components. You can provide options to customize the model, such as:
- Whether to include a trend component
- What seasonal patterns to look for (weekly, monthly, etc.)
- Whether to include external factors (regression)
- Technical parameters that control how the model learns
If you don't provide options, the model will use default settings, but it's usually better to configure it specifically for your data.
Properties
SupportsJitCompilation
Gets whether this model supports JIT compilation.
public override bool SupportsJitCompilation { get; }
Property Value
- bool
Returns
truewhen the model has estimated components. Prediction uses the point estimates from Bayesian inference.
Remarks
For Beginners: While BSTS training uses MCMC sampling, prediction uses point estimates and can be JIT compiled.
Methods
Clone()
Creates a deep copy of the current model.
public override IFullModel<T, Matrix<T>, Vector<T>> Clone()
Returns
- IFullModel<T, Matrix<T>, Vector<T>>
A new instance of the BSTS model with the same state and parameters.
Remarks
This method creates a complete copy of the model, including its configuration and trained components.
For Beginners: This method creates an exact duplicate of your trained model.
Unlike CreateInstance(), which creates a blank model with the same settings, Clone() creates a complete copy including:
- The model configuration (level, trend, seasonal settings, etc.)
- All trained components and their current values
- The current uncertainty estimates
This is useful for:
- Creating a backup before experimenting with a model
- Using the same trained model in multiple scenarios
- Creating ensemble models that use variations of the same base model
CreateInstance()
Creates a new instance of the BSTS model with the same options.
protected override IFullModel<T, Matrix<T>, Vector<T>> CreateInstance()
Returns
- IFullModel<T, Matrix<T>, Vector<T>>
A new instance of the BSTS model.
Remarks
This method creates a new, uninitialized instance of the BSTS model with the same configuration options.
For Beginners: This method creates a fresh copy of the model with the same settings.
Think of this like creating a new blank notebook with the same paper quality, size, and number of pages as another notebook, but without copying any of the written content.
This is used internally by the framework to create new model instances when needed, such as when cloning a model or creating ensemble models.
DeserializeCore(BinaryReader)
Deserializes the model's state from a binary stream.
protected override void DeserializeCore(BinaryReader reader)
Parameters
readerBinaryReaderThe binary reader to read from.
Remarks
For Beginners: This protected method loads a previously saved model from a file or stream.
Deserialization allows you to:
- Load a previously trained model
- Use it immediately without retraining
- Apply the exact same model to new data
The method loads all essential components that were saved during serialization:
- The level and trend values
- Seasonal components
- State covariance matrix
- Observation variance
- Key model options
After deserialization, the model is ready to make predictions as if it had just been trained.
EvaluateModel(Matrix<T>, Vector<T>)
Evaluates the model's performance on test data.
public override Dictionary<string, T> EvaluateModel(Matrix<T> xTest, Vector<T> yTest)
Parameters
xTestMatrix<T>Matrix of exogenous variables for testing.
yTestVector<T>Vector of actual target values for testing.
Returns
- Dictionary<string, T>
Dictionary of evaluation metrics (MSE, RMSE, MAE, MAPE).
Remarks
For Beginners: This method measures how well the model performs by comparing its predictions against actual values from a test dataset.
It calculates several common error metrics:
MSE (Mean Squared Error): Average of squared differences between predictions and actual values. Lower is better, but squaring emphasizes large errors. MSE is useful for comparing models but harder to interpret directly.
RMSE (Root Mean Squared Error): Square root of MSE, which gives errors in the same units as your original data. For example, if forecasting sales in dollars, RMSE is also in dollars.
MAE (Mean Absolute Error): Average of absolute differences between predictions and actual values. Easier to interpret than MSE and treats all error sizes equally.
MAPE (Mean Absolute Percentage Error): Average of percentage differences between predictions and actual values. Useful for understanding relative size of errors. For example, MAPE = 5% means predictions are off by 5% on average.
Lower values for all these metrics indicate better performance.
ExportComputationGraph(List<ComputationNode<T>>)
Exports the BSTS 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: forecast = level + trend + seasonal
Forecast(Vector<T>, int, Matrix<T>?)
Forecasts future values based on a history of time series data and optional exogenous variables.
public Vector<T> Forecast(Vector<T> history, int horizon, Matrix<T>? exogenousVariables = null)
Parameters
historyVector<T>The historical time series data.
horizonintThe number of future periods to predict.
exogenousVariablesMatrix<T>Optional matrix of external variables for future periods.
Returns
- Vector<T>
A vector of predicted values for future periods.
Remarks
This method generates forecasts for future time periods based on the trained model, historical data, and optional external variables.
For Beginners: This method forecasts future values based on past data.
Given:
- A series of past observations (the "history")
- The number of future periods to predict (the "horizon")
- Optional external factors that might affect predictions
This method projects each component of the model forward:
- The level continues at its current value with possible trend adjustments
- Seasonal patterns repeat as expected
- External variables influence the forecast according to learned relationships
For example, if forecasting retail sales, this method might predict:
- Continuing the overall upward trend
- Adding holiday peaks in appropriate months
- Adjusting for planned promotions or price changes (if included as external variables)
GetModelMetadata()
Gets metadata about the trained model, including its type, components, and configuration.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
Remarks
This method provides comprehensive information about the model, including its type, parameters, components, and serialized state. This metadata can be used for model inspection, selection, or persistence.
For Beginners: This method returns a complete description of your trained model.
The metadata includes:
- The type of model (BSTS in this case)
- The current values for level, trend, and seasonal components
- The configuration options you specified when creating the model
- A serialized version of the entire model that can be saved
This is useful for:
- Comparing different models to choose the best one
- Documenting what model was used for a particular analysis
- Saving model details for future reference
- Understanding which components are most important in your forecasts
Predict(Matrix<T>)
Makes predictions using the trained BSTS model.
public override Vector<T> Predict(Matrix<T> input)
Parameters
inputMatrix<T>Matrix of exogenous variables for the periods to predict.
Returns
- Vector<T>
Vector of predicted values.
Remarks
For Beginners: This method uses the trained model to forecast future values of your time series.
For each future time point in your input:
- It predicts the state of all model components
- Combines these components to generate a prediction
The prediction includes:
- The level (baseline value)
- Trend projections (if enabled)
- Seasonal effects appropriate for that time point
- Effects of external variables (if regression is enabled)
Unlike simpler models, BSTS accounts for all these components separately, giving you more accurate and interpretable forecasts.
If you need uncertainty intervals around these predictions, you would typically use additional methods that build on this prediction process.
PredictSingle(Vector<T>)
Predicts a single value based on a single input vector of external regressors.
public override T PredictSingle(Vector<T> input)
Parameters
inputVector<T>Vector of external regressors for a single time point.
Returns
- T
The predicted value for that time point.
Remarks
This method provides a convenient way to get a prediction for a single time point without having to create a matrix with a single row.
For Beginners: This is a shortcut for getting just one prediction.
Instead of providing a table of inputs for multiple time periods, you can provide just one set of external factors and get back a single prediction.
For example, if you want to predict tomorrow's sales based on tomorrow's promotions, weather forecast, and other factors, this method lets you do that directly.
Under the hood, it:
- Takes your single set of inputs
- Creates a small table with just one row
- Gets a prediction using the main prediction engine
- Returns that single prediction to you
Reset()
Resets the model to its untrained state.
public override void Reset()
Remarks
This method clears the trained components, effectively resetting the model to its initial state.
For Beginners: This method erases all the learned patterns from your model.
After calling this method:
- The level returns to its initial value
- The trend (if included) returns to its initial value
- All seasonal components are reset to zero
- Regression coefficients (if included) are cleared
- All variance parameters return to their initial values
The model behaves as if it was never trained, and you would need to train it again before making predictions.
SerializeCore(BinaryWriter)
Serializes the model's state to a binary stream.
protected override void SerializeCore(BinaryWriter writer)
Parameters
writerBinaryWriterThe binary writer to write to.
Remarks
For Beginners: This protected method saves the model's internal state to a file or stream.
Serialization allows you to:
- Save a trained model to disk
- Load it later without having to retrain
- Share the model with others
The method saves all essential components:
- The level and trend values
- Seasonal components
- State covariance matrix
- Observation variance
- Key model options
This allows the model to be fully reconstructed later.
TrainCore(Matrix<T>, Vector<T>)
Implements the core training algorithm for the Bayesian Structural Time Series model.
protected override void TrainCore(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>Feature matrix of external variables.
yVector<T>Target vector of time series values.
Remarks
This method contains the implementation details of the training process, handling initialization, Kalman filtering, smoothing, and parameter estimation.
For Beginners: This is the engine room of the training process.
While the public Train method provides a high-level interface, this method does the actual work:
- Initializes regression coefficients for external factors (if included)
- Runs the Kalman filter to estimate model components based on historical data
- Optionally performs backward smoothing to improve estimates using all available information
- Estimates optimal parameters to balance fit and flexibility
Think of it as the detailed step-by-step recipe that the chef follows when you order a meal.