One-Step Ahead Forecasting with
TensorFlow Structural Time Series

Step 1: Install Required Libraries

Make sure you have the following installed:

pip install tensorflow tensorflow-probability

 

Step 2: Prepare Your Time Series Data

  • Load your time series as a 1D NumPy array or TensorFlow tensor.

  • Example: Daily sales, temperature, etc.

  • Normalize if necessary

# Example shape: (num_timesteps,)

time_series = np.array([100, 105, 98, 110, …])

 

Step 3: Define Your STS Model

Choose the right components based on your data:

Component

Use case

LocalLevel

Simple trend

Seasonal

Regular cycles (e.g., weekly)

Autoregressive

Time-dependence

 

model = tfp.sts.LocalLevel(observed_time_series=time_series)

 

Step 4: Fit the Model to Historical Data

Estimate the parameters using Variational Inference:

surrogate_posterior = tfp.sts.build_factored_surrogate_posterior(model)

tfp.vi.fit_surrogate_posterior(…)

 

Step 5: Forecast the Next Time Step

Use the fitted model to forecast one step ahead:

forecast = tfp.sts.forecast(

    model=model,

    observed_time_series=time_series,

    parameter_samples=posterior_samples,

    num_steps=1

)

 

Step 6: Interpret the Forecast

The forecast gives:

  • Mean prediction for the next time step

  • Confidence interval (e.g., 95%)

  • Full predictive distribution

You can extract:

forecast_mean = forecast.mean().numpy()

forecast_std = forecast.stddev().numpy()