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

# Robust Linear Regression

This example has been lifted from the PyMC Docs, and adapted to for Bambi by Tyler James Burch (@tjburch on GitHub).

Many toy datasets circumvent problems that practitioners run into with real data. Specifically, the assumption of normality can be easily violated by outliers, which can cause havoc in traditional linear regression. One way to navigate this is through *robust linear regression*, outlined in this example.

First load modules and set the RNG for reproducibility.

```
"arviz-darkgrid")
az.style.use(1111) np.random.seed(
```

Next, generate pseudodata. The bulk of the data will be linear with noise distributed normally, but additionally several outliers will be interjected.

```
= 100
size = 1
true_intercept = 2
true_slope
= np.linspace(0, 1, size)
x # y = a + b*x
= true_intercept + true_slope * x
true_regression_line # add noise
= true_regression_line + np.random.normal(scale=0.5, size=size)
y
# Add outliers
= np.append(x, [0.1, 0.15, 0.2])
x_out = np.append(y, [8, 6, 9])
y_out
= pd.DataFrame({
data "x": x_out,
"y": y_out
})
```

Plot this data. The three data points in the top left are the interjected data.

```
= plt.figure(figsize=(7, 7))
fig = fig.add_subplot(111, xlabel="x", ylabel="y", title="Generated data and underlying model")
ax "x", label="sampled data")
ax.plot(x_out, y_out, ="true regression line", lw=2.0)
ax.plot(x, true_regression_line, label=0); plt.legend(loc
```

To highlight the problem, first fit a standard normally-distributed linear regression.

```
# Note, "gaussian" is the default argument for family. Added to be explicit.
= bmb.Model("y ~ x", data, family="gaussian")
gauss_model = gauss_model.fit(draws=2000, idata_kwargs={"log_likelihood": True})
gauss_fitted ="pps") gauss_model.predict(gauss_fitted, kind
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [y_sigma, Intercept, x]
```

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

` az.summary(gauss_fitted)`

mean | sd | hdi_3% | hdi_97% | mcse_mean | mcse_sd | ess_bulk | ess_tail | r_hat | |
---|---|---|---|---|---|---|---|---|---|

Intercept | 1.533 | 0.230 | 1.093 | 1.959 | 0.003 | 0.002 | 5481.0 | 2857.0 | 1.0 |

x | 1.201 | 0.400 | 0.458 | 1.964 | 0.005 | 0.004 | 5177.0 | 2869.0 | 1.0 |

y_sigma | 1.186 | 0.085 | 1.032 | 1.351 | 0.001 | 0.001 | 5873.0 | 2891.0 | 1.0 |

y_mean[0] | 1.533 | 0.230 | 1.093 | 1.959 | 0.003 | 0.002 | 5481.0 | 2857.0 | 1.0 |

y_mean[1] | 1.546 | 0.227 | 1.113 | 1.963 | 0.003 | 0.002 | 5487.0 | 2857.0 | 1.0 |

... | ... | ... | ... | ... | ... | ... | ... | ... | ... |

y_mean[98] | 2.722 | 0.227 | 2.288 | 3.143 | 0.003 | 0.002 | 5461.0 | 3205.0 | 1.0 |

y_mean[99] | 2.734 | 0.230 | 2.307 | 3.176 | 0.003 | 0.002 | 5454.0 | 3232.0 | 1.0 |

y_mean[100] | 1.653 | 0.197 | 1.290 | 2.027 | 0.003 | 0.002 | 5512.0 | 3038.0 | 1.0 |

y_mean[101] | 1.714 | 0.181 | 1.376 | 2.048 | 0.002 | 0.002 | 5539.0 | 3273.0 | 1.0 |

y_mean[102] | 1.774 | 0.166 | 1.447 | 2.064 | 0.002 | 0.002 | 5572.0 | 3294.0 | 1.0 |

106 rows × 9 columns

Remember, the true intercept was 1, the true slope was 2. The recovered intercept is much higher, and the slope is much lower, so the influence of the outliers is apparent.

Visually, looking at the recovered regression line and posterior predictive HDI highlights the problem further.

```
=(7, 5))
plt.figure(figsize# Plot Data
"x", label="data")
plt.plot(x_out, y_out, # Plot recovered linear regression
= np.linspace(min(x_out), max(x_out), 2000)
x_range = gauss_fitted.posterior.x.mean().item() * x_range + gauss_fitted.posterior.Intercept.mean().item()
y_pred
plt.plot(x_range, y_pred, ="black",linestyle="--",
color="Recovered regression line"
label
)# Plot HDIs
for interval in [0.38, 0.68]:
az.plot_hdi(x_out, gauss_fitted.posterior_predictive.y, =interval, color="firebrick")
hdi_prob# Plot true regression line
plt.plot(x, true_regression_line, ="True regression line", lw=2.0, color="black")
label=0); plt.legend(loc
```

