fusionlab.nn.utils.generate_forecast_with

fusionlab.nn.utils.generate_forecast_with(xtft_model, inputs, forecast_horizon, y=None, dt_col=None, mode='quantile', spatial_cols=None, q=None, tname=None, forecast_dt=None, apply_mask=False, mask_values=None, mask_fill_value=None, savefile=None, verbose=3, **kw)[source]

Generate forecasts using a pre-trained XTFT model based on the forecast horizon.

There are two approaches to generating forecasts with an XTFT model:

  1. A monolithic function (e.g. generate_forecast) that handles both single-step and multi-step forecasts within a single implementation. This approach results in a single, large function that internally branches its logic based on the value of the forecast horizon.

  2. A modular design where the single-step and multi-step forecasting functionalities are separated into two distinct functions (e.g. forecast_single_step and forecast_multi_step), with a thin wrapper (e.g. generate_xtft_forecast) that dispatches to the appropriate function based on the forecast horizon.

The modular approach (2) is generally preferred because it separates concerns and improves code readability, maintainability, and unit testing. Each function becomes responsible for a well-defined task: one for single-step forecasts and one for multi-step forecasts. The wrapper function, which we propose to name generate_xtft_forecast, simply selects the correct method based on the forecast horizon. Use this approach when your application may need to handle both short- and long- term forecasts, as it keeps the codebase modular and easier to debug.

Below is an implementation of the wrapper function generate_xtft_forecast that calls forecast_single_step when forecast_horizon equals 1 and forecast_multi_step when forecast_horizon is greater than 1.

Parameters:
  • xtft_model (object) – A validated Keras model instance. The model is expected to be verified via validate_keras_model.

  • inputs (list or tuple of numpy.ndarray) – A list containing three elements: X_static, X_dynamic, and X_future. If spatial_cols is provided, it is assumed that the first two columns of X_static correspond to the first and second spatial coordinates of the original training data.

  • forecast_horizon (int) – The number of future time steps to forecast. A value of 1 triggers a single-step forecast; values greater than 1 trigger a multi-step forecast.

  • y (numpy.ndarray, optional) – Actual target values for evaluation. If provided, evaluation metrics (e.g., R² Score, and in quantile mode, the coverage score) are computed.

  • dt_col (str, optional) – Name of the time column (e.g. "year"). If provided, the output DataFrame includes a column with these values.

  • mode (str, optional) – Forecast mode, either "quantile" or "point". In quantile mode, predictions are generated for multiple quantiles (default: [0.1, 0.5, 0.9]); in point mode, a single prediction is generated.

  • spatial_cols (list of str, optional) – List of spatial column names. If provided, it must contain at least two elements corresponding to the first and second columns of the original training data’s X_static.

  • time_steps (int, optional) – The number of historical time steps used as input.

  • q (list of float, optional) – List of quantile values for quantile forecasting. Default is [0.1, 0.5, 0.9] when mode is "quantile".

  • tname (str, optional) – Target variable name used to construct output column names (e.g., "subsidence"). Default is "target".

  • forecast_dt (any, optional) – Forecast datetime information. If provided and its length matches forecast_horizon, its values are added to the output DataFrame.

  • apply_mask (bool, optional) – If True, applies masking (via mask_by_reference) to adjust predictions in non-subsiding areas. Requires that both mask_values and mask_fill_value are provided.

  • mask_values (scalar, optional) – The reference value(s) used for masking. Must be provided if apply_mask is True.

  • mask_fill_value (scalar, optional) – The value used to fill masked predictions. Must be provided if apply_mask is True.

  • savefile (str, optional) – File path to save the forecast results as a CSV file. If not provided, a default filename is generated.

  • verbose (int, optional) – Verbosity level controlling printed output.

  • **kw (dict, optional) – Does nothing; here for future extension.

Returns:

A DataFrame containing the forecast results. In quantile mode, the output includes columns for each quantile and forecast step (e.g. <tname>_q10_step1, <tname>_q50_step2, etc.); in point mode, it contains a single prediction column per forecast step (e.g. <tname>_pred_step1). If y is provided, an additional column (<tname>_actual) is included.

Return type:

pandas.DataFrame

Examples

>>> from fusionlab.nn.transformers import XTFT
>>> from fusionlab.nn.utils import generate_forecast_with
>>> import numpy as np
>>>
>>> # Prepare a dummy XTFT model with example parameters.
>>> my_model = XTFT(
...     static_input_dim=10,
...     dynamic_input_dim=5,
...     future_input_dim=3,
...     forecast_horizon=1,          # This parameter will be updated in the
...                                  # wrapper function based on forecast_horizon.
...     quantiles=[0.1, 0.5, 0.9],
...     embed_dim=32,
...     max_window_size=3,
...     memory_size=100,
...     num_heads=4,
...     dropout_rate=0.1,
...     lstm_units=64,
...     attention_units=64,
...     hidden_units=32
... )
>>> my_model.compile(optimizer='adam')
>>>
>>> # Create dummy input data.
>>> X_static = np.random.rand(100, 10)
>>> X_dynamic = np.random.rand(100, 3, 5)
>>> X_future  = np.random.rand(100, 3, 3)
>>> y_array   = np.random.rand(100, 1, 1)  # For single-step target output.
>>> inputs    = [X_static, X_dynamic, X_future]
>>>
>>> # Fit the model with dummy data.
>>> my_model.fit(
...     x=[X_static, X_dynamic, X_future],
...     y=y_array,
...     epochs=1,
...     batch_size=32
... )
>>>
>>> # Example for a single-step forecast:
>>> forecast_df = generate_forecast_with(
...     xtft_model=my_model,
...     inputs=inputs,
...     forecast_horizon=1,
...     y=y_array,
...     dt_col="year",
...     mode="quantile",
...     spatial_cols=["longitude", "latitude"],
...     tname="subsidence",
...     verbose=3
... )
>>> print(forecast_df.head())
>>>
>>> # Example for a multi-step forecast:
>>> forecast_dates = ["2023", "2024", "2025", "2026"]
>>> forecast_df = generate_forecast_with(
...     xtft_model=my_model,
...     inputs=inputs,
...     forecast_horizon=4,
...     y=y_array,
...     dt_col="year",
...     mode="point",
...     spatial_cols=["longitude", "latitude"],
...     tname="subsidence",
...     forecast_dt=forecast_dates,
...     verbose=3
... )
>>> print(forecast_df.head())

See also

forecast_single_step

Generates a single-step forecast.

forecast_multi_step

Generates a multi-step forecast.

validate_keras_model

Validates a Keras model.

coverage_score

Computes the coverage score.

References