Polynomial Regression

This example has been contributed by Tyler James Burch (@tjburch on GitHub).

Code
%config InlineBackend.figure_format = "retina"
%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}

import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

plt.style.use("bambi.mplstyle")
seed = sum(map(ord, "Polynomial regression"))
rng = np.random.default_rng(seed)

This example will discuss polynomial regression using Bambi. Unlike many other examples shown, there aren’t specific polynomial methods or families implemented in Bambi, most of the interesting behavior for polynomial regression occurs within the formula definition. Regardless, there are some nuances that are useful to be aware of.

This example uses the kinematic equations from classical mechanics as a backdrop. Specifically, an object in motion experiencing constant acceleration can be described by the following:

x_f = \frac{1}{2} a t^2 + v_0 t + x_0

where x_0 and x_f are the initial and final locations, v_0 is the initial velocity, and a is acceleration.

A falling ball

First, we’ll consider a simple falling ball, released from 50 meters. In this situation, v_0 = 0 m/s, x_0 = 50 m and a = g, the acceleration due to gravity, -9.81 m/s^2. So dropping out the v_0 t component, the equation takes the form:

x_f = \frac{1}{2} g t^2 + x_0

We’ll start by simulating data for the first 2 seconds of motion. We will also assume some measurement error with a gaussian distribution of \sigma = 0.3.

g = -9.81  # acceleration due to gravity (m/s^2)
t = np.linspace(0, 2, 100)  # time in seconds
inital_height = 50
x_falling = 0.5 * g * t**2 + inital_height
noise = rng.normal(0, 0.3, x_falling.shape)
x_obs_falling = x_falling + noise
df_falling = pd.DataFrame({"t": t, "x": x_obs_falling})

fig, ax = plt.subplots()
ax.scatter(t, x_obs_falling, label="Observed Displacement", color="C0")
ax.plot(t, x_falling, label="True Function", color="C1")
ax.set(xlabel="Time (s)", ylabel="Displacement (m)")
ax.legend();

Casting the equation x_f = \frac{1}{2} g t^2 + x_0 into a regression context, we let time (t) be the independent variable, and final location (x_f) be the response/dependent variable. This allows our coefficients to be proportional to g and x_0. The intercept, \beta_0 corresponds exactly to x_0. Letting \beta_1 = \frac{1}{2} g then gives g = 2\beta_1 when x_1 = t^2, meaning we’re doing polynomial regression. We can put this into Bambi via the following, optionally including the + 1 to emphasize that we choose to include the coefficient.

model_falling = bmb.Model("x ~ I(t**2) + 1", df_falling)
results_falling = model_falling.fit(inference_method="pymc", random_seed=seed)
model_falling.compute_log_likelihood(results_falling)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, I(t ** 2), Intercept_centered]

Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 5 seconds.

The term I(t**2) indicates to evaluate inside the I. For including just the t^2 term, you can express it in any of the following ways:

  • I(t**2)
  • {t**2}
  • Square the data directly, and pass it as a new column

To verify, we’ll fit the other two versions as well.

model_falling_variation1 = bmb.Model(
    "x ~ {t**2} + 1", df_falling
)  # Using {t**2} syntax
results_variation1 = model_falling_variation1.fit(
    inference_method="pymc", random_seed=seed
)

model_falling_variation2 = bmb.Model(
    "x ~ tsquared + 1",  # Using data with the t variable squared
    df_falling.assign(
        tsquared=t**2
    ),  # Creating the tsquared variable for use in the formula
)
results_variation2 = model_falling_variation2.fit(
    inference_method="pymc", random_seed=seed
)

print(
    "I{t**2} coefficient: ",
    round(results_falling.posterior["I(t ** 2)"].values.mean(), 4),
)
print(
    "{t**2} coefficient: ",
    round(results_variation1.posterior["I(t ** 2)"].values.mean(), 4),
)
print(
    "tsquared coefficient: ",
    round(results_variation2.posterior["tsquared"].values.mean(), 4),
)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, I(t ** 2), Intercept_centered]

Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 3 seconds.
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, tsquared, Intercept_centered]

Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 3 seconds.
I{t**2} coefficient:  -4.8911
{t**2} coefficient:  -4.8911
tsquared coefficient:  -4.8911

