# Gaussian Processes

This article demonstrates the how to use Bambi with Gaussian Processes with 1 dimensional predictors. Bambi supports Gaussian Processes through the approximation known as Hilbert Space Gaussian Processes (HSGP).

HSGP is a framework that falls under the class of low-rank approximations that are based on forming a basis function approximation with $`m`$ basis functions, where $`m`$ is usually much less smaller than $`n`$, the number of observations.

For references see [Hilbert Space Methods for Reduced-Rank Gaussian Process Regression](https://arxiv.org/abs/1401.5508) and [Practical Hilbert Space Approximate Bayesian Gaussian Processes for Probabilistic Programming](https://arxiv.org/abs/2004.11408).

If you prefer a video format, have a look at [Introduction to Hilbert Space GPs in PyMC](https://www.youtube.com/watch?v=ri5sJAdcYHk&ab_channel=PyMCDevelopers) given by Bill Engels.

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

from formulae import design_matrices

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

from bambi.interpret import plot_predictions

plt.style.use("bambi.mplstyle")
seed = sum(map(ord, "GP 1D"))
rng = np.random.default_rng(seed)
```

## A basic example

Let's get started simulating some data from a smooth function. The goal is to fit a normal likelihood model where a Gaussian process term contributes to the mean.

``` python
size = 100
x = np.linspace(0, 50, size)
b = 0.1 * rng.normal(size=6)
sigma = 0.15

dm = design_matrices("0 + bs(x, df=6, intercept=True)", pd.DataFrame({"x": x}))
X = np.asarray(dm.common)
f = 10 * X @ b
y = f + rng.normal(size=size) * sigma
df = pd.DataFrame({"x": x, "y": y})

fig, ax = plt.subplots()
ax.scatter(df["x"], df["y"], color="0.2", alpha=0.5, s=30)
ax.plot(x, f, color="black");
```

![](hsgp_1d_files/figure-html/cell-3-output-1.png)

Now let's simply create and fit the model. We use the `hsgp` to initialize a HSGP term in the model formula. Notice we pass the variable `x` and values for two other arguments `m` and `c` that we'll cover later.

``` python
model = bmb.Model("y ~ 0 + hsgp(x, m=10, c=2)", df)
model
```

           Formula: y ~ 0 + hsgp(x, m=10, c=2)
            Family: gaussian
              Link: mu = identity
      Observations: 100
            Priors: 
        target = mu
            HSGP contributions
                hsgp(x, m=10, c=2)
                    cov: ExpQuad
                    sigma ~ Exponential(lam: 1.0)
                    ell ~ InverseGamma(alpha: 3.0, beta: 2.0)
            
            Auxiliary parameters
                sigma ~ HalfStudentT(nu: 4.0, sigma: 0.2453)

In the model description we can see the contribution of the HSGP term. It consists of two things: the name of the covariance kernel and the priors for its parameters. In this case, it's an **Exp**onentiated **Quad**ratic covariance kernel with parameters `sigma` (amplitude) and `ell` (lengthscale). The prior for the amplitude is `Exponential(1)` and the prior for the lengthscale is `InverseGamma(3, 2)`.

``` python
idata = model.fit(inference_method="numpyro", random_seed=seed)
print(idata.sample_stats["diverging"].sum().to_numpy())
```

    NUTS[numpyro]: [sigma, hsgp(x, m=10, c=2)_sigma, hsgp(x, m=10, c=2)_ell, hsgp(x, m=10, c=2)_weights_raw]
    An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

    There were 171 divergences after tuning. Increase `target_accept` or reparameterize.

    171

``` python
idata.posterior
```

![](data:image/svg+xml;base64,PHN2ZyBzdHlsZT0icG9zaXRpb246IGFic29sdXRlOyB3aWR0aDogMDsgaGVpZ2h0OiAwOyBvdmVyZmxvdzogaGlkZGVuIj4KPGRlZnM+CjxzeW1ib2wgaWQ9Imljb24tZGF0YWJhc2UiIHZpZXdib3g9IjAgMCAzMiAzMiI+CjxwYXRoIGQ9Ik0xNiAwYy04LjgzNyAwLTE2IDIuMjM5LTE2IDV2NGMwIDIuNzYxIDcuMTYzIDUgMTYgNXMxNi0yLjIzOSAxNi01di00YzAtMi43NjEtNy4xNjMtNS0xNi01eiIgLz4KPHBhdGggZD0iTTE2IDE3Yy04LjgzNyAwLTE2LTIuMjM5LTE2LTV2NmMwIDIuNzYxIDcuMTYzIDUgMTYgNXMxNi0yLjIzOSAxNi01di02YzAgMi43NjEtNy4xNjMgNS0xNiA1eiIgLz4KPHBhdGggZD0iTTE2IDI2Yy04LjgzNyAwLTE2LTIuMjM5LTE2LTV2NmMwIDIuNzYxIDcuMTYzIDUgMTYgNXMxNi0yLjIzOSAxNi01di02YzAgMi43NjEtNy4xNjMgNS0xNiA1eiIgLz4KPC9zeW1ib2w+CjxzeW1ib2wgaWQ9Imljb24tZmlsZS10ZXh0MiIgdmlld2JveD0iMCAwIDMyIDMyIj4KPHBhdGggZD0iTTI4LjY4MSA3LjE1OWMtMC42OTQtMC45NDctMS42NjItMi4wNTMtMi43MjQtMy4xMTZzLTIuMTY5LTIuMDMwLTMuMTE2LTIuNzI0Yy0xLjYxMi0xLjE4Mi0yLjM5My0xLjMxOS0yLjg0MS0xLjMxOWgtMTUuNWMtMS4zNzggMC0yLjUgMS4xMjEtMi41IDIuNXYyN2MwIDEuMzc4IDEuMTIyIDIuNSAyLjUgMi41aDIzYzEuMzc4IDAgMi41LTEuMTIyIDIuNS0yLjV2LTE5LjVjMC0wLjQ0OC0wLjEzNy0xLjIzLTEuMzE5LTIuODQxek0yNC41NDMgNS40NTdjMC45NTkgMC45NTkgMS43MTIgMS44MjUgMi4yNjggMi41NDNoLTQuODExdi00LjgxMWMwLjcxOCAwLjU1NiAxLjU4NCAxLjMwOSAyLjU0MyAyLjI2OHpNMjggMjkuNWMwIDAuMjcxLTAuMjI5IDAuNS0wLjUgMC41aC0yM2MtMC4yNzEgMC0wLjUtMC4yMjktMC41LTAuNXYtMjdjMC0wLjI3MSAwLjIyOS0wLjUgMC41LTAuNSAwIDAgMTUuNDk5LTAgMTUuNSAwdjdjMCAwLjU1MiAwLjQ0OCAxIDEgMWg3djE5LjV6IiAvPgo8cGF0aCBkPSJNMjMgMjZoLTE0Yy0wLjU1MiAwLTEtMC40NDgtMS0xczAuNDQ4LTEgMS0xaDE0YzAuNTUyIDAgMSAwLjQ0OCAxIDFzLTAuNDQ4IDEtMSAxeiIgLz4KPHBhdGggZD0iTTIzIDIyaC0xNGMtMC41NTIgMC0xLTAuNDQ4LTEtMXMwLjQ0OC0xIDEtMWgxNGMwLjU1MiAwIDEgMC40NDggMSAxcy0wLjQ0OCAxLTEgMXoiIC8+CjxwYXRoIGQ9Ik0yMyAxOGgtMTRjLTAuNTUyIDAtMS0wLjQ0OC0xLTFzMC40NDgtMSAxLTFoMTRjMC41NTIgMCAxIDAuNDQ4IDEgMXMtMC40NDggMS0xIDF6IiAvPgo8L3N5bWJvbD4KPC9kZWZzPgo8L3N2Zz4=)

``` xr-text-repr-fallback
<xarray.DataTree 'posterior'>
Group: /posterior
    Dimensions:                         (chain: 4, draw: 1000,
                                         hsgp(x, m=10, c=2)_weights_dim: 10,
                                         __obs__: 100)
    Coordinates:
      * chain                           (chain) int64 32B 0 1 2 3
      * draw                            (draw) int64 8kB 0 1 2 3 ... 996 997 998 999
      * hsgp(x, m=10, c=2)_weights_dim  (hsgp(x, m=10, c=2)_weights_dim) int64 80B ...
      * __obs__                         (__obs__) int64 800B 0 1 2 3 ... 96 97 98 99
    Data variables:
        hsgp(x, m=10, c=2)_weights_raw  (chain, draw, hsgp(x, m=10, c=2)_weights_dim) float64 320kB ...
        sigma                           (chain, draw) float64 32kB ...
        hsgp(x, m=10, c=2)_sigma        (chain, draw) float64 32kB ...
        hsgp(x, m=10, c=2)_ell          (chain, draw) float64 32kB ...
        hsgp(x, m=10, c=2)_weights      (chain, draw, hsgp(x, m=10, c=2)_weights_dim) float64 320kB ...
        hsgp(x, m=10, c=2)              (chain, draw, __obs__) float64 3MB ...
    Attributes:
        created_at:                  2026-08-29T15:09:38.749154+00:00
        creation_library:            ArviZ
        creation_library_version:    1.3.0
        creation_library_language:   Python
        sample_dims:                 ['chain', 'draw']
        inference_library:           numpyro
        inference_library_version:   0.21.0
        sampling_time:               3.742185
        tuning_steps:                1000
        modeling_interface:          bambi
        modeling_interface_version:  0.20.1.dev78+g69d4473ea.d20260829
```

xarray.DataTree

'posterior'

Dimensions:

- chain: 4
- draw: 1000
- hsgp(x, m=10, c=2)\_weights_dim: 10
- \_\_obs\_\_: 100

Coordinates: (4)

chain

(chain)

int64

0 1 2 3

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    array([0, 1, 2, 3])

draw

(draw)

int64

0 1 2 3 4 5 ... 995 996 997 998 999

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    array([  0,   1,   2, ..., 997, 998, 999], shape=(1000,))

hsgp(x, m=10, c=2)\_weights_dim

(hsgp(x, m=10, c=2)\_weights_dim)

int64

0 1 2 3 4 5 6 7 8 9

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

\_\_obs\_\_

(\_\_obs\_\_)

int64

0 1 2 3 4 5 6 ... 94 95 96 97 98 99

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
           18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
           36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
           54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
           72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
           90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

Data variables: (6)

hsgp(x, m=10, c=2)\_weights_raw

(chain, draw, hsgp(x, m=10, c=2)\_weights_dim)

float64

...

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    Array([[[-0.09791026, -1.62712086,  0.44066824, ...,  1.33461362,
             -0.21127806, -1.49605607],
            [-0.35304923,  1.23992533, -0.14882454, ...,  0.43439872,
              0.19015342, -0.51281678],
            [-0.4691033 , -0.60960238,  0.18539051, ...,  2.85023791,
              1.34883328,  0.53474181],
            ...,
            [-0.28124855, -1.54927772, -0.762654  , ...,  1.81117656,
             -1.71186665, -0.18795534],
            [-0.20601436,  0.47646095,  1.33901752, ...,  0.23276365,
              1.83457354, -1.84091359],
            [-0.27282326, -0.67571779, -0.24543531, ...,  2.34617089,
             -1.14703415,  0.35485549]],

           [[ 0.50306481,  0.43909854, -0.92188276, ...,  1.28157833,
             -0.45408189, -0.88323693],
            [-0.59267209, -0.64757859,  0.38812913, ...,  0.86949024,
              0.73189322, -0.4767456 ],
            [ 0.53897899, -1.67026201,  0.00522889, ...,  1.91738036,
              1.76870124, -0.96016739],
    ...
            [-1.08548206,  1.48330963, -0.03564206, ...,  1.32402238,
              0.14311391, -0.33691393],
            [ 0.02513183, -2.38671247,  0.53373674, ...,  2.867206  ,
              1.848657  , -2.62844137],
            [-0.12155927, -2.48352344,  0.8631622 , ...,  2.32282385,
              2.20530813, -2.18320965]],

           [[ 1.05626935, -0.246209  ,  0.64356278, ...,  2.16798278,
             -0.17455918, -0.59060604],
            [-0.34520741,  2.68913005, -0.27210968, ...,  1.09289686,
             -0.9590802 , -2.43873778],
            [-1.73030429, -1.74212381, -0.00902904, ...,  0.62412494,
             -0.09755944, -0.58647709],
            ...,
            [-0.19439925, -0.71075505,  0.69817925, ...,  0.8490751 ,
              0.68220739, -1.43323846],
            [-0.72215504,  0.51628907, -0.27749438, ...,  0.74990001,
             -0.09414391, -0.14451729],
            [ 1.1653386 , -0.70015302,  1.36071362, ...,  0.83977728,
              0.20311736, -1.72061393]]], dtype=float64)

sigma

(chain, draw)

float64

...

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    Array([[0.24261334, 0.21043337, 0.21958345, ..., 0.21874134, 0.22376457,
            0.2285591 ],
           [0.25154753, 0.19871462, 0.23199526, ..., 0.24239165, 0.24005185,
            0.20639071],
           [0.2237526 , 0.21580614, 0.24344294, ..., 0.26167834, 0.21725951,
            0.22038138],
           [0.22350812, 0.23742504, 0.23814338, ..., 0.21881272, 0.22030234,
            0.22925096]], dtype=float64)

hsgp(x, m=10, c=2)\_sigma

(chain, draw)

float64

...

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    Array([[1.49931906, 3.76827991, 2.61325472, ..., 2.3015771 , 2.57632789,
            3.64569109],
           [2.11128344, 1.30959562, 1.65286812, ..., 2.74277693, 2.76203422,
            2.38969594],
           [2.46787703, 1.58366325, 1.87226054, ..., 1.0670931 , 0.99922505,
            1.08268677],
           [2.25295588, 2.63987588, 1.93253513, ..., 2.94229523, 2.72917731,
            2.28925098]], dtype=float64)

hsgp(x, m=10, c=2)\_ell

(chain, draw)

float64

...

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    Array([[1.175908  , 0.86960554, 0.92909629, ..., 4.02194062, 0.41711397,
            1.61667134],
           [0.37279692, 0.82839856, 1.01486165, ..., 0.22900144, 0.50364168,
            0.33687126],
           [1.50662297, 0.64688617, 1.33620177, ..., 1.39406889, 0.65761253,
            0.83113288],
           [0.89373752, 0.56854145, 0.74560558, ..., 0.51666262, 1.89712402,
            0.46992311]], dtype=float64)

hsgp(x, m=10, c=2)\_weights

(chain, draw, hsgp(x, m=10, c=2)\_weights_dim)

float64

...

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    Array([[[-2.51945002e-01, -4.18266249e+00,  1.13084710e+00, ...,
              3.36122935e+00, -5.29027261e-01, -3.72182730e+00],
            [-1.96382826e+00,  6.89319660e+00, -8.26598291e-01, ...,
              2.38809509e+00,  1.04205257e+00, -2.80032266e+00],
            [-1.87039385e+00, -2.42903475e+00,  7.37924713e-01, ...,
              1.12129048e+01,  5.28716399e+00,  2.08761849e+00],
            ...,
            [-2.04712905e+00, -1.11425361e+01, -5.37669497e+00, ...,
              1.02520894e+01, -9.05428079e+00, -9.21519126e-01],
            [-5.42690631e-01,  1.25494937e+00,  3.52607817e+00, ...,
              6.11498551e-01,  4.81613277e+00, -4.82883647e+00],
            [-2.00095362e+00, -4.94630368e+00, -1.79082075e+00, ...,
              1.65223123e+01, -7.98962379e+00,  2.44163179e+00]],

           [[ 1.02668382e+00,  8.96045559e-01, -1.88091569e+00, ...,
              2.60987496e+00, -9.24177848e-01, -1.79645207e+00],
            [-1.11826000e+00, -1.22123765e+00,  7.31334832e-01, ...,
              1.62315588e+00,  1.36236387e+00, -8.84575477e-01],
            [ 1.42052231e+00, -4.39875453e+00,  1.37531727e-02, ...,
              4.97314818e+00,  4.56773999e+00, -2.46772568e+00],
    ...
            [-2.16423188e+00,  2.95316830e+00, -7.07909729e-02, ...,
              2.56127665e+00,  2.74601361e-01, -6.40594190e-01],
            [ 3.22382218e-02, -3.06061047e+00,  6.84074421e-01, ...,
              3.65330896e+00,  2.35123507e+00, -3.33624186e+00],
            [-1.89931539e-01, -3.87842326e+00,  1.34681901e+00, ...,
              3.59055723e+00,  3.39904152e+00, -3.35410150e+00]],

           [[ 3.56116202e+00, -8.29591303e-01,  2.16632305e+00, ...,
              7.21905670e+00, -5.79311606e-01, -1.95272516e+00],
            [-1.08781491e+00,  8.47193857e+00, -8.56922978e-01, ...,
              3.42666706e+00, -3.00302412e+00, -7.62449149e+00],
            [-4.57077512e+00, -4.60010421e+00, -2.38249634e-02, ...,
              1.63450355e+00, -2.54900635e-01, -1.52834285e+00],
            ...,
            [-6.50879694e-01, -2.37925107e+00,  2.33638405e+00, ...,
              2.83106693e+00,  2.27213521e+00, -4.76752212e+00],
            [-4.29407235e+00,  3.06178600e+00, -1.63835401e+00, ...,
              4.21643179e+00, -5.21407841e-01, -7.87004882e-01],
            [ 2.89521117e+00, -1.73920225e+00,  3.37913496e+00, ...,
              2.07922478e+00,  5.02437552e-01, -4.25176126e+00]]],      dtype=float64)

hsgp(x, m=10, c=2)

(chain, draw, \_\_obs\_\_)

float64

...

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    Array([[[-0.43819698, -0.43518747, -0.43217637, ..., -0.14222317,
             -0.13916601, -0.1361095 ],
            [-0.46604404, -0.46221606, -0.458387  , ..., -0.0936319 ,
             -0.08982277, -0.08601511],
            [-0.45678935, -0.45307898, -0.44937115, ..., -0.11114986,
             -0.10776128, -0.10437675],
            ...,
            [-0.45536982, -0.45179494, -0.44821227, ..., -0.07542672,
             -0.07119681, -0.06696133],
            [-0.47790423, -0.47366477, -0.46942724, ..., -0.08014624,
             -0.07623456, -0.07232768],
            [-0.42403153, -0.42159096, -0.41914224, ..., -0.15171141,
             -0.14855768, -0.14539752]],

           [[-0.41284992, -0.40970707, -0.40656054, ..., -0.09364619,
             -0.09023457, -0.08682112],
            [-0.35539849, -0.35401239, -0.3526264 , ..., -0.22289876,
             -0.22156816, -0.22023858],
            [-0.42508602, -0.42172704, -0.41836795, ..., -0.10222672,
             -0.09896601, -0.09570743],
    ...
            [-0.2696337 , -0.26968094, -0.26972803, ..., -0.2742775 ,
             -0.27433461, -0.27439209],
            [-0.42189053, -0.41877737, -0.41566395, ..., -0.12216197,
             -0.1191322 , -0.11610441],
            [-0.45860881, -0.45505171, -0.45149541, ..., -0.12089989,
             -0.11753349, -0.11417021]],

           [[-0.40608935, -0.40294623, -0.39979951, ..., -0.08795711,
             -0.08457646, -0.08119456],
            [-0.46299307, -0.4596474 , -0.4562979 , ..., -0.12678918,
             -0.1232674 , -0.1197459 ],
            [-0.44421947, -0.44104549, -0.4378707 , ..., -0.13485668,
             -0.13167621, -0.12849644],
            ...,
            [-0.45606197, -0.45244516, -0.44882784, ..., -0.10726901,
             -0.10374118, -0.10021569],
            [-0.46203978, -0.45853466, -0.45503039, ..., -0.12875411,
             -0.12541826, -0.12208505],
            [-0.43022581, -0.42669486, -0.42316116, ..., -0.0788477 ,
             -0.07517449, -0.07150114]]], dtype=float64)

Attributes: (11)

created_at :  
2026-08-29T15:09:38.749154+00:00

creation_library :  
ArviZ

creation_library_version :  
1.3.0

creation_library_language :  
Python

sample_dims :  
\['chain', 'draw'\]

inference_library :  
numpyro

inference_library_version :  
0.21.0

sampling_time :  
3.742185

tuning_steps :  
1000

modeling_interface :  
bambi

modeling_interface_version :  
0.20.1.dev78+g69d4473ea.d20260829

``` python
az.plot_trace_dist(
    idata,
    var_names=[
        "sigma",
        "hsgp(x, m=10, c=2)_sigma",
        "hsgp(x, m=10, c=2)_ell",
        "hsgp(x, m=10, c=2)_weights",
    ],
    figure_kwargs={"figsize": (7, 5)},
);
```

![](hsgp_1d_files/figure-html/cell-7-output-1.png)

The fit is horrible. To fix that we can use better priors. But before doing that, it's important to note that HSGP terms have a unique characteristic in that they do not receive priors themselves. Rather, the associated parameters of an HSGP term, such as `sigma` and `ell`, are the ones that are assigned priors. Therefore, we need to assign the HSGP term a dictionary of priors instead of a single prior.

``` python
prior_hsgp = {
    "sigma": bmb.Prior("Exponential", lam=2),  # amplitude
    "ell": bmb.Prior("InverseGamma", mu=10, sigma=1),  # lengthscale
}

# This is the dictionary we pass to Bambi
priors = {"hsgp(x, m=10, c=2)": prior_hsgp, "sigma": bmb.Prior("HalfNormal", sigma=10)}
model = bmb.Model("y ~ 0 + hsgp(x, m=10, c=2)", df, priors=priors)
model
```

           Formula: y ~ 0 + hsgp(x, m=10, c=2)
            Family: gaussian
              Link: mu = identity
      Observations: 100
            Priors: 
        target = mu
            HSGP contributions
                hsgp(x, m=10, c=2)
                    cov: ExpQuad
                    sigma ~ Exponential(lam: 2.0)
                    ell ~ InverseGamma(mu: 10.0, sigma: 1.0)
            
            Auxiliary parameters
                sigma ~ HalfNormal(sigma: 10.0)

Notice the priors were updated in the model summary. Now we're ready to fit the model!

``` python
idata = model.fit(inference_method="numpyro", random_seed=seed)
print(idata.sample_stats["diverging"].sum().to_numpy())
```

    NUTS[numpyro]: [sigma, hsgp(x, m=10, c=2)_sigma, hsgp(x, m=10, c=2)_ell, hsgp(x, m=10, c=2)_weights_raw]

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

    There were 3 divergences after tuning. Increase `target_accept` or reparameterize.

    3

``` python
az.plot_trace_dist(
    idata,
    var_names=[
        "sigma",
        "hsgp(x, m=10, c=2)_sigma",
        "hsgp(x, m=10, c=2)_ell",
        "hsgp(x, m=10, c=2)_weights",
    ],
    figure_kwargs={"figsize": (7, 5)},
);
```

![](hsgp_1d_files/figure-html/cell-10-output-1.png)

The marginal posteriors look somehow better, but we still have lots of divergences. What else can we do? Change the parametrization!

The `hsgp()` function has a `centered` argument which defaults to `False` and thus Bambi uses a non-centered parametrization by default. But we can change that actually. Let's try it!

``` python
prior_hsgp = {
    "sigma": bmb.Prior("Exponential", lam=2),  # amplitude
    "ell": bmb.Prior("InverseGamma", mu=10, sigma=1),  # lengthscale
}

# This is the dictionary we pass to Bambi
priors = {
    "hsgp(x, m=10, c=2, centered=True)": prior_hsgp,
    "sigma": bmb.Prior("HalfNormal", sigma=10),
}
model = bmb.Model("y ~ 0 + hsgp(x, m=10, c=2, centered=True)", df, priors=priors)
model
```

           Formula: y ~ 0 + hsgp(x, m=10, c=2, centered=True)
            Family: gaussian
              Link: mu = identity
      Observations: 100
            Priors: 
        target = mu
            HSGP contributions
                hsgp(x, m=10, c=2, centered=True)
                    cov: ExpQuad
                    sigma ~ Exponential(lam: 2.0)
                    ell ~ InverseGamma(mu: 10.0, sigma: 1.0)
            
            Auxiliary parameters
                sigma ~ HalfNormal(sigma: 10.0)

``` python
idata = model.fit(inference_method="numpyro", random_seed=seed)
print(idata.sample_stats["diverging"].sum().to_numpy())
```

    NUTS[numpyro]: [sigma, hsgp(x, m=10, c=2, centered=True)_sigma, hsgp(x, m=10, c=2, centered=True)_ell, hsgp(x, m=10, c=2, centered=True)_weights]

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

    0

``` python
az.plot_trace_dist(
    idata,
    var_names=[
        "sigma",
        "hsgp(x, m=10, c=2, centered=True)_sigma",
        "hsgp(x, m=10, c=2, centered=True)_ell",
        "hsgp(x, m=10, c=2, centered=True)_weights",
    ],
    figure_kwargs={"figsize": (7, 5)},
);
```

![](hsgp_1d_files/figure-html/cell-13-output-1.png)

Awesome! That looks much better now.

We still get all the nice things from Bambi when using GPs. An example of this is the [plot_predictions](../reference/interpret.plot_predictions.md) function from the `interpret` module, which enables us to generate a visualization of the adjusted mean with credible bands automatically.

``` python
fig, ax = plt.subplots()
plot_predictions(
    model,
    idata,
    "x",
    fig_kwargs={"xlabel": "Predictor", "ylabel": "Observed"},
    on=ax,
)
ax.scatter(df["x"], df["y"], color="0.2", alpha=0.5, s=6);
```

![](hsgp_1d_files/figure-html/cell-14-output-1.png)

On top of that, we can also get a visualization with intervals of the posterior predictive distribution, for a grid of predictor values. To get that, we just pass `target="y"` to [plot_predictions](../reference/interpret.plot_predictions.md).

``` python
fig, ax = plt.subplots()
plot_predictions(
    model=model,
    idata=idata,
    conditional="x",
    target="y",
    fig_kwargs={"xlabel": "Predictor", "ylabel": "Observed"},
    on=ax,
)
ax.scatter(df["x"], df["y"], color="0.2", alpha=0.5, s=6)
ax.plot(x, f, color="black", linestyle="--");
```

![](hsgp_1d_files/figure-html/cell-15-output-1.png)

## How does `hsgp()` work?

`hsgp()` is a transformation that is available in the namespace where the model formula is evaluated. In plain English, `hsgp()` is like a function you can use in your model formulas. You don't need to worry about the details, Bambi knows how to handle them. But if still you want to see the actual code, you can have a look at the implementation of the `HSGP` class in [bambi/transformations.py](https://github.com/bambinos/bambi/blob/main/bambi/transformations.py).

What users do need to care about is the arguments the `hsgp()` transformation support. There are a bunch of arguments that can be passed after the variable number of non-keyword arguments representing the variables of the HSGP contribution. Below is a brief overview of these arguments and their respective descriptions.

- `m`: The number of basis vectors
- `L`: The boundary of the variable space
- `c`: The proportion extension factor
- `by`: This argument specifies the values of a variable used for grouping. It is used to create a HSGP term by group. If left unspecified, the default value is `None`, which means that there is no group variable and all observations belong to the same group.
- `cov`: This argument specifies the name of the covariance function to be used. The default value is `"ExpQuad"`.
- `share_cov`: Determines whether the same covariance function is shared across all groups. This argument is relevant only when by is not `None` and the default value is `True`.
- `scale`: When set to `True`, the predictors are be rescaled such that the largest Euclidean distance between two points is 1. This adjustment often improves the sampling speed and convergence.
- `iso`: Determines whether to use an isotropic or anisotropic (non-isotropic) Gaussian Process. With an isotropic GP, the same level of smoothing is applied to all predictors, while an anisotropic GP allows different levels of smoothing for individual predictors. Note that this argument is ignored if only one predictor is provided. The default value is `True`.
- `drop_first`: Whether to exclude the first basis vector or not. The default value is `False`.
- `centered`: Whether to use the centered or the non-centered parametrization. Defaults to `False`.

The parameters `m`, `L` and `c` are directly related to the basis vectors of the HSGP approximation. If you want to know more about `m`, `L`, and/or `c`, it's recommended to have a look at the documentation of the HSGP class in PyMC.

So far, we showcased how to use `m`, `c` and `centered`. In the remainder of this article we're going to see how `by` and `share_cov` are used when we add a GP contribution by groups.

## HSGP by levels of a categorical covariate

In this section we fit a model with a HSGP contribution by levels of a categorical variable. The data was simulated with the `gamSim()` function from the R package `{mgcv}` by Simon Wood.

``` python
data = pd.read_csv("data/gam_data.csv")
data["fac"] = pd.Categorical(data["fac"])
data.head()[["x2", "y", "fac"]]
```

|     | x2       | y         | fac |
|-----|----------|-----------|-----|
| 0   | 0.497183 | 3.085274  | 3   |
| 1   | 0.196003 | -2.250410 | 2   |
| 2   | 0.958474 | 0.070548  | 3   |
| 3   | 0.972759 | -0.230454 | 1   |
| 4   | 0.755836 | 2.173497  | 2   |

Let's visualize `x2` versus `y` for the different levels in `fac`.

``` python
fig, ax = plt.subplots()
for level, group in data.groupby("fac", observed=True):
    ax.scatter(group["x2"], group["y"], s=20, label=level)
ax.legend(title="fac");
```

![](hsgp_1d_files/figure-html/cell-17-output-1.png)

We can observe the relation between `x2` and `y` can be approximated by a smooth non-linear curve, for all groups.

Below, we create the model with Bambi. The biggest difference is that we're passing `by=fac` in the `hsgp()` call. This is all we need to ask Bambi to create multiple GP contribution terms, one per group.

Another trick that was not shown previously is the usage of an alias. `.set_alias()` from the [Model](../reference/Model.md) class allow us to have more readable and shorter names for the components of a model. As you'll see below, it makes a huge difference when displaying summaries or visualizations for the parameters of the model.

``` python
prior_hsgp = {
    "sigma": bmb.Prior("Exponential", lam=3),
    "ell": bmb.Prior("Exponential", lam=3),
}
priors = {
    "hsgp(x2, by=fac, m=12, c=1.5)": prior_hsgp,
    "sigma": bmb.Prior("HalfNormal", sigma=1),
}
model = bmb.Model("y ~ 0 + hsgp(x2, by=fac, m=12, c=1.5)", data, priors=priors)
model.set_alias({"hsgp(x2, by=fac, m=12, c=1.5)": "hsgp"})
model
```

           Formula: y ~ 0 + hsgp(x2, by=fac, m=12, c=1.5)
            Family: gaussian
              Link: mu = identity
      Observations: 300
            Priors: 
        target = mu
            HSGP contributions
                hsgp(x2, by=fac, m=12, c=1.5)
                    cov: ExpQuad
                    sigma ~ Exponential(lam: 3.0)
                    ell ~ Exponential(lam: 3.0)
            
            Auxiliary parameters
                sigma ~ HalfNormal(sigma: 1.0)

``` python
model.build()
model.graph()
```

![](hsgp_1d_files/figure-html/cell-19-output-1.svg)

See how nicer are the names for the HSGP contribution parameters with the alias!

``` python
idata = model.fit(inference_method="numpyro", target_accept=0.95, random_seed=seed)
print(idata.sample_stats.diverging.sum().item())
```

    NUTS[numpyro]: [sigma, hsgp_sigma, hsgp_ell, hsgp_weights_raw]

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

    0

``` python
az.plot_trace_dist(
    idata,
    var_names=["hsgp_weights", "hsgp_sigma", "hsgp_ell", "sigma"],
    figure_kwargs={"figsize": (7, 5)},
);
```

![](hsgp_1d_files/figure-html/cell-21-output-1.png)

This time we got no divergences and good mixing and nice convergence in our first try (or perhaps it wasn't the first try!). One thing that stands out are the marginal posterior for some of the beta parameters (the weights of the basis). This may indicate our approximation is using more basis vectors than what's really needed.

**Note:** At this point we have used the term 'basis vector' several times. This concept is very close to the concept of 'basis functions'. The difference is that the 'basis vector' is a 'basis function' already evaluated at a set of points. In this case, the set of points is made by the values of the numerical predictor `x2`.

Do you remember how easy was it to use [plot_predictions()](../reference/interpret.plot_predictions.md) above? Should it be harder now? Well, the answer will surprise you: No!

All we need to do is pass a second variable name, which is then mapped to the color in the visualization. Voilà!

``` python
fig = plot_predictions(model, idata, ["x2", "fac"])
ax = fig.axes[0]
for _, group in data.groupby("fac", observed=True):
    ax.scatter(group["x2"], group["y"], alpha=0.7, s=6)
fig
```

![](hsgp_1d_files/figure-html/cell-22-output-1.png)

We can go one step further and modify the model to use different covariance functions for the different groups. For that purpose, we pass `share_cov=False`. As always, Bambi takes care of all the details.

``` python
prior_hsgp = {
    "sigma": bmb.Prior("Exponential", lam=1),
    "ell": bmb.Prior("Exponential", lam=3),
}
priors = {
    "hsgp(x2, by=fac, m=12, c=1.5, share_cov=False)": prior_hsgp,
    "sigma": bmb.Prior("HalfNormal", sigma=1),
}
model = bmb.Model(
    "y ~ 0 + hsgp(x2, by=fac, m=12, c=1.5, share_cov=False)", data, priors=priors
)
model.set_alias({"hsgp(x2, by=fac, m=12, c=1.5, share_cov=False)": "hsgp"})
model
```

           Formula: y ~ 0 + hsgp(x2, by=fac, m=12, c=1.5, share_cov=False)
            Family: gaussian
              Link: mu = identity
      Observations: 300
            Priors: 
        target = mu
            HSGP contributions
                hsgp(x2, by=fac, m=12, c=1.5, share_cov=False)
                    cov: ExpQuad
                    sigma ~ Exponential(lam: 1.0)
                    ell ~ Exponential(lam: 3.0)
            
            Auxiliary parameters
                sigma ~ HalfNormal(sigma: 1.0)

``` python
model.build()
model.graph()
```

![](hsgp_1d_files/figure-html/cell-24-output-1.svg)

Have a closer look at the model graph. See that the `hsgp_sigma` and `hsgp_ell` parameters are no longer scalar. There are three of each, one for each group.

``` python
idata = model.fit(inference_method="numpyro", target_accept=0.95, random_seed=seed)
```

    NUTS[numpyro]: [sigma, hsgp_sigma, hsgp_ell, hsgp_weights_raw]

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

*\[Rich HTML output -- view on the documentation site\]*

    There was 1 divergence after tuning. Increase `target_accept` or reparameterize.

``` python
az.plot_trace_dist(
    idata,
    var_names=["hsgp_ell", "hsgp_sigma", "sigma"],
    figure_kwargs={"figsize": (7, 5)},
);
```

![](hsgp_1d_files/figure-html/cell-26-output-1.png)

In fact, we can see not all the groups have similar posteriors for the covariance function parameters when they are allowed to vary.

Before closing the article, it's worth looking at a particular but not uncommon pattern when using the HSGP approximation. Let's have a look at the posterior distributions for the weights of the basis.

``` python
az.plot_trace_dist(idata, var_names=["hsgp_weights"], figure_kwargs={"figsize": (7, 2)});
```

![](hsgp_1d_files/figure-html/cell-27-output-1.png)

Looks like some distributions are extremely flat, and others are extremely tight around zero.

To investigate this further we can manually plot the posterior for the first J basis vectors and see what they look like.

``` python
basis_n = 6
fig, axes = plt.subplots(3, 1, figsize=(7, 10))
for i in range(3):
    ax = axes[i]
    values = idata.posterior["hsgp_weights"].sel({"hsgp_by": i + 1})
    for j in range(basis_n):
        x, f, _ = az.kde(values.sel({"hsgp_weights_dim": j}).to_numpy().flatten())
        ax.plot(x, f, color=f"C{j}", label=f"Basis {i * basis_n + j + 1}")
    ax.set(ylabel="Density")

fig.legend(loc="center left", bbox_to_anchor=(0.95, 0.5));
```

![](hsgp_1d_files/figure-html/cell-28-output-1.png)

Indeed, we can see that, at least for the first group, the posterior of the weights start being too tight around zero when we consider the 6th basis vector. But the posteriors for the weights of the previous basis vectors look nice.

To confirm our thought, let's increase the value of `basis_n` to 9 and see what happens.

``` python
basis_n = 9
fig, axes = plt.subplots(3, 1, figsize=(7, 10))
for i in range(3):
    ax = axes[i]
    values = idata.posterior["hsgp_weights"].sel({"hsgp_by": i + 1})
    for j in range(basis_n):
        x, f, _ = az.kde(values.sel({"hsgp_weights_dim": j}).to_numpy().flatten())
        ax.plot(x, f, color=f"C{j}", label=f"Basis {i * basis_n + j + 1}")

    ax.set(ylabel="Density")

fig.legend(loc="center left", bbox_to_anchor=(0.95, 0.5));
```

![](hsgp_1d_files/figure-html/cell-29-output-1.png)

Alright, that's too spiky! Nonetheless, we don't see that happening for the third group yet, indicating the higher number of basis vectors is more appropriate for this group.

``` python
%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
    formulae  : 0.7.0
    matplotlib: 3.11.1
    numpy     : 2.4.6
    pandas    : 2.3.3

    Watermark: 2.6.0
