Table of Contents

Class InterventionAnalysisModel<T>

Namespace
AiDotNet.TimeSeries
Assembly
AiDotNet.dll

Represents a model that analyzes and forecasts time series data with interventions or structural changes.

public class InterventionAnalysisModel<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, typically float or double.

Inheritance
InterventionAnalysisModel<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

Intervention analysis combines ARIMA (AutoRegressive Integrated Moving Average) modeling with the ability to account for external events or interventions that cause structural changes in the time series. These interventions can be temporary or permanent and can have various effects on the level, trend, or seasonality of the data.

For Beginners: Intervention analysis helps understand how specific events affect your data patterns.

Think of it like analyzing sales data:

  • You've been tracking monthly sales that follow a regular pattern
  • Then you run a major marketing campaign in July
  • Sales jump significantly and stay higher for several months

This model helps you:

  • Measure exactly how much the marketing campaign boosted sales
  • Understand how long the effect lasted
  • Make better predictions by accounting for these special events

Other examples of interventions include policy changes, natural disasters, product launches, or any significant event that changes the normal pattern of your data.

Constructors

InterventionAnalysisModel(InterventionAnalysisOptions<T, Matrix<T>, Vector<T>>?)

Initializes a new instance of the InterventionAnalysisModel<T> class with the specified options.

public InterventionAnalysisModel(InterventionAnalysisOptions<T, Matrix<T>, Vector<T>>? options = null)

Parameters

options InterventionAnalysisOptions<T, Matrix<T>, Vector<T>>

The configuration options for the intervention analysis model. If null, default options are used.

Remarks

This constructor initializes the intervention analysis model with the provided configuration options or default options if none are specified. The options determine parameters such as the AR and MA orders, the interventions to consider, and the optimizer to use for parameter estimation.

For Beginners: This sets up your model with your chosen settings.

When creating the model, you can specify:

  • How many past values to use in predictions (AR order)
  • How many past errors to consider (MA order)
  • When interventions or special events occurred
  • What method to use to find the best parameters

If you don't provide options, the model uses sensible defaults.

Methods

CreateInstance()

Creates a new instance of the intervention analysis 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 intervention analysis model.

Remarks

This method creates a new instance of the intervention analysis model with the same configuration options as the current instance. This is useful for creating copies or clones of the model for purposes like cross-validation or ensemble modeling.

For Beginners: This creates a new copy of the model with the same settings.

Creating a new instance:

  • Makes a fresh copy of the model with the same configuration
  • The new copy hasn't been trained yet
  • You can train and use the copy independently from the original

This is helpful when you want to:

  • Train multiple versions of the same model on different data subsets
  • Create an ensemble of models for better predictions
  • Share your model configuration with others
  • Keep your original model while experimenting with variations

DeserializeCore(BinaryReader)

Deserializes the model's core parameters from a binary reader.

protected override void DeserializeCore(BinaryReader reader)

Parameters

reader BinaryReader

The binary reader to read from.

Remarks

This method reads the model's essential parameters from a binary stream, allowing a previously saved model to be loaded from a file or database. The deserialized parameters include the AR and MA parameters, intervention effects, and model options.

For Beginners: This loads a previously saved model.

The method:

  • Reads the saved model data from a file or database
  • Converts this data back into the model's parameters
  • Reconstructs the model exactly as it was when saved

This is particularly useful when:

  • You want to use a model that took a long time to train
  • You want to ensure consistent results across different runs
  • You need to deploy the model in a production environment

Think of it like opening a document you previously saved, allowing you to continue using the model without having to train it again.

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>

The test input features matrix.

yTest Vector<T>

The test target values vector.

Returns

Dictionary<string, T>

A dictionary containing various evaluation metrics.

Remarks

This method evaluates the model's performance on test data by generating predictions and calculating various error metrics. The returned metrics include Mean Absolute Error (MAE), Mean Squared Error (MSE), Root Mean Squared Error (RMSE), and R-squared (R2).

For Beginners: This measures how accurate the model's predictions are.

The evaluation:

  • Makes predictions for data the model hasn't seen before
  • Compares these predictions to the actual values
  • Calculates different types of error measurements:
    • MAE (Mean Absolute Error): Average of absolute differences
    • MSE (Mean Squared Error): Average of squared differences
    • RMSE (Root Mean Squared Error): Square root of MSE, in the same units as your data
    • R2 (R-squared): How much of the variation in the data is explained by the model (0-1)

Lower values of MAE, MSE, and RMSE indicate better performance. Higher values of R2 (closer to 1) indicate better performance.

GetInterventionEffects()

Gets a dictionary of the estimated intervention effects.

public Dictionary<string, double> GetInterventionEffects()

Returns

Dictionary<string, double>

A dictionary mapping intervention identifiers to their estimated effects.

Remarks