Each of these provides identical results, giving -4.9, which is g/2. This makes the acceleration exactly the -9.81 m/s^2 acceleration that generated the data. Looking at our model summary,

az.summary(results_falling)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
sigma 0.2905 0.0211 0.26 0.33 6078 2925 1.00 0.00027 0.0002
I(t ** 2) -4.8911 0.0247 -4.9 -4.9 6031 2985 1.00 0.00032 0.00023
Intercept_centered 43.4192 0.0288 43 43 6181 2946 1.00 0.00037 0.00027
Intercept 49.974 0.0435 50 50 6231 2987 1.00 0.00055 0.00038

We see that both g/2 = -4.9 (so g=-9.81) and the original height of x_0 = 50 m are recovered, along with the injected noise.

We can then use the model to answer some questions, for example, when would the ball land? This would correspond to x_f = 0.

0 = \frac{1}{2} g t^2 - x_0

t = \sqrt{2x_0 / g}

calculated_x0 = results_falling.posterior["Intercept"].values.mean()
calculated_g = -2 * results_falling.posterior["I(t ** 2)"].values.mean()
calculated_land = np.sqrt(2 * calculated_x0 / calculated_g)
print(f"The ball will land at {round(calculated_land, 2)} seconds")
The ball will land at 3.2 seconds

Or if we want to account for our measurement error and use the full posterior,

calculated_x0_posterior = results_falling.posterior["Intercept"].values
calculated_g_posterior = -2 * results_falling.posterior["I(t ** 2)"].values
calculated_land_posterior = np.sqrt(
    2 * calculated_x0_posterior / calculated_g_posterior
)
lower_est = round(np.quantile(calculated_land_posterior, 0.025), 2)
upper_est = round(np.quantile(calculated_land_posterior, 0.975), 2)
print(f"The ball landing will be measured between {lower_est} and {upper_est} seconds")
The ball landing will be measured between 3.18 and 3.21 seconds

Projectile Motion

Next, instead of a ball strictly falling, instead imagine one thrown straight upward. In this case, we add the initial velocity back into the equation.

x_f = \frac{1}{2} g t^2 + v_0 t + x_0

We will envision the ball tossed upward, starting at 1.5 meters above ground level. It will be tossed at 7 m/s upward. It will also stop when hitting the ground.

v0 = 7
x0 = 1.5
x_projectile = (1 / 2) * g * t**2 + v0 * t + x0
noise = rng.normal(0, 0.2, x_projectile.shape)
x_obs_projectile = x_projectile + noise
df_projectile = pd.DataFrame(
    {"t": t, "tsq": t**2, "x": x_obs_projectile, "x_true": x_projectile}
)
df_projectile = df_projectile[df_projectile["x"] >= 0]

fig, ax = plt.subplots()
ax.scatter(df_projectile.t, df_projectile.x, label="Observed Displacement", color="C0")
ax.plot(df_projectile.t, df_projectile.x_true, label="True Function", color="C1")
ax.set(xlabel="Time (s)", ylabel="Displacement (m)", ylim=(0, None))
ax.legend();

Modeling this using Bambi, we must include the linear term on time to capture the inital velocity. We’ll do the following regression,

x_f = \beta_0 + \beta_1 t + \beta_2 t^2

which then maps the solved coefficents to the following: \beta_0 = x_0, \beta_1 = v_0, and \beta_2 = \frac{g}{2}.

