Tutorial 4: Forecasting with uncertainty¶
In Tutorial 3 we fit a model for the moose counts over the whole survey period. In this tutorial, we fit the same model and then generate forecasts of future moose populations.
In doing so, we'll meet some new ProbPipe operations: expectation and sample. We'll also dig deeper into
some concepts introduced in the preceding tutorials: merging distributions and automatic uncertainty propagation.
# @title Setup: install ProbPipe on Colab (run this first)
# On Google Colab, install ProbPipe and download the data; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
import os
import urllib.request
# Colab's preinstalled PyMC 5 does not work with ArviZ 1.x, so the install upgrades PyMC.
%pip install --quiet 'probpipe-core[pymc] @ git+https://github.com/TARPS-group/prob-pipe.git@main'
os.makedirs('data', exist_ok=True)
urllib.request.urlretrieve(
'https://raw.githubusercontent.com/TARPS-group/prob-pipe/main/'
'docs/tutorials/data/moose.csv',
'data/moose.csv',
)
import warnings
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from probpipe import (
Beta,
HalfNormal,
KDEDistribution,
LogNormal,
Normal,
NumericArrayBatch,
Poisson,
RecordSpec,
condition_on,
conditional_distribution,
expectation,
function,
sample,
quantile,
workflow_run,
)
# TensorFlow Probability warns that JAX runs in 32-bit precision, which these models use.
warnings.filterwarnings('ignore', message=r'Explicitly requested dtype float64')
# Cleaner printing for floats
np.set_printoptions(precision=3, suppress=True)
# set random seed for reproducibility
workflow_run.set_default(seed=532431)
Plotting helper functions¶
This cell defines helper functions used for plotting below. Run it, and expand the cell if you want to see how the plots are made.
# @title Plotting helper functions
def plot_forecast(low, median, high, trajectories, observed_counts, title=None):
def all_counts(x):
return np.concatenate([x['y'].raw, x['y_future'].raw], axis=-1)
low, median, high, paths = (all_counts(x) for x in (low, median, high, trajectories))
all_years = np.concatenate([years, future_years])
last_observed_year = years[-1]
past = all_years <= last_observed_year
future = all_years >= last_observed_year # shares the last observed year, so the curves join
fig, ax = plt.subplots(figsize=(8, 3.5), layout='constrained')
ax.axvspan(last_observed_year, all_years[-1] + 0.5, color='0.92', zorder=0)
ax.axvline(last_observed_year, color='0.4', linestyle='--', linewidth=1)
ax.text(last_observed_year + 0.3, 0.03, 'forecast', transform=ax.get_xaxis_transform(), color='0.3')
for window, color, name in [(past, 'tab:green', 'predictive'), (future, 'tab:orange', 'forecast')]:
ax.fill_between(all_years[window], low[window], high[window], color=color, alpha=0.3, label=f'{name} interval')
ax.plot(all_years[window], median[window], color=color, label=f'{name} median')
lines = ax.plot(all_years, paths.T, color='0.35', linewidth=0.7, alpha=0.6)
lines[0].set_label('sampled trajectories')
ax.plot(years, observed_counts, 'o', color='black', markersize=4, label='observed counts')
ax.set(xlabel='year', ylabel='moose counted', title=title, xlim=(years[0] - 0.5, all_years[-1] + 0.5))
ax.legend(loc='upper left', fontsize='small')
plt.show()
def plot_probability_below(y_future_draws, year, threshold, probability):
counts = y_future_draws.raw[:, future_years.tolist().index(year)]
# bins of 10 moose, with one edge at the threshold, so the shaded bars hold exactly the counts below it
width = 10
first = np.floor((counts.min() - threshold) / width)
last = np.ceil((counts.max() - threshold) / width)
edges = threshold + width * np.arange(first, last + 1)
heights, edges = np.histogram(counts, bins=edges, density=True)
below = edges[:-1] < threshold
fig, ax = plt.subplots(figsize=(7, 3), layout='constrained')
ax.bar(edges[:-1][below], heights[below], width=width, align='edge', color='tab:orange',
label=f'P(count < {threshold:g}) = {float(probability):.3f}')
ax.bar(edges[:-1][~below], heights[~below], width=width, align='edge', color='tab:orange', alpha=0.3)
ax.axvline(threshold, color='tab:red', linestyle='--', linewidth=1)
ax.set(xlabel=f'moose counted in {year}', ylabel='probability density',
title=f'Forecast distribution of the {year} count')
ax.legend(loc='upper right')
plt.show()
1. The model from tutorial 3¶
We start by re-implementing the model of tutorial 3, picking up where we left off. Nothing new here.
# data
data = pd.read_csv('data/moose.csv')
years = data['year'].to_numpy()
observed_counts = jnp.asarray(data['count'], dtype=jnp.float32)
n_years = observed_counts.shape[0]
# population model
def ricker(r: jax.Array, K: jax.Array, n0: float, e: jax.Array) -> jax.Array:
"""The population in each year after the year of *n0*, given each year's shock to the growth."""
def step(N: jax.Array, shock: jax.Array) -> tuple[jax.Array, jax.Array]:
N_next = N * jnp.exp(r * (1.0 - N / K) + shock)
return N_next, N_next
_, N = jax.lax.scan(step, jnp.asarray(n0, dtype=jnp.float32), e)
return N
# prior on parameters
prior = LogNormal('K', jnp.log(350.0), 0.4) & LogNormal('r', jnp.log(0.4), 0.4) & Beta('phi', 2.0, 2.0) & HalfNormal('sigma', 0.2)
# prior on random shocks, conditional on sigma
@conditional_distribution(given_spec=prior.event_spec['sigma'], label='shock_prior')
def shocks_given_sigma(sigma: jax.Array) -> Normal:
return Normal('e', jnp.zeros(n_years), sigma)
# likelihood
shock_spec = shocks_given_sigma.event_spec
likelihood_given_spec = prior.event_spec.without('sigma') & shock_spec
@conditional_distribution(given_spec=likelihood_given_spec)
def likelihood(K: jax.Array, r: jax.Array, phi: jax.Array,
e: jax.Array, n0: float = 50.0) -> Poisson:
return Poisson('y', phi * ricker(r, K, n0, e))
# full model
prior = (shocks_given_sigma & prior).with_label('prior')
model = (likelihood & prior).with_label('model')
print(model)
model(y, e, K, r, phi, sigma)
# fit model
posterior = condition_on(model, {'y': observed_counts})
print(posterior)
model(e, K, r, phi, sigma; y)
2. Forecasting the future¶
We now forecast future moose survey populations (what we expect surveyers to see, not the true latent population). We'll assume the distribution of the shocks remains the same over this period. Let $\widetilde{e} = (\widetilde{e}_t)$ and $\widetilde{y} = (\widetilde{y}_t)$ denote the shocks and observations, respectively, over the forecast window.
Intuitively, one forecast can be generated as follows:
- Sample $(e, K, r, \phi, \sigma)$ from the posterior distribution.
- Simulate future shocks $p(\widetilde{e} \mid \sigma)$, given the value of $\sigma$ from step 1.
- Simulate future observations $p(\widetilde{y} \mid \widetilde{e}, K, r, \phi)$, given the sampled values from the previous two steps.
Formally, this corresponds to sampling from the forecast distribution: $$ p_{\mathrm{forecast}}(\widetilde{y}, \widetilde{e}, e, K, r, \sigma, \phi) = p(\widetilde{y} \mid \widetilde{e}, K, r, \phi) \cdot p(\widetilde{e} \mid \sigma) \cdot p_{\mathrm{post}}(e, K, r, \phi, \sigma). $$
ProbPipe Implementation¶
We implement this forecast distribution in ProbPipe below. We actually go one step further and extend the distribution to be over $y$ in addition $\widetilde{y}$: $$ p_{\mathrm{forecast}}(\widetilde{y}, y, \widetilde{e}, e, K, r, \sigma, \phi) = p(\widetilde{y} \mid \widetilde{e}, K, r, \phi) \cdot p(y \mid e, K, r, \phi) \cdot p(\widetilde{e} \mid \sigma) \cdot p_{\mathrm{post}}(e, K, r, \phi, \sigma). $$
The $\widetilde{y}$ marginal of this distribution is still the forecast as before, and now the $y$ marginal is the posterior predictive over the moose counts in the survey window. Thus, one sample from this distribution gives us both posterior predictions and forecasts.
# set up forecast window
last_observed_year = years[-1]
n_forecast_years = 5
first_forecast_year = last_observed_year + 1
future_years = jnp.arange(first_forecast_year, first_forecast_year + n_forecast_years)
print('forecast years:', future_years)
forecast years: [1989 1990 1991 1992 1993]
# shocks over the forecast years, from the same distribution as the observed years' shocks
@conditional_distribution(given_spec=prior.event_spec['sigma'], label='future_shock_prior')
def future_shocks_given_sigma(sigma: jax.Array) -> Normal:
return Normal('e_future', jnp.zeros(n_forecast_years), sigma)
# counts over the forecast years, given the past and future shocks
future_likelihood_given_spec = prior.event_spec.without('sigma') & future_shocks_given_sigma.event_spec
@conditional_distribution(given_spec=future_likelihood_given_spec, label='future_likelihood')
def future_likelihood(K: jax.Array, r: jax.Array, phi: jax.Array,
e: jax.Array, e_future: jax.Array, n0: float = 50.0) -> Poisson:
N = ricker(r, K, n0, jnp.concatenate([e, e_future]))
return Poisson('y_future', phi * N[n_years:])
# full forecast model
forecast_model = future_likelihood & likelihood & future_shocks_given_sigma & posterior
forecast_model = forecast_model.with_label('forecast_model')
print(forecast_model)
forecast_model(y_future, y, e_future, e, K, r, phi, sigma)
Let's summarize the $y$ and $\widetilde{y}$ parts of this distribution. We've used the
quantile operation in previous tutorials. We now also introduce the sample operation.
levels = jnp.array([0.05, 0.5, 0.95])
# quantiles of predictive/forecast distribution
low, med, high = quantile(forecast_model['y_future', 'y'], levels)
# samples of predictive/forecast distribution
trajectories = sample(forecast_model['y_future', 'y'], 10)
plot_forecast(low, med, high, trajectories, observed_counts,
title='Posterior predictions and forecast of the moose counts')
3. Forecasting a probability¶
Suppose a land manager wants to know the probability that the survey will record fewer than 300 moose in 1993. This probability can be written as the expectation of a step function at that threshold $$ \mathbb{P}(y_{1993} < 300) = \mathbb{E}[1_{<300}(y_{1993})], $$ where $1_{<300}(y_{1993})$ equals 1 when $y_{1993} < 300$ and 0 otherwise. Computing the expectation with respect to the posterior predictive distribution gives our forecast of this probability.
An expectation can be computed in ProbPipe using the expectation operation. This operation is defined so that:
$$
\mathrm{expectation}(\mathbb{P}, f) = \mathbb{E}_{x \sim \mathbb{P}}[f(x)].
$$
That is, the first argument is a distribution over the function input $x$, and the second argument is the function to take the expectation of.
def count_below_300(y_future: jax.Array) -> jax.Array:
"""1 if the population of the last year, 1993, is below 300, and 0 otherwise."""
return y_future[-1] < 300.0
prob_below_300 = expectation(forecast_model['y_future'], count_below_300)
print('probability that the 1993 count is below 300:', round(float(prob_below_300), 3))
probability that the 1993 count is below 300: 0.801
We can visualize this probability by plotting the 1993 forecast distribution.
# draws of the forecast counts, to show the forecast distribution of the 1993 count
y_future_draws = sample(forecast_model['y_future'], 4000)
plot_probability_below(y_future_draws, 1993, 300, prob_below_300)
4. Provenance¶
To conclude, let's review the steps used to compute the forecast probability.
print(prob_below_300.provenance)
1. shock_prior & (LogNormal & LogNormal & Beta & HalfNormal) 2. prior = with_label(1) 3. likelihood & 2 4. model = with_label(3) 5. model = condition_on(4, given) route inference_methods, method blackjax_nuts, approximate 6. future_likelihood & likelihood & future_shock_prior & 5 7. forecast_model = with_label(6) 8. expectation(7['y_future'], f, fixed_args, given) route pushforward_mean, method sampling_lift, approximate
Summary¶
In this tutorial, we built up a more complicated probabilistic model that yielded a single object that encoded both the posterior predictive distribution and the forecast distribution. We also introduced two new operations:
sample: draws samples from a distributionexpectation: estimates the expectation of a given function with respect to a distribution
Human-validated by Andrew Roberts on 2026-10-27.