API Reference¶
Welcome to the fusionlab-learn API reference. This section provides detailed
specifications for the public functions, classes, and modules included
in the package.
Transformer Models (fusionlab.nn.transformers)¶
Implementations of pure-transformer and Temporal Fusion Transformer architectures.
A standard Transformer model for multi-horizon time series forecasting. |
|
TemporalFusionTransformer model implementation for multi-horizon forecasting, with optional static, past, and future inputs. |
|
Temporal Fusion Transformer (TFT) required static, dynamic(past) and future inputs. |
|
DummyTFT: Simplified TFT variant using only Static and Dynamic inputs. |
Fusion-Attentive Models (fusionlab.nn.models)¶
Core implementations of the Hybrid-Attentive Fusion and its variants.
Base Attentive Model. |
|
Hybrid Attentive LSTM Network (HAL-Net). |
|
Extreme Temporal Fusion Transformer (XTFT) model for complex time series forecasting. |
|
SuperXTFT: An enhanced version of XTFT with Variable Selection Networks (VSNs) and integrated Gate → Add & Norm → GRN pipeline in attention layers. |
Physic-Informed Models (fusionlab.nn.pinn)¶
Fusion models that integrate physical laws into the training process.
Transient Ground-Water–Driven Subsidence Network |
|
Physics-Informed Hybrid Attentive-based LSTM Network (PIHALNet). |
|
Physics-Informed Hybrid Attentive LSTM Network (PiHALNet). |
|
Physics-Informed Transient Groundwater Flow. |
Core Neural Network Components (fusionlab.nn.components)¶
Reusable building blocks for feature selection, sequence processing, attention, and output generation used within the forecasting models.
Gated Residual Network applying transformations with optional context. |
|
Applies GRN to each variable and learns importance weights. |
|
Injects positional information into an input tensor. |
|
Static Enrichment Layer for combining static and temporal features [1]. |
|
Learned Normalization layer that learns mean and standard deviation parameters for normalizing input features. |
|
Implements the Position-wise Feed-Forward Network (FFN) layer. |
Sequence Processing Components (fusionlab.nn.components)¶
Components primarily focused on processing temporal sequences.
MultiScaleLSTM layer applying multiple LSTMs at different sampling scales and concatenating their outputs [1]. |
|
DynamicTimeWindow layer that slices the last |
|
Aggregate multi-scale LSTM outputs using specified temporal fusion strategy. |
|
Aggregate multi-scale LSTM outputs using a specified strategy. |
|
Aggregates time window output features based on the specified |
|
Creates a causal attention mask of shape [1,1,seq_len,seq_len] where mask[0,0,i,j] = 1.0 if j > i else 0.0. |
Attention Mechanisms (fusionlab.nn.components)¶
Various attention layers used in Fusion Model architectures.
Temporal Attention Layer conditioning query with context. |
|
CrossAttention layer that attends one source sequence to another [1]. |
|
Hierarchical Attention layer that processes short-term and long-term sequences separately using multi-head attention, then combines their outputs [1]. |
|
Memory-Augmented Attention layer that uses a learned memory matrix to enhance temporal representation [1]. |
|
MultiResolutionAttentionFusion layer applying multi-head attention fusion over features [1]. |
|
ExplainableAttention layer that returns attention scores from multi-head attention [1]. |
Embedding & Output Components (fusionlab.nn.components)¶
Layers for input embedding and generating final model outputs.
MultiModalEmbedding layer for embedding multiple input modalities into a common feature space and concatenating them along the last dimension. |
|
MultiDecoder for multi-horizon forecasting [1]. |
|
QuantileDistributionModeling layer projects deterministic outputs into quantile predictions [1]. |
Losses (fusionlab.nn.components & fusionlab.nn.losses)¶
Losses tailored for time series forecasting and anomaly detection.
Loss Components (fusionlab.nn.components)¶
These classes implement composite or parameterized loss behaviors.
Loss Functions** (fusionlab.nn.losses)¶
Pure functions for computing scalar losses on predictions.
Create a combined prediction + anomaly loss function for prediction-based strategy. |
|
Create a total loss that adds quantile loss + anomaly loss. |
|
Create a multi-objective Keras loss function that wraps a |
|
Quantile (Pinball) Loss Function for Quantile Regression. |
|
Multi-Quantile (Pinball) Loss Function for Quantile Regression. |
|
Compute the anomaly loss based on given anomaly scores and a |
Anomaly Detection (fusionlab.nn.anomaly_detection)¶
Components specifically designed for anomaly detection tasks.
LSTM Autoencoder for time series reconstruction-based anomaly |
|
Computes an anomaly score from input features using a Multi-Layer |
|
Calculates an anomaly score based on prediction error between |
Hyperparameter Tuning (fusionlab.nn.forecast_tuner)¶
Utilities for optimizing model hyperparameters using Keras Tuner.
A robust and flexible hyperparameter tuner for hydrogeological PINN models. |
|
A Keras Tuner for hyperparameter optimization of the HALNet model. |
|
Keras‑Tuner wrapper dedicated to Extreme Temporal Fusion Transformer families (XTFT, SuperXTFT). |
|
Hyper‑parameter optimiser for Temporal Fusion Transformer (TFT) architectures – both the stricter TFT and the flexible TemporalFusionTransformer ( |
|
Hyperparameter tuner for the PIHALNet model, which jointly predicts land subsidence and groundwater level (GWL) via a physics-informed neural network (PINN) framework. |
|
Fine-tunes XTFT, SuperXTFT, or TFT (stricter) models. |
|
Fine-tunes TemporalFusionTransformer (flexible via model_name='tft_flex') |
Neural Network Utilities (fusionlab.nn.utils)¶
Utilities specifically for preparing data for or interacting with neural network models.
Create input sequences and corresponding targets for time series forecasting. |
|
Split sequences into static and dynamic inputs for the model. |
|
Reshapes time series data into rolling sequences for models like |
|
Compute the forecast horizon for time series forecasting models. |
|
Prepare future static and dynamic inputs for making predictions. |
|
Compute anomaly scores for given true targets using various methods. |
|
Generate forecast using the XTFT model. |
|
Generate forecasts using a pre-trained XTFT model based on the forecast horizon. |
|
Generate a single-step forecast using the XTFT model. |
|
Generate a multi-step forecast using the XTFT model. |
|
Convert a multi-step forecast DataFrame from wide to long format. |
|
Formats model predictions into a structured pandas DataFrame. |
|
Deprecated alias for |
|
Prepares a list of input tensors for a model's call method. |
|
Formats PIHALNet predictions into a structured pandas DataFrame. |
|
Reshapes and prepares time-series data into sequences for PINN models. |
|
Formats PINN model predictions into a structured pandas DataFrame. |
PINN Parameter Descriptors (fusionlab.params)¶
Classes for specifying how physical coefficients in PINN models should be handled, allowing them to be defined as fixed constants or as learnable parameters to be discovered during training.
Learnable Hydraulic Conductivity (K). |
|
Learnable Specific Storage (Ss). |
|
Learnable Source/Sink term (Q). |
|
Indicates that the PINN’s physical coefficient \(C\) should be learned (trainable). |
|
Non-trainable, constant \(C\). |
|
Disable physics – \(C\) is ignored. |
|
Normalise a physical-parameter descriptor. |
Metrics (fusionlab.metrics)¶
A collection of metrics for evaluating forecast accuracy, calibration, sharpness, and stability, particularly suited for probabilistic and time-series forecasting.
Compute the coverage score of prediction intervals. |
|
Compute the sample-based Continuous Ranked Probability Score (CRPS). |
|
Compute the Mean Interval Width (sharpness) of prediction intervals. |
|
Compute the Prediction Stability Score (PSS). |
|
Compute Quantile Calibration Error (QCE). |
|
Compute Theil's U Statistic. |
|
Compute the Time-Weighted Accuracy (TWA) score. |
|
Compute the Time-Weighted Interval Score (TWIS). |
|
Compute the Time-Weighted Mean Absolute Error (TW-MAE). |
|
Compute the Weighted Interval Score (WIS). |
Visualization (fusionlab.plot)¶
A suite of plotting functions for visualizing time-series forecasts—enabling easy comparison of predictions with actual observations and detailed inspection of results at each forecast step or over specified horizons.
Visual‑metric helpers (fusionlab.plot.evaluation)¶
A curated set of plotting utilities that turn the raw numbers returned
by fusionlab.metrics into clear, publication‑quality figures.
They cover point‑forecast accuracy, interval sharpness & coverage,
ensemble calibration, temporal stability, and more – all tailored to
time‑series / probabilistic‑forecast workflows.
Visualise prediction‑interval coverage in two ways: |
|
Visualise the Continuous Ranked Probability Score (CRPS) for ensemble forecasts. |
|
Compare forecasts to ground‑truth on a temporal or spatial canvas. |
|
Visualise Mean Interval Width (MIW) – a simple sharpness measure equal to the average distance between lower and upper prediction‐ interval bounds. |
|
Plot one or several error metrics as a function of forecast step. |
|
Visualise a chosen error metric per segment on a radar chart. |
|
Visualise the Prediction Stability Score (PSS) — the average absolute change between successive time steps in a forecast trajectory. |
|
Visualise Quantile Calibration Error (QCE). |
|
Visualise Theil’s U statistic. |
|
Visualise time‑weighted error / accuracy metrics (MAE, classification accuracy, or interval‑based scores) as either |
|
Visualise Weighted Interval Score (WIS). |
Quick‑look forecast helpers (fusionlab.plot.forecast)¶
Light‑weight plotting utilities that turn a long‑format forecast DataFrame (as returned by :func:fusionlab.nn.utils.format_predictions_to_dataframe) into clear, side‑by‑side figures for rapid inspection.
Generates and displays spatial forecast visualizations. |
|
Visualizes model forecasts from a structured DataFrame. |
|
Plots forecast data, organizing subplots by forecast step. |
|
Visualize forecast results and actual test data for one or more evaluation periods. |
Data Processing Utilities (fusionlab.utils)¶
A grab-bag of utilities for cleaning, reshaping, and enriching raw time-series or spatial measurements before they enter the modelling pipeline
Preprocessing helpers (fusionlab.utils)¶
A collection of helpers for data manipulation, feature engineering, and preparing data for models.
Perform operations on NaN values within data structures, handling both primary data and optional witness data based on specified parameters. |
|
Convert a long PIHALNet prediction table into a wide format where each temporal slice becomes a dedicated column. |
|
Transforms a long-format forecast DataFrame to a wide format. |
|
Cluster 2D spatial data in |
|
Sample spatial data intelligently to represent the distribution |
|
Augments specified feature columns in a time series DataFrame by adding noise. |
|
Generate dummy PINN data dictionary with specified or default ranges. |
|
Applies temporal interpolation and/or feature augmentation to a spatiotemporal DataFrame. |
|
Masks (replaces) values in columns other than the reference column for rows in which the reference column matches (or is closest to) the specified value(s). |
|
Dynamically load data from a joblib-saved dictionary with flexible key access. |
|
Quick save your job using 'joblib' or persistent Python pickle module. |
Time Series Utilities (fusionlab.utils.ts_utils)¶
General utilities for time series data processing, analysis, and feature engineering.
Validate and preprocess time series data, ensuring the presence of a properly formatted datetime column or index. |
|
Converts a given DataFrame's column or index to datetime format using pandas' |
|
Filter a DataFrame based on the provided evaluation periods. |
|
Perform feature engineering on a time series to create relevant predictors for machine learning models. |
|
Generate lag features for a time series to capture temporal dependencies. |
|
Perform trend analysis on a given time series, combining a stationarity test and a linear trend detection. |
|
Perform transformations on a time series (e.g., removing upward/downward trends or applying differencing) based on automatically detected trends. |
|
Decompose a time series into trend, seasonal, and residual components while keeping the other features intact. |
|
Infer the suitable decomposition method for a given time series, based on certain heuristics or user preferences. |
|
Determine the best decomposition approach for a time series, offering two modes: |
|
Perform correlation analysis on a time series dataset, including autocorrelation (ACF), partial autocorrelation (PACF), and cross-correlation with external features. |
|
Perform stationarity transformations on a time series dataset by applying differencing, variance stabilization, or detrending. |
|
Perform a time-based split on a time series dataset for either a simple train-test partition or cross-validation. |
|
Detect outliers in a time series using either Z-Score or Interquartile Range (IQR). |
|
Perform feature selection or dimensionality reduction on a dataset, using either correlation-based filtering or Principal Component Analysis (PCA). |
Datasets (fusionlab.datasets)¶
Utilities for loading included sample datasets and generating synthetic time series data for testing and demonstration.
Loading Functions (fusionlab.datasets)
Fetch the Zhongshan land subsidence dataset (sampled 2000 points). |
|
Fetch the sampled Nansha land subsidence dataset (2000 points). |
|
Loads, preprocesses, and optionally sequences landslide datasets. |
|
Load and preprocess subsidence‐focused PINN data for Zhongshan or Nansha. |
|
Generate multi-variate time series with static, dynamic, and future features. |
|
Generate synthetic actuals and corresponding quantile predictions. |
|
Generate sequence data with injected anomalies. |
|
Generate synthetic time series with specified trend and seasonality. |
|
Generate multi-series data with multiple related target variables. |
Command-Line Tools (fusionlab.tools)¶
High-level applications for common workflows. For usage details, see the Command-Line Tools guide.
References