This method returns a dictionary containing the estimated effects of each intervention considered by the model. The keys are identifiers for the interventions, and the values are the estimated magnitudes of their effects.

For Beginners: This shows how much each special event affected your data.

The method:

  • Returns a list of all interventions the model knows about
  • For each intervention, shows:
    • When it started
    • How long it lasted
    • How much it affected the data (its effect size)

This helps you understand:

  • Which interventions had the biggest impact
  • Whether an intervention had a positive or negative effect
  • The relative importance of different interventions

For example, you might learn that a marketing campaign increased sales by 15%, while a website redesign increased sales by only 3%.

GetModelMetadata()

Returns 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

This method returns detailed metadata about the intervention analysis model, including its type, current parameters (AR parameters, MA parameters, intervention effects), and configuration options. This metadata can be used for model selection, comparison, documentation, and serialization purposes.

For Beginners: This provides information about your model's settings and state.

The metadata includes:

  • The type of model (Intervention Analysis)
  • Current parameter values (AR parameters, MA parameters)
  • Details about the interventions and their estimated effects
  • Configuration settings from when you created the model
  • A serialized version of the entire model

This information is useful for:

  • Keeping track of different models you've created
  • Comparing model configurations
  • Documenting which settings worked best
  • Sharing model information with others
  • Understanding the relative importance of different interventions

Predict(Matrix<T>)

Generates predictions for the given input data.

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

Parameters

input Matrix<T>

The input features matrix.

Returns

Vector<T>

A vector containing the predicted values.

Remarks

This method generates forecasts for each time point in the input matrix. It calls PredictSingle for each row in the input matrix, which applies the AR and MA terms and considers intervention effects.

For Beginners: This makes predictions for each time point in your data.

The prediction process:

  • Takes the input features for each time point
  • Makes a separate prediction for each time point
  • Each prediction takes into account:
    • Past values (AR component)
    • Past errors (MA component)
    • Any interventions active at that time point

The result is a forecast that considers both the natural patterns in your data and the effects of special events or interventions.

PredictSingle(Vector<T>)

Predicts a single value based on the input vector.

public override T PredictSingle(Vector<T> input)

Parameters

input Vector<T>

The input vector containing features for the prediction.

Returns

T

The predicted value for the given input.

Remarks

This method implements the single-value prediction capability required by the model interface. It creates a context for the prediction and then calls the internal prediction logic that applies the AR terms, MA terms, and intervention effects.

For Beginners: This generates a prediction for a single point in time.

When you need a forecast for just one specific time point, this method:

  • Takes the input features for that time point
  • Creates a temporary context with appropriate historical information
  • Calls the internal prediction engine to generate a forecast
  • Returns that single prediction

It handles the case where you need just one forecast rather than a whole series of them. For example, predicting tomorrow's sales figure rather than forecasting sales for the next month.

Reset()

Resets the model to its initial state.

public override void Reset()

Remarks

This method resets the intervention analysis model to its initial state, clearing any learned parameters and returning to the initial configuration provided in the options. This allows the model to be retrained from scratch with new data or different hyperparameters.

For Beginners: This resets the model to start fresh.

Resetting the model:

  • Clears all learned parameters (AR parameters, MA parameters)
  • Resets the intervention effects
  • Empties stored residuals and fitted values
  • Returns the model to its original state before training

This is useful when you want to:

  • Train the model on different data
  • Try different settings or approaches
  • Experiment with different interventions
  • Start with a clean slate after experimentation

SerializeCore(BinaryWriter)

Serializes the model's core parameters to a binary writer.

protected override void SerializeCore(BinaryWriter writer)

Parameters

writer BinaryWriter

The binary writer to write to.

Remarks

This method writes the model's essential parameters to a binary stream, allowing the model to be saved to a file or database. The serialized parameters include the AR and MA parameters, intervention effects, and model options.

For Beginners: This saves the model so you can use it later.

The method:

  • Converts the model's parameters to a format that can be saved
  • Writes these values to a file or database
  • Includes all the information needed to recreate the model exactly

This allows you to:

  • Save a trained model for future use
  • Share the model with others
  • Use the model in other applications

It's like saving a document so you can open it again later without having to start from scratch.

TrainCore(Matrix<T>, Vector<T>)

Core implementation of the training logic for the intervention analysis model.

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

Parameters

x Matrix<T>

The input features matrix (typically time indicators or related variables).

y Vector<T>

The target values vector (the time series data to forecast).

Remarks

This method implements the core training mechanism for the intervention analysis model. It delegates to the main training process, which initializes parameters, optimizes them, and computes the model residuals.

For Beginners: This is the engine that powers the model's learning process.

This method:

  • Stores your time series data internally
  • Sets up initial parameter values for the model
  • Uses an optimizer to find the best parameter values
  • Calculates how well the model fits your historical data

Think of it as the actual learning process that happens behind the scenes when you train the model to recognize patterns in your data.