Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make figure in AR2 example reproducible #1816

Merged
merged 6 commits into from
Jun 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified docs/source/_static/img/examples/ar2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 24 additions & 3 deletions examples/ar2.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
import os
import time

import matplotlib.pyplot as plt

import jax
from jax import random
import jax.numpy as jnp
Expand All @@ -54,13 +56,15 @@ def transition(carry, _):
m_t = const + alpha_1 * y_prev + alpha_2 * y_prev_prev
y_t = numpyro.sample("y", dist.Normal(m_t, sigma))
carry = (y_t, y_prev)
return carry, None
return carry, m_t

timesteps = jnp.arange(y.shape[0] - 2)
init = (y[1], y[0])

with numpyro.handlers.condition(data={"y": y[2:]}):
scan(transition, init, timesteps)
_, mu = scan(transition, init, timesteps)

numpyro.deterministic("mu", mu)


def ar2_for_loop(y):
Expand Down Expand Up @@ -110,7 +114,24 @@ def main(args):
# faster
model = ar2_scan

run_inference(model, args, rng_key, y)
samples = run_inference(model, args, rng_key, y)

# do prediction
mean_prediction = samples["mu"].mean(axis=0)

# make plots
fig, ax = plt.subplots(figsize=(8, 6), constrained_layout=True)

# plot training data
ax.plot(t, y, color="blue", label="True values")
# plot mean prediction
# note that we can't make predictions for the first two points,
# because they don't have lagged values to use for prediction.
ax.plot(t[2:], mean_prediction, color="orange", label="Mean predictions")
ax.set(xlabel="time", ylabel="y", title="AR2 process")
ax.legend()

plt.savefig("ar2.png")


if __name__ == "__main__":
Expand Down
Loading