model_projectile_all_terms = bmb.Model("x ~ I(t**2) + t + 1", df_projectile)
fit_projectile_all_terms = model_projectile_all_terms.fit(
    inference_method="pymc", target_accept=0.9, random_seed=seed
)
model_projectile_all_terms.compute_log_likelihood(fit_projectile_all_terms)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, I(t ** 2), t, Intercept_centered]

Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 4 seconds.
az.summary(fit_projectile_all_terms)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
sigma 0.1813 0.0142 0.16 0.21 2748 2460 1.00 0.00028 0.00024
I(t ** 2) -4.944 0.105 -5.1 -4.8 1499 1814 1.00 0.0027 0.002
t 7.126 0.174 6.8 7.4 1495 1773 1.00 0.0045 0.0033
Intercept_centered 2.8818 0.02 2.8 2.9 2731 2305 1.00 0.00038 0.00028
Intercept 1.42 0.06 1.3 1.5 2199 2393 1.00 0.0013 0.00092
hdi = az.hdi(fit_projectile_all_terms.posterior, prob=0.95)
print(
    f"Initial height: {hdi['Intercept'].sel(ci_bound='lower'):.2f} to {hdi['Intercept'].sel(ci_bound='upper'):.2f} meters (True: {x0} m)"
)
print(
    f"Initial velocity: {hdi['t'].sel(ci_bound='lower'):.2f} to {hdi['t'].sel(ci_bound='upper'):.2f} meters per second (True: {v0} m/s)"
)
print(
    f"Acceleration: {2*hdi['I(t ** 2)'].sel(ci_bound='lower'):.2f} to {2*hdi['I(t ** 2)'].sel(ci_bound='upper'):.2f} meters per second squared (True: {g} m/s^2)"
)
Initial height: 1.30 to 1.53 meters (True: 1.5 m)
Initial velocity: 6.78 to 7.47 meters per second (True: 7 m/s)
Acceleration: -10.31 to -9.48 meters per second squared (True: -9.81 m/s^2)

We once again are able to recover all our input parameters.

In addition to directly calculating all terms, to include all polynomial terms up to a given degree you can use the poly keyword. We don’t do that in this notebook for two reasons. First, by default it orthogonalizes the terms making it ill-suited to this example since the coefficients have physical meaning. For more information on the orthogonalization, please see the orthogonal polynomial notebook. The orthogonalization process can be disabled by the raw argument of poly, but we still elect not to use it because in later examples we decide to use different effects on the t term vs the t^2 term, and doing so is not easy when using poly. However, just to show that the results match when using the raw = True argument, we’ll fit the same model as above.

model_poly_raw = bmb.Model("x ~ poly(t, 2, raw=True)", df_projectile)
model_poly_raw.set_alias({"poly(t, 2, raw=True)": "t_poly"})
fit_poly_raw = model_poly_raw.fit(inference_method="pymc", random_seed=seed)
model_poly_raw.compute_log_likelihood(fit_poly_raw)
az.summary(fit_poly_raw)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, t_poly, Intercept_centered]

Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 3 seconds.
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
sigma 0.1815 0.0149 0.16 0.21 2545 1796 1.00 0.00029 0.00022
t_poly[0] 7.122 0.175 6.8 7.4 1994 2005 1.00 0.0039 0.0027
t_poly[1] -4.942 0.105 -5.1 -4.8 1997 2038 1.00 0.0023 0.0016
Intercept_centered 2.8822 0.0203 2.8 2.9 2802 2098 1.00 0.00038 0.00028
Intercept 1.421 0.06 1.3 1.5 2291 2232 1.00 0.0013 0.00087

We see the same results, where poly(t, 2, raw=True)[0] corresponds to the coefficient on t (v_0 in our example), and poly(t, 2, raw=True)[1] is the coefficient on t^2 (\frac{g}{2}).

Measuring gravity on a new planet

In the next example, you’ve been recruited to join the space program as a research scientist, looking to directly measure the gravity on a new planet, PlanetX. You don’t know anything about this planet or it’s safety, so you have time for one, and only one, throw of a ball. However, you’ve perfected your throwing mechanics, and can achieve the same initial velocity wherever you are. To baseline, you make a toss on planet Earth, warm up your spacecraft and stop at Mars to make a toss, then travel far away, and make a toss on PlanetX.

First we simulate data for this experiment.

def simulate_throw(v0, g, noise_std, time_step=0.25, max_time=10, seed=seed):
    times = np.arange(0, max_time, time_step)
    heights = v0 * times - 0.5 * g * times**2
    heights_with_noise = heights + rng.normal(0, noise_std, len(times))
    valid_indices = heights_with_noise >= 0
    return (
        times[valid_indices],
        heights_with_noise[valid_indices],
        heights[valid_indices],
    )


