Table of Contents

Class ARModel<T>

Namespace
AiDotNet.TimeSeries
Assembly
AiDotNet.dll

Implements an AR (AutoRegressive) model for time series forecasting.

public class ARModel<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

T

The numeric type used for calculations (e.g., float, double, decimal).

Inheritance
ARModel<T>
Implements
IFullModel<T, Matrix<T>, Vector<T>>
IModel<Matrix<T>, Vector<T>, ModelMetadata<T>>
IParameterizable<T, Matrix<T>, Vector<T>>
ICloneable<IFullModel<T, Matrix<T>, Vector<T>>>
IGradientComputable<T, Matrix<T>, Vector<T>>
Inherited Members
Extension Methods

Remarks

The AR model is a time series forecasting method that uses the relationship between an observation and a number of lagged observations to predict future values.

For Beginners: The AR (AutoRegressive) model is one of the simplest and most intuitive time series forecasting methods. It's similar to how we naturally predict things in everyday life.

Think of it this way: If you want to guess tomorrow's temperature, you might look at today's temperature. If it's hot today, it's likely to be hot tomorrow. That's essentially what an AR model does - it uses past values to predict future values.

For example, if you want to predict today's stock price, an AR model might look at the prices from the last few days. If the stock has been trending upward, the model will likely predict that it continues to rise.

The key parameter is the "AR order" (p), which determines how many past values to consider. For example:

  • AR(1): Only looks at the previous value (yesterday to predict today)
  • AR(2): Looks at the previous two values (yesterday and the day before to predict today)
  • AR(7): Looks at values from the past week to make predictions

Unlike more complex models like ARMA or ARIMA, the AR model only contains the autoregressive component and doesn't account for moving average errors or trends that require differencing.

Constructors

ARModel(ARModelOptions<T>)

Creates a new AR model with the specified options.

public ARModel(ARModelOptions<T> options)

Parameters

options ARModelOptions<T>

Options for the AR model, including AR order and training parameters.

Remarks

For Beginners: This constructor creates a new AR 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)
  • 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 AR 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, 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 AR 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 AR model.

Remarks

This method creates a new, uninitialized instance of the AR 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

reader BinaryReader

The 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:

  1. Load a previously trained model
  2. Use it immediately without retraining
  3. Apply the exact same model to new data

The method loads:

  • The AR order (how many coefficients)
  • The AR coefficients (how past values 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

xTest Matrix<T>

Feature matrix for testing.

yTest Vector<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

history Vector<T>

The historical time series data.

horizon int

The 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:

  1. Uses the model to predict the next value after the history
  2. Adds that prediction to the extended history
  3. Uses the extended history to predict the next value
  4. 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 (AR 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 AR model.

public override Vector<T> Predict(Matrix<T> input)

Parameters

input Matrix<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 AR 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 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, and the actual values used will be from the training data or previous predictions.

PredictSingle(Vector<T>)

Predicts a single value based on a single input vector.

public override T PredictSingle(Vector<T> input)

Parameters

input Vector<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 AR 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:

  1. Takes your single input vector
  2. Creates a small table with just one row
  3. Gets a prediction using the main prediction engine
  4. Returns that single prediction to you

Reset()

Resets the model to its untrained state.

public override void Reset()

Remarks

This method clears the trained coefficients, effectively resetting the model to its initial state.

For Beginners: This method erases all the learned patterns from your model.

After calling this method:

  • All coefficients are cleared
  • The model behaves as if it was never trained
  • You would need to train it again before making predictions

This is useful when you want to:

  • Experiment with different training data on the same model
  • Retrain a model from scratch with new parameters
  • Reset a model that might have been trained incorrectly

Think of it like erasing a whiteboard so you can start fresh with new calculations.

SerializeCore(BinaryWriter)

Serializes the model's state to a binary stream.

protected override void SerializeCore(BinaryWriter writer)

Parameters

writer BinaryWriter

The 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:

  1. Save a trained model to disk
  2. Load it later without having to retrain
  3. Share the model with others

The method saves the essential components of the model:

  • The AR order (how many coefficients)
  • The AR coefficients (how past values affect predictions)

This allows the model to be fully reconstructed later.

ToString()

Returns a string representation of the AR 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 AR model, including its order and coefficients.

For Beginners: This method gives you a text description of your model.

The returned string includes:

  • The type of model (AR)
  • The AR order (how many past values 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 AR model.

protected override void TrainCore(Matrix<T> x, Vector<T> y)

Parameters

x Matrix<T>

Feature matrix (typically just time indices for AR models).

y Vector<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:

  1. Initializes the model coefficients for each past time period
  2. Calculates prediction errors with the current model
  3. Determines how to adjust coefficients to improve predictions
  4. Updates the coefficients accordingly
  5. 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.