The recovered regression line, as well as the \(0.5\sigma\) and \(1\sigma\) bands are shown.

Clearly there is skew in the fit. At lower \(x\) values, the regression line is far higher than the true line. This is a result of the outliers, which cause the model to assume a higher value in that regime.

Additionally the uncertainty bands are too wide (remember, the \(1\sigma\) band ought to cover 68% of the data, while here it covers most of the points). Due to the small probability mass in the tails of a normal distribution, the outliers have an large effect, causing the uncertainty bands to be oversized.

Clearly, assuming the data are distributed normally is inducing problems here. Bayesian robust linear regression forgoes the normality assumption by instead using a Student T distribution to describe the distribution of the data. The Student T distribution has thicker tails, and by allocating more probability mass to the tails, outliers have a less strong effect.

Comparing the two distributions,

```
= np.random.normal(loc=0, scale=1, size=100_000)
normal_data = np.random.standard_t(df=1, size=100_000)
t_data
= np.arange(-8,8,0.15)
bins
plt.hist(normal_data, =bins, density=True,
bins=0.6,
alpha="Normal"
label
)
plt.hist(t_data, =bins,density=True,
bins=0.6,
alpha="Student T"
label
)"x")
plt.xlabel("Probability density")
plt.ylabel(-8,8)
plt.xlim(; plt.legend()
```

As we can see, the tails of the Student T are much larger, which means values far from the mean are more likely when compared to the normal distribution.

The T distribution is specified by a number of degrees of freedom (\(\nu\)). In `numpy.random.standard_t`

this is the parameter `df`

, in the pymc T distribution, it’s `nu`

. It is constrained to real numbers greater than 0. As the degrees of freedom increase, the probability in the tails Student T distribution decrease. In the limit of \(\nu \rightarrow + \infty\), the Student T distribution is a normal distribution. Below, the T distribution is plotted for various \(\nu\).

```
= np.arange(-8,8,0.15)
bins for ndof in [0.1, 1, 10]:
= np.random.standard_t(df=ndof, size=100_000)
t_data
plt.hist(t_data, =bins,density=True,
bins=f"$\\nu = {ndof}$",
label="step"
histtype
)
plt.hist(normal_data, =bins, density=True,
bins="step",
histtype="Normal"
label
)
"x")
plt.xlabel("Probability density")
plt.ylabel(-6,6)
plt.xlim(; plt.legend()
```

In Bambi, the way to specify a regression with Student T distributed data is by passing `"t"`

to the `family`

parameter of a Model.

```
= bmb.Model("y ~ x", data, family="t")
t_model = t_model.fit(draws=2000, idata_kwargs={"log_likelihood": True})
t_fitted ="pps") t_model.predict(t_fitted, kind
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [y_sigma, y_nu, Intercept, x]
```

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

` az.summary(t_fitted)`

mean | sd | hdi_3% | hdi_97% | mcse_mean | mcse_sd | ess_bulk | ess_tail | r_hat | |
---|---|---|---|---|---|---|---|---|---|

Intercept | 0.994 | 0.107 | 0.797 | 1.199 | 0.002 | 0.001 | 4029.0 | 3029.0 | 1.0 |

x | 1.900 | 0.184 | 1.562 | 2.254 | 0.003 | 0.002 | 4172.0 | 3105.0 | 1.0 |

y_sigma | 0.405 | 0.046 | 0.321 | 0.492 | 0.001 | 0.001 | 4006.0 | 3248.0 | 1.0 |

y_nu | 2.601 | 0.620 | 1.500 | 3.727 | 0.011 | 0.008 | 3431.0 | 3063.0 | 1.0 |

y_mean[0] | 0.994 | 0.107 | 0.797 | 1.199 | 0.002 | 0.001 | 4029.0 | 3029.0 | 1.0 |

... | ... | ... | ... | ... | ... | ... | ... | ... | ... |

y_mean[98] | 2.875 | 0.103 | 2.688 | 3.079 | 0.001 | 0.001 | 4786.0 | 3228.0 | 1.0 |

y_mean[99] | 2.894 | 0.105 | 2.709 | 3.105 | 0.002 | 0.001 | 4768.0 | 3155.0 | 1.0 |

y_mean[100] | 1.184 | 0.091 | 1.009 | 1.350 | 0.001 | 0.001 | 4046.0 | 3140.0 | 1.0 |