# Define the parameters
v0 = 20  # Initial velocity (m/s)
g_planets = {
    "Earth": 9.81,
    "Mars": 3.72,
    "PlanetX": 6.0,
}  # Gravitational acceleration (m/s^2)
noise_std = 1.5  # Standard deviation for noise

# Generate data
records = []
for planet, g in g_planets.items():
    times, heights, heights_true = simulate_throw(v0, g, noise_std)
    for time, height, height_true in zip(times, heights, heights_true):
        records.append([planet, time, height, height_true])

# Convert to a DataFrame
df = pd.DataFrame(records, columns=["Planet", "Time", "Height", "Height_true"])
df["Planet"] = df["Planet"].astype("category")

And drawing those trajectories,

fig, ax = plt.subplots()

for i, planet in enumerate(df["Planet"].cat.categories):
    subset = df[df["Planet"] == planet]
    ax.plot(subset["Time"], subset["Height_true"], alpha=0.7, color=f"C{i}")
    ax.scatter(subset["Time"], subset["Height"], alpha=0.7, label=planet, color=f"C{i}")

ax.set(
    xlabel="Time (seconds)",
    ylabel="Height (meters)",
    title="Trajectory Comparison",
    ylim=(0, None),
)
ax.legend(title="Planet");

We now aim to model this data. We again use the folowing equation (calling displacement h for height):

h = \frac{1}{2} g_{p} t^2 + v_{0} t

where g_p now has a subscript to indicate the planet that we’re throwing from.

In Bambi, we’ll do the following:

Height ~ I(Time**2):Planet + Time + 0

which corresponds one-to-one with the above formula. The intercept is eliminated since we start from x=0.

planet_model = bmb.Model("Height ~ I(Time**2):Planet + Time + 0", df)
planet_model.build()
planet_model.graph()

planet_fit = planet_model.fit(chains=4, inference_method="pymc", random_seed=seed)
planet_model.compute_log_likelihood(planet_fit)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, I(Time ** 2):Planet, Time]

Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 4 seconds.

The model has fit. Let’s look at how we did recovering the simulated parameters.

az.summary(planet_fit)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
sigma 1.421 0.116 1.3 1.6 2020 2175 1.01 0.0026 0.002
I(Time ** 2):Planet[Earth] -4.866 0.06 -5 -4.8 1821 2043 1.00 0.0014 0.001
I(Time ** 2):Planet[Mars] -1.8883 0.0178 -1.9 -1.9 1320 1621 1.00 0.00049 0.00036
I(Time ** 2):Planet[PlanetX] -3.048 0.029 -3.1 -3 1382 1783 1.00 0.00079 0.00058
Time 20.233 0.135 20 20 1300 1506 1.00 0.0038 0.0028

Getting the gravities back to the physical value,

hdi
<xarray.DataTree 'posterior'>
Group: /posterior
    Dimensions:             (ci_bound: 2)
    Coordinates:
      * ci_bound            (ci_bound) <U5 40B 'lower' 'upper'
    Data variables:
        sigma               (ci_bound) float64 16B 0.1541 0.2097
        I(t ** 2)           (ci_bound) float64 16B -5.153 -4.738
        t                   (ci_bound) float64 16B 6.775 7.47
        Intercept_centered  (ci_bound) float64 16B 2.842 2.919
        Intercept           (ci_bound) float64 16B 1.298 1.533
