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 azimport bambi as bmbimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdplt.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 = 0m/s, x_0 = 50m and a = g, the acceleration due to gravity, -9.81m/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 secondsinital_height =50x_falling =0.5* g * t**2+ inital_heightnoise = rng.normal(0, 0.3, x_falling.shape)x_obs_falling = x_falling + noisedf_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.
Each of these provides identical results, giving -4.9, which is g/2. This makes the acceleration exactly the -9.81m/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 = 50m 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"].valuescalculated_g_posterior =-2* results_falling.posterior["I(t ** 2)"].valuescalculated_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.
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.
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 >=0return ( times[valid_indices], heights_with_noise[valid_indices], heights[valid_indices], )# Define the parametersv0 =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 datarecords = []for planet, g in g_planets.items(): times, heights, heights_true = simulate_throw(v0, g, noise_std)for time, height, height_true inzip(times, heights, heights_true): records.append([planet, time, height, height_true])# Convert to a DataFramedf = pd.DataFrame(records, columns=["Planet", "Time", "Height", "Height_true"])df["Planet"] = df["Planet"].astype("category")
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,
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.
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 gmust 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.
/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.
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