y_mean[101] | 1.279 | 0.084 | 1.118 | 1.432 | 0.001 | 0.001 | 4074.0 | 3151.0 | 1.0 |

y_mean[102] | 1.374 | 0.077 | 1.232 | 1.519 | 0.001 | 0.001 | 4128.0 | 3194.0 | 1.0 |

107 rows × 9 columns

Note the new parameter in the model, `y_nu`

. This is the aforementioned degrees of freedom. If this number were very high, we would expect it to be well described by a normal distribution. However, the HDI of this spans from 1.5 to 3.7, meaning that the tails are much heavier than a normal distribution. As a result of the heavier tails, `y_sigma`

has also dropped precipitously from the normal model, meaning the oversized uncertainty bands from above have shrunk.

Comparing the extracted values of the two models,

```
def get_slope_intercept(mod):
return (
mod.posterior.x.mean().item(),
mod.posterior.Intercept.mean().item()
)= get_slope_intercept(gauss_fitted)
gauss_slope, gauss_int = get_slope_intercept(t_fitted)
t_slope, t_int
pd.DataFrame({"Model":["True","Normal","T"],
"Slope":[2, gauss_slope, t_slope],
"Intercept": [1, gauss_int, t_int]
"Model").T.round(decimals=2) }).set_index(
```

Model | True | Normal | T |
---|---|---|---|

Slope | 2.0 | 1.20 | 1.90 |

Intercept | 1.0 | 1.53 | 0.99 |

Here we can see the mean recovered values of both the slope and intercept are far closer to the true values using the robust regression model compared to the normally distributed one.

Visually comparing the robust regression line,

```
=(7, 5))
plt.figure(figsize# Plot Data
"x", label="data")
plt.plot(x_out, y_out, # Plot recovered robust linear regression
= np.linspace(min(x_out), max(x_out), 2000)
x_range = t_fitted.posterior.x.mean().item() * x_range + t_fitted.posterior.Intercept.mean().item()
y_pred
plt.plot(x_range, y_pred, ="black",linestyle="--",
color="Recovered regression line"
label
)# Plot HDIs
for interval in [0.05, 0.38, 0.68]:
az.plot_hdi(x_out, t_fitted.posterior_predictive.y, =interval, color="firebrick")
hdi_prob# Plot true regression line
plt.plot(x, true_regression_line, ="true regression line", lw=2.0, color="black")
label=0); plt.legend(loc
```

This is much better. The true and recovered regression lines are much closer, and the uncertainty bands are appropriate sized. The effect of the outliers is not *entirely* gone, the recovered line still slightly differs from the true line, but the effect is far smaller, which is a result of the Student T likelihood function ascribing a higher probability to outliers than the normal distribution. Additionally, this inference is based on sampling methods, so it is expected to have small differences (especially given a relatively small number of samples).

Last, another way to evaluate the models is to compare based on Leave-one-out Cross-validation (LOO), which provides an estimate of accuracy on out-of-sample predictions.

```
= {
models "gaussian": gauss_fitted,
"Student T": t_fitted
}= az.compare(models)
df_compare df_compare
```

```
/home/tomas/anaconda3/envs/bambi/lib/python3.10/site-packages/arviz/stats/stats.py:803: UserWarning: Estimated shape parameter of Pareto distribution is greater than 0.7 for one or more samples. You should consider using a more robust model, this is because importance sampling is less likely to work well if the marginal posterior and LOO posterior are very different. This is more likely to happen with a non-robust model and highly influential observations.
warnings.warn(
```

rank | elpd_loo | p_loo | elpd_diff | weight | se | dse | warning | scale | |
---|---|---|---|---|---|---|---|---|---|

Student T | 0 | -101.760564 | 5.603439 | 0.000000 | 1.000000e+00 | 14.994794 | 0.000000 | False | log |

gaussian | 1 | -171.732028 | 14.081743 | 69.971464 | 3.053913e-11 | 29.382970 | 17.542539 | True | log |

`=False); az.plot_compare(df_compare, insample_dev`

Here it is quite obvious that the Student T model is much better, due to having a clearly larger value of LOO.

```
%load_ext watermark
%watermark -n -u -v -iv -w
```

```
Last updated: Thu Jan 05 2023
Python implementation: CPython
Python version : 3.10.4
IPython version : 8.5.0
bambi : 0.9.3
pandas : 1.5.2
numpy : 1.23.5
matplotlib: 3.6.2
sys : 3.10.4 (main, Mar 31 2022, 08:41:55) [GCC 7.5.0]
arviz : 0.14.0
Watermark: 2.3.1
```