hdi = az.hdi(planet_fit.posterior, prob=0.95)
print(
    f"g for Earth: {2*hdi['I(Time ** 2):Planet'].sel({'Planet_dim':'Earth', 'ci_bound':'lower'}):.2f} to {2*hdi['I(Time ** 2):Planet'].sel({'Planet_dim':'Earth', 'ci_bound':'upper'}):.2f} meters (True: -9.81 m)"
)
print(
    f"g for Mars: {2*hdi['I(Time ** 2):Planet'].sel({'Planet_dim':'Mars', 'ci_bound':'lower'}):.2f} to {2*hdi['I(Time ** 2):Planet'].sel({'Planet_dim':'Mars', 'ci_bound':'upper'}):.2f} meters (True: -3.72 m)"
)
print(
    f"g for PlanetX: {2*hdi['I(Time ** 2):Planet'].sel({'Planet_dim':'PlanetX', 'ci_bound':'lower'}):.2f} to {2*hdi['I(Time ** 2):Planet'].sel({'Planet_dim':'PlanetX', 'ci_bound':'upper'}):.2f} meters (True: -6.0 m)"
)
print(
    f"Initial velocity: {hdi['Time'].sel({'ci_bound':'lower'}):.2f} to {hdi['Time'].sel({'ci_bound':'upper'}):.2f} meters per second (True: 20 m/s)"
)
g for Earth: -9.97 to -9.50 meters (True: -9.81 m)
g for Mars: -3.85 to -3.71 meters (True: -3.72 m)
g for PlanetX: -6.21 to -5.98 meters (True: -6.0 m)
Initial velocity: 19.96 to 20.50 meters per second (True: 20 m/s)

We can see that we’re pretty close to recovering most the parameters, but the fit isn’t great. Plotting the posteriors for g against the true values,

pc = az.plot_dist(
    -2 * planet_fit.posterior,
    var_names=["I(Time ** 2):Planet"],
    group="posterior",
    figure_kwargs={"figsize": (7, 3)},
)
axes = pc.get_viz("plot").to_numpy()
axes[0].axvline(9.81, ls="--", color="0.7")
axes[1].axvline(3.72, ls="--", color="0.7")
axes[2].axvline(6.0, ls="--", color="0.7");

The fit seems to work, more or less, but certainly could be improved.

Adding a prior

But, we can do better! We have a very good idea of the acceleration due to gravity on Earth and Mars, so why not use that information? From an experimental standpoint, we can consider these throws from a calibration mindset, allowing us to get some information on the resolution of our detector, and our throwing apparatus. The model will spend considerably less time trying to pin down those parameters, and will better explore other parameters with already good values of the g terms locked in.

For Earth, at the extremes, g takes values as low as 9.78 m/s^2 (at the Equator) up to 9.83 (at the Poles). So we can add a very strong prior,

g_{\text{Earth}} \sim \text{Normal}(-9.81, 0.025)

For Mars, we know the mean value is about 3.72 m/s^2. There’s less information on local variation readily available by a cursory search, however we know that the radius of Mars is about half that of Earth, so \sigma = \frac{0.025}{2} = 0.0125 might make sense, but to be conservative we’ll round that up to \sigma = 0.02.

g_{\text{Mars}} \sim \text{Normal}(-3.72, 0.02)

For PlanetX, we must use a very loose prior. We might say that we know the ball took longer to fall than Earth, but not as long as on Mars, so we can split the difference. Then set a very wide \sigma value.

g_{\text{PlanetX}} \sim \text{Normal}(\frac{-9.81 - 3.72}{2}, 3) = \text{Normal}(-6.77, 3)

Since these correspond to g/2, we’ll divide all values by 2 when putting them into Bambi. Additionally, we know the balls landed eventually, so g must be negative. We’ll truncate the upper limit of the distribution at 0.

Now, for defining this in Bambi, the term of interest is I(Time ** 2):Planet. Often, you set one prior that applies to all groups, however, if you want to set each group individually, you can pass a list to the bmb.Prior definition. The broadcasting rules from PyMC apply here, so it could equivalently take a numpy array. You’ll notice that the priors are passed alphabetically by group name.

priors = {
    "I(Time ** 2):Planet": bmb.Prior(
        "TruncatedNormal",
        mu=np.array([-9.81 / 2, -3.72 / 2, -6.77 / 2]),  # Earth  # Mars  # PlanetX
        sigma=np.array([0.025 / 2, 0.02 / 2, 3 / 2]),  # Earth  # Mars  # PlanetX
        upper=np.array([0, 0, 0]),
    )
}

planet_model_with_prior = bmb.Model(
    "Height ~ I(Time**2):Planet + Time + 0", df, priors=priors
)

