Class ProphetModel<T, TInput, TOutput>
- Namespace
- AiDotNet.TimeSeries
- Assembly
- AiDotNet.dll
Represents a Prophet model for time series forecasting.
public class ProphetModel<T, TInput, TOutput> : 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).
TInputTOutput
- Inheritance
-
ProphetModel<T, TInput, TOutput>
- Implements
- Inherited Members
- Extension Methods
Remarks
The Prophet model is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects.
For Beginners: Think of the Prophet model as a smart crystal ball for predicting future values in a series of data points over time. It's like predicting weather, but for any kind of data that changes over time, such as sales, website traffic, or stock prices. The model looks at past patterns, including seasonal changes (like how sales might increase during holidays) and overall trends, to make educated guesses about future values.
Constructors
ProphetModel(ProphetOptions<T, TInput, TOutput>?)
Initializes a new instance of the ProphetModel<T> class.
public ProphetModel(ProphetOptions<T, TInput, TOutput>? options = null)
Parameters
optionsProphetOptions<T, TInput, TOutput>The options for configuring the Prophet model. If null, default options are used.
Remarks
This constructor sets up the Prophet model with the specified options or default options if none are provided. It initializes all the components of the model, including trend, seasonal components, holiday effects, changepoints, and regressors.
For Beginners: This is like setting up your prediction tool. You can customize how it works by providing options, or let it use default settings. The model prepares itself to handle different aspects of your data, such as overall direction (trend), repeating patterns (seasonal components), special events (holidays), sudden changes (changepoints), and other factors that might affect your predictions (regressors).
Properties
IsOptimized
Gets whether parameter optimization succeeded during the most recent training run.
public bool IsOptimized { get; }
Property Value
Remarks
When OptimizeParameters is disabled or optimization fails, this value is false.
SupportsJitCompilation
Gets whether this model supports JIT compilation.
public override bool SupportsJitCompilation { get; }
Property Value
- bool
Returns
truewhen the model has been trained with valid components. ProphetModel can be JIT compiled using precomputed Fourier basis matrices for seasonality and average holiday/changepoint effects.
Remarks
For Beginners: JIT compilation optimizes the Prophet model's calculations by precomputing the Fourier basis for seasonality and averaging holiday effects. This provides faster inference while maintaining good accuracy.
Methods
ApplyParameters(Vector<T>)
Applies the provided parameters to the model.
protected override void ApplyParameters(Vector<T> parameters)
Parameters
parametersVector<T>The vector of parameters to apply.
Remarks
This method applies the provided parameter values to the model, updating its internal state to reflect the new parameters. The implementation is model-specific and should be overridden by derived classes as needed.
For Beginners: This method updates the model's internal parameters with new values. It's the counterpart to GetParameters and should understand the parameter vector in exactly the same way.
For example, if the first 5 elements of the parameters vector represent lag coefficients, this method should apply them as lag coefficients in the model's internal structure.
Exceptions
- ArgumentException
Thrown when the parameters vector is invalid.
ComputeAnomalyScores(Matrix<T>, Vector<T>)
Computes anomaly scores for each point in a time series.
public Vector<T> ComputeAnomalyScores(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>The input matrix containing time indices and any regressors.
yVector<T>The actual time series values.
Returns
- Vector<T>
A vector of anomaly scores (absolute prediction errors) for each point.
Remarks
The anomaly score is the absolute difference between the actual value and the predicted value. The predicted value accounts for trend, seasonality, holidays, and regressor effects, so the score represents how much the actual value deviates from the contextual expectation.
For Beginners: This method tells you exactly how unusual each point is, considering all the patterns Prophet has learned: - A score of 0 means the value matched the prediction perfectly - Higher scores mean the value was more unexpected
Unlike simple anomaly detection that just looks at absolute values, Prophet considers:
- Is this value unusual for this time of year?
- Is this value unusual for this day of the week?
- Is this value unusual given the overall trend?
- Is this value unusual for a holiday/non-holiday?
Exceptions
- InvalidOperationException
Thrown when the model hasn't been trained.
CreateInstance()
Creates a new instance of the Prophet 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 Prophet model.
Remarks
This method creates a fresh copy of the model with the same configuration options but without any trained parameters. It's used for creating new models with similar configurations.
For Beginners: This method makes a fresh copy of the model with the same settings, but without any of the learned information. It's like creating a new recipe book with the same instructions but no completed recipes yet. This is useful when you want to: - Train the same type of model on different data - Create multiple similar models for comparison - Start over with the same configuration but different training
DeserializeCore(BinaryReader)
Deserializes the core components of the Prophet model.
protected override void DeserializeCore(BinaryReader reader)
Parameters
readerBinaryReaderThe BinaryReader to read the serialized data from.
Remarks
This method reads the model's parameters and options from a binary stream. It reconstructs the trend, seasonal components, holiday components, changepoint, regressors, and various model options.
For Beginners: This method loads a previously saved model from a file. It's like restoring a snapshot of the model's state, including all the patterns it had learned. This allows us to use a trained model without having to retrain it every time we want to use it.
DetectAnomalies(Matrix<T>, Vector<T>)
Detects anomalies in a time series by comparing predictions to actual values.
public bool[] DetectAnomalies(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>The input matrix containing time indices and any regressors.
yVector<T>The actual time series values.
Returns
- bool[]
A boolean array where true indicates an anomaly at that position.
Remarks
This method uses the Prophet model to predict each point in the time series based on trend, seasonality, holidays, and regressors, then flags points where the prediction error exceeds the anomaly threshold computed during training.
For Beginners: This method identifies unusual data points by comparing what actually happened to what the model predicted should happen, accounting for trends, seasons, and holidays.
Prophet is particularly good at detecting contextual anomalies - values that are unusual given the current context. For example:
- A high sales value in July that would be normal in December might be flagged
- A normal weekday value occurring on a holiday might be flagged
The result tells you which points are unusual enough to warrant investigation.
Exceptions
- InvalidOperationException
Thrown when the model hasn't been trained or anomaly detection wasn't enabled.
DetectAnomaliesDetailed(Matrix<T>, Vector<T>)
public List<(int Index, T Actual, T Predicted, T Score)> DetectAnomaliesDetailed(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>yVector<T>
Returns
EvaluateModel(Matrix<T>, Vector<T>)
Evaluates the performance of the Prophet model on a test dataset.
public override Dictionary<string, T> EvaluateModel(Matrix<T> xTest, Vector<T> yTest)
Parameters
xTestMatrix<T>The input matrix containing the test features.
yTestVector<T>The vector containing the true target values for the test set.
Returns
- Dictionary<string, T>
A dictionary containing various performance metrics.
Remarks
This method calculates several common regression metrics to assess the model's performance: - Mean Absolute Error (MAE): Measures the average magnitude of errors in the predictions. - Mean Squared Error (MSE): Measures the average squared difference between predictions and actual values. - Root Mean Squared Error (RMSE): The square root of MSE, providing a metric in the same units as the target variable. - R-squared (R2): Represents the proportion of variance in the dependent variable that is predictable from the independent variable(s).
For Beginners: This method helps us understand how well our model is performing. It compares the model's predictions to the actual values we know are correct, and calculates several numbers that tell us how close our predictions are: - MAE: On average, how far off are our predictions? (in the same units as our data) - MSE: Similar to MAE, but punishes big mistakes more (in squared units) - RMSE: Like MSE, but back in the original units of our data - R2: How much of the changes in our data does our model explain? (from 0 to 1, where 1 is perfect)
These numbers help us decide if our model is good enough or if we need to improve it.
ExportComputationGraph(List<ComputationNode<T>>)
Exports the ProphetModel 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 the Prophet prediction formula: prediction = trend + seasonal_fourier + avg_holiday + changepoint_effect + regressor_effect
Seasonality is computed using precomputed Fourier basis matrices, allowing efficient matrix operations. Holiday effects are averaged for JIT approximation.
For Beginners: This converts the Prophet model into an optimized computation graph. The graph represents: 1. Base trend value 2. Fourier series for seasonal patterns (sin/cos combinations) 3. Average holiday effects 4. Changepoint adjustments 5. Regressor contributions
Expected speedup: 2-4x for inference after JIT compilation.
GetAnomalyThreshold()
Gets the current anomaly detection threshold.
public T GetAnomalyThreshold()
Returns
- T
The anomaly threshold computed during training.
Remarks
For Beginners: This tells you the cutoff value used to decide whether a prediction error is large enough to be an anomaly. Values with scores above this threshold are considered anomalies.
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
This method provides detailed information about the model's configuration, learned parameters, and operational statistics. It's useful for model versioning, comparison, and documentation.
For Beginners: This method creates a detailed report card about the model. It includes information about how the model was set up and what it learned during training. This is useful for: - Keeping track of different models you've created - Comparing models to see which one works better - Documenting what your model does for other people to understand - Saving the model's configuration for future reference
Predict(Matrix<T>)
Predicts output values for the given input matrix.
public override Vector<T> Predict(Matrix<T> input)
Parameters
inputMatrix<T>The input matrix to make predictions for.
Returns
- Vector<T>
A vector of predicted values.
Remarks
This method generates predictions for each row in the input matrix by calling PredictSingle for each row.
For Beginners: This method takes a bunch of input data and produces predictions for each piece of that data. It's like running many individual predictions all at once.
PredictSingle(Vector<T>)
Predicts a single value based on the input vector.
public override T PredictSingle(Vector<T> input)
Parameters
inputVector<T>The input vector containing time and other regressor values.
Returns
- T
The predicted value for the given input.
Remarks
This method generates a prediction for a single input vector by combining the effects of trend, seasonality, holidays, changepoints, and regressors as learned during training.
For Beginners: This is the method that makes a prediction for a single point in time. It takes all the patterns the model has learned (trends, seasons, holiday effects, etc.) and combines them to predict what value we should expect at the given time point.
The input vector should contain:
- Time information (typically the first element)
- Any additional regressor values that the model was trained with
PredictWithIntervals(Matrix<T>)
Computes prediction intervals for future forecasts.
public (Vector<T> Predictions, Vector<T> LowerBound, Vector<T> UpperBound) PredictWithIntervals(Matrix<T> x)
Parameters
xMatrix<T>The input matrix for forecasting.
Returns
- (Vector<T> Predictions, Vector<T> LowerBound, Vector<T> UpperBound)
A tuple containing (predictions, lower bounds, upper bounds).
Remarks
Prediction intervals provide uncertainty bounds around the point predictions. Points outside these intervals are likely anomalies. The width of the interval is controlled by the PredictionIntervalWidth option.
For Beginners: Instead of just getting a single predicted value, this method gives you a range where the actual value is likely to fall: - Lower bound: The low end of the expected range - Upper bound: The high end of the expected range
If an actual value falls outside this range, it's probably an anomaly. For example, if the predicted range for sales is $800-$1200 and actual sales were $2000, that's clearly unusual.
SerializeCore(BinaryWriter)
Serializes the core components of the Prophet model.
protected override void SerializeCore(BinaryWriter writer)
Parameters
writerBinaryWriterThe BinaryWriter to write the serialized data to.
Remarks
This method writes the model's parameters and options to a binary stream. It includes the trend, seasonal components, holiday components, changepoint, regressors, and various model options.
For Beginners: This method saves all the important parts of our model to a file. It's like taking a snapshot of the model's current state, including all the patterns it has learned. This allows us to save our trained model and use it later without having to retrain it.
SetAnomalyThreshold(T)
Sets a custom anomaly detection threshold.
public void SetAnomalyThreshold(T threshold)
Parameters
thresholdTThe new threshold value.
Remarks
For Beginners: If the automatic threshold is flagging too many or too few anomalies, you can set your own: - Higher threshold = fewer anomalies detected (only extreme values) - Lower threshold = more anomalies detected (more sensitive)
Tip: Look at the scores from ComputeAnomalyScores to decide on a good threshold for your specific use case.
SetParameters(Vector<T>)
Sets the parameters for this model.
public override void SetParameters(Vector<T> parameters)
Parameters
parametersVector<T>A vector containing the model parameters.
TrainCore(Matrix<T>, Vector<T>)
Core implementation of the training logic for the Prophet model.
protected override void TrainCore(Matrix<T> x, Vector<T> y)
Parameters
xMatrix<T>The input features matrix.
yVector<T>The target vector containing the values to be predicted.
Remarks
This protected method contains the actual implementation of the training process. It's called by the public Train method and handles the core training logic.
For Beginners: This is where the real learning happens for the model. The method carefully validates your data, then initializes the model components (like trend and seasonal patterns), and finally optimizes all the parameters to best fit your data. If anything goes wrong during this process, it provides clear error messages to help you understand and fix the issue.
If OptimizeParameters is enabled, the model will attempt parameter optimization. If optimization fails, training continues using the initial parameter estimates, a warning is emitted via Trace, and IsOptimized remains false.