Class ARMAModel<T>
- Namespace
- AiDotNet.TimeSeries
- Assembly
- AiDotNet.dll
Implements an ARMA (AutoRegressive Moving Average) model for time series forecasting.
public class ARMAModel<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
-
ARMAModel<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
ARMA models combine two components to forecast time series data: - AR (AutoRegressive): Uses the relationship between an observation and a number of lagged observations - MA (Moving Average): Uses the relationship between an observation and residual errors from moving average model
For Beginners: The ARMA model is a popular method for analyzing and forecasting time series data (data collected over time, like daily temperatures, stock prices, or monthly sales).
Think of ARMA as combining two different approaches:
AutoRegressive (AR): This component predicts future values based on past values. For example, tomorrow's temperature might be related to today's temperature. If it's hot today, it's likely to be hot tomorrow as well.
Moving Average (MA): This component predicts future values based on past prediction errors. For example, if we consistently underestimate temperature, the MA component helps adjust our future predictions upward.
The model has two key parameters:
- p: The AR order - how many past values to consider
- q: The MA order - how many past prediction errors to consider
Unlike ARIMA, ARMA doesn't include the differencing (I) component, so it works best with time series data that is already stationary (doesn't have strong trends).
Constructors
ARMAModel(ARMAOptions<T>)
Creates a new ARMA model with the specified options.
public ARMAModel(ARMAOptions<T> options)
Parameters
optionsARMAOptions<T>Options for the ARMA model, including AR order, MA order, and training parameters.
Remarks
For Beginners: This constructor creates a new ARMA model. You need to provide options to customize the model:
- AROrder: How many past values to consider (like using yesterday and the day before to predict today)
- MAOrder: How many past prediction errors to consider
- LearningRate: How quickly the model adjusts during training
- MaxIterations: The maximum number of training attempts
- Tolerance: How precise the model needs to be before training stops
Choosing good values for these options depends on your specific data and requirements.
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 ARMA model with the same state and parameters.
Remarks
This method creates a complete copy of the model, including its configuration and trained coefficients.
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 (AR order, MA order, etc.)
- All trained coefficients and internal state
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
Think of it like photocopying a completed notebook - you get all the written content as well as the structure of the notebook itself.
CreateInstance()
Creates a new instance of the ARMA 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 ARMA model.
Remarks
This method creates a new, uninitialized instance of the ARMA 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:
- The AR and MA orders (how many coefficients)
- The AR coefficients (how past values affect predictions)
- The MA coefficients (how past errors affect predictions)
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>Feature matrix for testing.
yTestVector<T>Actual target values for testing.
Returns
- Dictionary<string, T>
A 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 squares the errors, so large errors have a bigger impact.
RMSE (Root Mean Squared Error): Square root of MSE, which gives errors in the same units as the original data. For example, if your data is 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 sizes of errors equally.
MAPE (Mean Absolute Percentage Error): Average of percentage differences between predictions and actual values. Useful for understanding the relative size of errors compared to the actual values.
Lower values for all these metrics indicate better performance.
Forecast(Vector<T>, int)
Predicts future values based on a history of time series data.
public override Vector<T> Forecast(Vector<T> history, int horizon)
Parameters
historyVector<T>The historical time series data.
horizonintThe number of future periods to predict.
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 and historical data. It uses a rolling prediction approach where each prediction becomes part of the history for subsequent predictions.
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")
This method:
- Uses the model to predict the next value after the history
- Adds that prediction to the extended history
- Uses the extended history to predict the next value
- Repeats until it has made predictions for the entire horizon
For example, if you have sales data for Jan-Jun and want to predict Jul-Sep (horizon=3), this method will predict Jul, then use Jan-Jul to predict Aug, then use Jan-Aug to predict Sep.
This approach is common in time series forecasting as it allows each prediction to build on previous predictions.
GetModelMetadata()
Gets metadata about the trained model, including its type, coefficients, 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, coefficients, 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 (ARMA in this case)
- The trained coefficients that determine predictions
- 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
Think of it like creating a detailed ID card for your model that contains all the important information about how it works and was configured.
Predict(Matrix<T>)
Makes predictions using the trained ARMA model.
public override Vector<T> Predict(Matrix<T> input)
Parameters
inputMatrix<T>Input matrix for prediction (typically just time indices for future periods).
Returns
- Vector<T>
A vector of predicted values.
Remarks
For Beginners: This method uses the trained ARMA model to forecast future values.
For each time point in the input, it calls the prediction helper method to generate a forecast based on:
- The AR component (effect of past values)
- The MA component (effect of past prediction errors)
The result is a vector of predicted values, one for each time point in the input.
Note: For pure time series forecasting, the input parameter might just indicate how many future periods to predict.
PredictSingle(Vector<T>)
Predicts a single value based on a single input vector.
public override T PredictSingle(Vector<T> input)
Parameters
inputVector<T>The input vector 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 inputs and get back a single prediction.
For ARMA models, the input typically represents a sequence of past values. This method looks at those past values and predicts what the next value will be, based on the patterns the model learned during training.
Under the hood, it:
- Takes your single input vector
- Creates a small table with just one row
- Gets a prediction using the main prediction engine
- Returns that single prediction to you
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 the essential components of the model:
- The AR and MA orders (how many coefficients)
- The AR coefficients (how past values affect predictions)
- The MA coefficients (how past errors affect predictions)
This allows the model to be fully reconstructed later.
ToString()
Returns a string representation of the ARMA model.
public override string ToString()
Returns
- string
A string describing the model and its parameters.
Remarks
This method provides a human-readable description of the ARMA model, including its orders and coefficients.
For Beginners: This method gives you a text description of your model.
The returned string includes:
- The type of model (ARMA)
- The AR and MA orders (how many past values and errors the model uses)
- The actual coefficient values (if the model has been trained)
This is useful for printing or logging model details, or for quickly seeing the structure of the model without examining all its properties individually.
TrainCore(Matrix<T>, Vector<T>)
Implements the core training algorithm for the ARMA model.
protected override void TrainCore(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>Feature matrix (typically just time indices for ARMA models).
yVector<T>Target vector (the time series values to be modeled).
Remarks
This method contains the implementation details of the training process, handling coefficient initialization, gradient calculation, and parameter updates.
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 both AR and MA coefficients for the model
- Calculates prediction errors with the current model
- Determines how to adjust both sets of coefficients to improve predictions
- Updates the coefficients accordingly
- Repeats until the improvements become very small
Think of it as the detailed step-by-step recipe that the chef follows when you order a meal.