planet_model_with_prior.build()
idata = planet_model_with_prior.prior_predictive()
az.summary(idata, group="prior", var_names="~mu", kind="stats")
/home/tomas/oss/bambinos/bambi/.pixi/envs/dev/lib/python3.14/site-packages/pytensor/link/numba/dispatch/basic.py:234: UserWarning: Numba will use object mode to run truncated_normal_rv{"(),(),(),()->()"}'s perform method. Set `pytensor.config.compiler_verbose = True` to see more details.
  warnings.warn(
mean sd eti89_lb eti89_ub
I(Time ** 2):Planet[Earth] -4.9 0.012 -4.9 -4.9
I(Time ** 2):Planet[Mars] -1.9 0.0098 -1.9 -1.8
I(Time ** 2):Planet[PlanetX] -3.5 1.4 -5.7 -1
sigma 15 14 0.97 41
Time -0.064 16 -25 25

Here we’ve sampled the prior predictive and can see that our priors are correctly specified to the associated planets.

Next we fit the model.

planet_fit_with_prior = planet_model_with_prior.fit(
    chains=4, inference_method="pymc", random_seed=seed
)
planet_model_with_prior.compute_log_likelihood(planet_fit_with_prior)
az.summary(planet_fit_with_prior)
planet_model_with_prior.predict(planet_fit_with_prior, kind="response");
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, I(Time ** 2):Planet, Time]
/home/tomas/oss/bambinos/bambi/.pixi/envs/dev/lib/python3.14/site-packages/pymc/step_methods/hmc/quadpotential.py:321: RuntimeWarning: overflow encountered in dot
  return 0.5 * np.dot(x, v_out)
/home/tomas/oss/bambinos/bambi/.pixi/envs/dev/lib/python3.14/site-packages/pymc/step_methods/hmc/quadpotential.py:321: RuntimeWarning: overflow encountered in dot
  return 0.5 * np.dot(x, v_out)

Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 4 seconds.
az.summary(planet_fit_with_prior, var_names="~mu")
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
sigma 1.435 0.117 1.3 1.6 4120 2236 1.00 0.0019 0.0015
I(Time ** 2):Planet[Earth] -4.9002 0.0123 -4.9 -4.9 4120 2826 1.00 0.00019 0.00014
I(Time ** 2):Planet[Mars] -1.8723 0.0083 -1.9 -1.9 2427 2605 1.00 0.00017 0.00012
I(Time ** 2):Planet[PlanetX] -3.0296 0.0193 -3.1 -3 2631 2546 1.00 0.00038 0.00028
Time 20.131 0.068 20 20 2319 2121 1.00 0.0014 0.001

We see some improvements here! Off the cuff, these look better, you’ll notice the v_0 coefficient on Time covers the true value of 20 m/s.

Now taking a look at the effects before and after adding the prior on the gravities,

pc = az.plot_dist(
    {
        "No prior": -2 * planet_fit.posterior,
        "Priors used": -2 * planet_fit_with_prior.posterior,
    },
    var_names=["I(Time ** 2):Planet"],
    group="posterior",
    figure_kwargs={"figsize": (7, 3.5), "layout": "constrained"},
)

axes = pc.get_viz("plot").to_numpy()
axes[0].axvline(9.81, ls="--", color="0.7")
axes[1].axvline(3.72, ls="--", color="0.7")
axes[2].axvline(6.0, ls="--", color="0.7")
pc.add_legend("model", loc="outside lower center", ncols=2);

Adding the prior gives smaller uncertainties for Earth and Mars by design, however, we can see the estimate for PlanetX has also considerably improved by injecting our knowledge into the model.

%load_ext watermark
%watermark -n -u -v -iv -w
Last updated: Sat, 29 Aug 2026

Python implementation: CPython
Python version       : 3.14.7
IPython version      : 9.16.1

arviz     : 1.3.0
bambi     : 0.20.1.dev78+g69d4473ea.d20260829
matplotlib: 3.11.1
numpy     : 2.4.6
pandas    : 2.3.3

Watermark: 2.6.0