SysIdentPy Documentation

repository·main·Indexed 19 days ago

https://github.com/wilsonrljr/sysidentpy

An open-source Python package for System Identification and Time Series Forecasting using NARMAX models and their variants (NARX, NAR, NARMA, NFIR, ARMAX, ARX, ARMA). It provides a framework for model structure selection (FROLS, MetaMSS, etc.), parameter estimation, and model simulation. The library supports various basis functions, integrates with PyTorch for neural NARX architectures, and is compatible with scikit-learn and CatBoost estimators.

Tokens
96.9K
Snippets
265
Records
335
Agent score
67%

What's inside sysidentpy

  1. Overview of metrics in sysidentpy.metrics

    main

    The sysidentpy.metrics module provides 13 public functions for evaluating regression and forecasting errors by comparing observed values (y) with predicted values (yhat).

    Metrics are categorized by their mathematical properties:

    • Signed error: forecast_error, mean_forecast_error. Useful for detecting bias/direction.
    • Squared error: mean_squared_error, root_mean_squared_error. Penalizes large errors heavily.
    • Normalized squared error: normalized_root_mean_squared_error, root_relative_squared_error. Dimensionless; used for scale comparison.
    • Absolute error: mean_absolute_error, median_absolute_error. Direct interpretation; less sensitive to outliers.
    • Scaled absolute error: mean_absolute_scaled_error. Compares MAE against a naive forecast from training data.
    • Logarithmic/Percentage error: mean_squared_log_error, symmetric_mean_absolute_percentage_error. Assesses relative differences.
    • Goodness of fit: explained_variance_score, r2_score. Compares error to output variability.
    import numpy as np
    from sysidentpy.metrics import (
        explained_variance_score,
        forecast_error,
        mean_absolute_error,
        mean_absolute_scaled_error,
        mean_forecast_error,
        mean_squared_error,
        mean_squared_log_error,
        median_absolute_error,
        normalized_root_mean_squared_error,
        r2_score,
        root_mean_squared_error,
        root_relative_squared_error,
        symmetric_mean_absolute_percentage_error,
    )
    
    y = np.array([3.0, -0.5, 2.0, 7.0])
    yhat = np.array([2.5, 0.0, 2.0, 8.0])
    y_train = np.array([1.0, 2.0, 3.0, 4.0])
    
    # Example usage of various metrics
    errors = forecast_error(y, yhat)
    bias = mean_forecast_error(y, yhat)
    mse = mean_squared_error(y, yhat)
    rmse = root_mean_squared_error(y, yhat)
    nrmse = normalized_root_mean_squared_error(y, yhat)
    rrse = root_relative_squared_error(y, yhat)
    mae = mean_absolute_error(y, yhat)
    median_ae = median_absolute_error(y, yhat)
    mase = mean_absolute_scaled_error(y, yhat, y_train)
    msle = mean_squared_log_error(y, yhat)
    smape = symmetric_mean_absolute_percentage_error(y, yhat)
    evs = explained_variance_score(y, yhat)
    r2 = r2_score(y, yhat)
  2. Overview of SysIdentPy features

    main

    SysIdentPy is a framework for building Dynamical Nonlinear Models for time series and dynamic systems using NARMAX (Nonlinear AutoRegressive Moving Average with eXogenous inputs) models and their variants (NARX, NAR, NARMA, NFIR, ARMAX, ARX, ARMA, etc.).

    Key Capabilities:

    • Model Structure Selection: Methods like FROLS, MetaMSS, AOLS, UOFR, Entropic Regression, RMSS, and Orthogonal Floating Search (OSF, OIF, OOS/O2S).
    • Basis Functions: Support for up to 8 different basis functions (linear and nonlinear) that can be ensembled.
    • Parameter Estimation: Over 15 methods for parameter estimation, including multiobjective estimation using affine information.
    • Model Simulation: Use the SimulateNARMAX class to reproduce results from literature or test published models.
    • Neural NARX: Integration with PyTorch to create custom neural NARX architectures using PyTorch optimizers and loss functions.
    • General Estimators: Compatibility with interfaces from scikit-learn, Catboost, and other compatible tools.
  3. What is an NFIR model?

    main

    An NFIR (Nonlinear Finite Impulse Response) model is a type of model with no output feedback. Unlike NARMAX models, NFIR models do not use output regressors ($y(k-n_y)$); they rely solely on input regressors ($x(k-n_x)$) and noise/uncertainty terms ($e$).

    The mathematical form is:

    $$y_k= F^\ell[x_{k-d}, x_{k-d-1}, \dotsc, x_{k-d-n_x}, e_{k-1}, \dotsc, e_{k-n_e}] + e_k$$

    Key Characteristics:

    • Complexity: NFIR models generally require a significantly higher number of regressors (higher order) compared to NARMAX models to achieve comparable accuracy.
    • Stability: It is generally more challenging to establish stability with NARMAX models than with NFIR models, which can be an advantage in control-oriented contexts.
    • Parsimony: If you require a compact and parsimonious model, NARMAX is typically preferred over NFIR.
  4. What is a NARMAX model?

    main

    NARMAX stands for Non-linear Autoregressive Models with Moving Average and Exogenous Input. It is a class of mathematical models used to represent complex nonlinear systems by relating the current output to past inputs, past outputs, and noise/uncertainty terms.

    A NARMAX model is defined by the equation:

    $$y_k= F^\ell[y_{k-1}, \dots, y_{k-n_y},x_{k-d}, x_{k-d-1}, \dots, x_{k-d-n_x}, e_{k-1}, \dots, e_{k-n_e}] + e_k$$

    Key components:

    • $y_k$: System output at discrete time $k$.
    • $x_k$: System input.
    • $e_k$: Uncertainties or noise.
    • $n_y, n_x, n_e$: Maximum lags for output, input, and noise respectively.
    • $\ell$: Nonlinearity degree.
    • $d$: Time delay (typically $d=1$).

    Common Variants:

    • NARX: NARMAX without noise terms ($e_{k-n_e}$).
    • NARMA: NARMAX where $\ell > 1$ and there are no input terms.
    • NAR: NARMAX with no input or noise terms.
    • ARMAX/ARX: Linear versions where $\ell = 1$.
  5. What is System Identification and how does SysIdentPy fit in?

    main

    System Identification (SI) is a data-driven framework used to model dynamical systems. SysIdentPy is a library designed to facilitate the modeling of nonlinear dynamic systems, specifically focusing on the NARMAX (Nonlinear AutoRegressive Moving Average model with eXogenous inputs) method.

    SysIdentPy provides tools to interact with almost every step of the NARMAX modeling process, except for control design. The supported steps include:

    1. Model Representation: Defining the mathematical form.
    2. Model Structure Selection (MSS): Determining which terms belong in the final model (the most critical and complex step).
    3. Parameter Estimation: Estimating coefficients for the selected terms.
    4. Model Validation: Ensuring the model is unbiased and accurate.
    5. Model Prediction/Simulation: Predicting future outputs or simulating system behavior.
    6. Analysis: Understanding the dynamical properties of the system.
  6. How Pareto Optimality and Dominance work

    main

    In multiobjective optimization, a solution is Pareto optimal (or a Pareto-model) if no objective function can be improved without making at least one other objective function worse.

    Pareto Dominance definition: Given two vectors $[y^{(1)}, y^{(2)}] \in \mathbb{R}^m$ in the objective space, $y^{(1)}$ dominates $y^{(2)}$ ($y^{(1)} \prec y^{(2)}$) if and only if:

    1. $\forall i \in {1, \ldots, m}: y_i^{(1)} \leq y_i^{(2)}$
    2. $\exists j \in {1, \ldots, m}: y_j^{(1)} < y_j^{(2)}$

    Users can generate a Pareto set using the Weighted Sum Method, which scalarizes multiple objectives into a single objective by applying non-negative weights $w$ that sum to 1.

  7. Configure lags for multiple input models

    main

    When working with models that have multiple inputs (MISO - Multiple Input Single Output), you must specify the lags for each input using a nested list.

    For example, if you have two inputs and want to include lags 1 and 2 for both, you should pass [[1, 2], [1, 2]] to the xlag parameter. This differs from single-input models where a simple list or integer might be used.

  8. Performance and Numerical behavior of Array API

    main

    GPU Acceleration

    GPU acceleration is most effective for:

    • Large regressor matrices (high polynomial degrees or many lags).
    • Long time series.
    • Batch operations (e.g., cross-validation).

    For small problems, the overhead of GPU kernel launches and memory copies may exceed the computational benefits.

    Numerical Equivalence

    Results produced via Array API dispatch are designed to be numerically equivalent to the NumPy path. However, expect small floating-point differences ($10^{-7}$ to $10^{-8}$) due to different operation ordering, fused multiply-add (FMA) behavior, or different SVD/QR implementations across backends.

  9. Compare NRMSE and RRSE for normalization

    main

    SysIdentPy provides two different ways to normalize RMSE. They are not interchangeable:

    1. normalized_root_mean_squared_error (NRMSE): Normalizes RMSE by the observed output range: $\frac{\text{RMSE}}{\max(y) - \min(y)}$. It is dimensionless but sensitive to extreme values that widen the range. If y is constant, it returns 0 for perfect predictions and inf for imperfect ones.

    2. root_relative_squared_error (RRSE): Uses the output mean as a reference. For non-constant output, an RRSE < 1 means the model outperforms a constant prediction ($\hat{y}_k = \bar{y}$). If the output is constant, it behaves like NRMSE (0 for perfect, inf for imperfect).

  10. Understand Multiobjective Parameter Estimation in SysIdentPy

    main

    Multiobjective parameter estimation in SysIdentPy shifts from finding a single optimal parameter set to identifying a Pareto front. This set of solutions provides trade-offs between competing objectives, such as goodness-of-fit, model complexity, and robustness.

    A key implementation is the Affine Information Least Squares (AILS) algorithm, which solves a convex multiobjective optimization problem. It uses affine information pairs (like static function and static gain data) alongside standard dynamic input/output data to find Pareto-set solutions.

  11. Configure Model Types: NARX, NAR, and NFIR

    main

    The model_type argument determines the relationship between inputs and outputs:

    • NARX: Uses both input (x) and output (y) regressors. Requires xlag and ylag.
    • NAR: Uses only output regressors. Set model_type="NAR". You do not need to provide input data to .fit() or .predict(), but you must set forecast_horizon in .predict().
    • NFIR: Uses only input regressors. Set model_type="NFIR". You must provide the output array to .fit() and .predict() to provide initial conditions.
    # NAR Model Example
    model = FROLS(ylag=2, basis_function=Polynomial(degree=1), model_type="NAR")
    model.fit(y=y_train)
    yhat = model.predict(y=y_valid, forecast_horizon=23)
    
    # NFIR Model Example
    model = FROLS(xlag=2, basis_function=Polynomial(degree=1), model_type="NFIR")
    model.fit(X=x_train, y=y_train)