Class MAModel<T>
- Namespace
- AiDotNet.TimeSeries
- Assembly
- AiDotNet.dll
Implements a Moving Average (MA) model for time series forecasting.
public class MAModel<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
-
MAModel<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
MA models predict future values based on past prediction errors (residuals). The model is defined as: Yt = μ + et + ?1et-1 + ?2et-2 + ... + ?qet-q where Yt is the value at time t, μ is the mean, et is the error term at time t, and ?i are the MA coefficients.
For Beginners: A Moving Average (MA) model predicts future values based on past prediction errors.
Think of it like this: If you've been consistently underestimating or overestimating values in the past, the MA model learns from these mistakes and adjusts future predictions.
For example, if a weather forecast has been consistently underestimating temperatures by 2 degrees for several days, an MA model would learn this pattern and adjust its future predictions upward.
The key parameter of an MA model is 'q', which determines how many past prediction errors to consider. For instance, with q=3, the model looks at errors from the last three periods when making a new prediction.
Constructors
MAModel(MAModelOptions<T>?)
Creates a new MA model with the specified options.
public MAModel(MAModelOptions<T>? options = null)
Parameters
optionsMAModelOptions<T>Options for the MA model, including the order (q) parameter. If null, default options are used.
Remarks
For Beginners: This constructor creates a new MA model. You can customize the model by providing options:
- q: How many past prediction errors to consider
If you don't provide options, default values will be used, but it's usually best to choose values that make sense for your specific data.
Methods
CreateInstance()
Creates a new instance of the MA 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 MA model.
Remarks
For Beginners: This method creates a fresh copy of the model with the same settings.
The new copy:
- Has the same q parameter as the original model
- Has the same configuration options
- Is untrained (doesn't have coefficients yet)
This is useful when you want to:
- Train multiple versions of the same model on different data
- Create ensemble models that combine predictions from multiple similar models
- Reset a model to start fresh while keeping the same structure
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 private 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 the parameters that were saved during serialization: the order (q) value, the mean of the series, the MA coefficients, and the recent errors.
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): The average of squared differences between predictions and actual values
- RMSE (Root Mean Squared Error): The square root of MSE, which is in the same units as the original data
- MAE (Mean Absolute Error): The average of absolute differences between predictions and actual values
- MAPE (Mean Absolute Percentage Error): The average percentage difference between predictions and actual values
Lower values for all these metrics indicate better performance.
GetModelMetadata()
Gets metadata about the model, including its type, parameters, and configuration.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
Remarks
For Beginners: This method provides a summary of your model's settings and what it has learned.
The metadata includes:
- The type of model (MA)
- The q parameter that defines the model structure
- The MA coefficients that were learned during training
- The mean value that serves as the baseline prediction
This information is useful for:
- Documenting your model for future reference
- Comparing different models to see which performs best
- Understanding what patterns the model has identified in your data
Predict(Matrix<T>)
Makes predictions using the trained MA 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 MA model to forecast future values.
The prediction process:
- Starts with the mean of the time series as a base value
- Adds the effects of recent prediction errors (MA component)
- For each prediction, updates the error history used for the next prediction
Since this is a pure MA model, predictions will gradually converge to the mean as we forecast further into the future, because we assume zero errors for future periods that we haven't observed yet.
PredictSingle(Vector<T>)
Predicts a single value based on the input vector.
public override T PredictSingle(Vector<T> input)
Parameters
inputVector<T>Input vector containing features for prediction (not used in MA models).
Returns
- T
The predicted value.
Remarks
For Beginners: This method generates a single prediction for the next time period.
In an MA model, predictions start with the mean of the series and then get adjusted based on recent prediction errors. The input parameter is typically not used in pure MA models since predictions depend only on past errors.
For example, if the average temperature is 70—F but we've been consistently underestimating by 2—F recently, the model might predict 72—F for tomorrow.
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 private 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 the essential parameters: the order (q) value, the mean of the series, the MA coefficients, and the recent errors.
TrainCore(Matrix<T>, Vector<T>)
Core implementation of the training logic for the MA model.
protected override void TrainCore(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>Feature matrix (typically just time indices for MA models).
yVector<T>Target vector (the time series values to be modeled).
Remarks
For Beginners: This method contains the core implementation of the training process. It:
- Calculates the mean of the time series to use as a baseline
- Estimates the MA coefficients using a robust maximum likelihood estimation
- Calculates the variance of the white noise process
- Initializes the recent errors vector for making future predictions
Training an MA model is complex because we can't directly observe the past errors. The method uses sophisticated statistical techniques to estimate the most likely values for the MA coefficients given the observed data.