```
#Import Turing, Distributions and DataFrames
using Turing, Distributions, DataFrames, Distributed
# Import MCMCChain, Plots, and StatsPlots for visualizations and diagnostics.
using MCMCChains, Plots, StatsPlots
# Set a seed for reproducibility.
using Random
Random.seed!(12);
```

# Bayesian Poisson Regression

This notebook is ported from the example notebook of PyMC3 on Poisson Regression.

Poisson Regression is a technique commonly used to model count data. Some of the applications include predicting the number of people defaulting on their loans or the number of cars running on a highway on a given day. This example describes a method to implement the Bayesian version of this technique using Turing.

We will generate the dataset that we will be working on which describes the relationship between number of times a person sneezes during the day with his alcohol consumption and medicinal intake.

We start by importing the required libraries.

# Generating data

We start off by creating a toy dataset. We take the case of a person who takes medicine to prevent excessive sneezing. Alcohol consumption increases the rate of sneezing for that person. Thus, the two factors affecting the number of sneezes in a given day are alcohol consumption and whether the person has taken his medicine. Both these variable are taken as boolean valued while the number of sneezes will be a count valued variable. We also take into consideration that the interaction between the two boolean variables will affect the number of sneezes

5 random rows are printed from the generated data to get a gist of the data generated.

```
= 1 # no alcohol, took medicine
theta_noalcohol_meds = 3 # alcohol, took medicine
theta_alcohol_meds = 6 # no alcohol, no medicine
theta_noalcohol_nomeds = 36 # alcohol, no medicine
theta_alcohol_nomeds
# no of samples for each of the above cases
= 100
q
#Generate data from different Poisson distributions
= Poisson(theta_noalcohol_meds)
noalcohol_meds = Poisson(theta_alcohol_meds)
alcohol_meds = Poisson(theta_noalcohol_nomeds)
noalcohol_nomeds = Poisson(theta_alcohol_nomeds)
alcohol_nomeds
= vcat(
nsneeze_data rand(noalcohol_meds, q),
rand(alcohol_meds, q),
rand(noalcohol_nomeds, q),
rand(alcohol_nomeds, q),
)= vcat(zeros(q), ones(q), zeros(q), ones(q))
alcohol_data = vcat(zeros(q), zeros(q), ones(q), ones(q))
meds_data
= DataFrame(;
df =nsneeze_data,
nsneeze=alcohol_data,
alcohol_taken=meds_data,
nomeds_taken=meds_data .* alcohol_data,
product_alcohol_meds
)sample(1:nrow(df), 5; replace=false), :] df[
```

Row | nsneeze | alcohol_taken | nomeds_taken | product_alcohol_meds |
---|---|---|---|---|

Int64 | Float64 | Float64 | Float64 | |

1 | 1 | 0.0 | 0.0 | 0.0 |

2 | 1 | 0.0 | 0.0 | 0.0 |

3 | 5 | 1.0 | 0.0 | 0.0 |

4 | 35 | 1.0 | 1.0 | 1.0 |

5 | 6 | 0.0 | 1.0 | 0.0 |

# Visualisation of the dataset

We plot the distribution of the number of sneezes for the 4 different cases taken above. As expected, the person sneezes the most when he has taken alcohol and not taken his medicine. He sneezes the least when he doesn’t consume alcohol and takes his medicine.

```
# Data Plotting
= Plots.histogram(
p1 :, :alcohol_taken] .== 0) .& (df[:, :nomeds_taken] .== 0), 1];
df[(df[="no_alcohol+meds",
title
)= Plots.histogram(
p2 :, :alcohol_taken] .== 1) .& (df[:, :nomeds_taken] .== 0), 1]);
(df[(df[="alcohol+meds",
title
)= Plots.histogram(
p3 :, :alcohol_taken] .== 0) .& (df[:, :nomeds_taken] .== 1), 1]);
(df[(df[="no_alcohol+no_meds",
title
)= Plots.histogram(
p4 :, :alcohol_taken] .== 1) .& (df[:, :nomeds_taken] .== 1), 1]);
(df[(df[="alcohol+no_meds",
title
)plot(p1, p2, p3, p4; layout=(2, 2), legend=false)
```

We must convert our `DataFrame`

data into the `Matrix`

form as the manipulations that we are about are designed to work with `Matrix`

data. We also separate the features from the labels which will be later used by the Turing sampler to generate samples from the posterior.

```
# Convert the DataFrame object to matrices.
= Matrix(df[:, [:alcohol_taken, :nomeds_taken, :product_alcohol_meds]])
data = df[:, :nsneeze]
data_labels data
```

```
400×3 Matrix{Float64}:
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
⋮
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
```

We must recenter our data about 0 to help the Turing sampler in initialising the parameter estimates. So, normalising the data in each column by subtracting the mean and dividing by the standard deviation:

```
# Rescale our matrices.
= (data .- mean(data; dims=1)) ./ std(data; dims=1) data
```

```
400×3 Matrix{Float64}:
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
-0.998749 -0.998749 -0.576628
⋮
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
0.998749 0.998749 1.72988
```

# Declaring the Model: Poisson Regression

Our model, `poisson_regression`

takes four arguments:

`x`

is our set of independent variables;`y`

is the element we want to predict;`n`

is the number of observations we have; and`σ²`

is the standard deviation we want to assume for our priors.

Within the model, we create four coefficients (`b0`

, `b1`

, `b2`

, and `b3`

) and assign a prior of normally distributed with means of zero and standard deviations of `σ²`

. We want to find values of these four coefficients to predict any given `y`

.

Intuitively, we can think of the coefficients as:

`b1`

is the coefficient which represents the effect of taking alcohol on the number of sneezes;`b2`

is the coefficient which represents the effect of taking in no medicines on the number of sneezes;`b3`

is the coefficient which represents the effect of interaction between taking alcohol and no medicine on the number of sneezes;

The `for`

block creates a variable `theta`

which is the weighted combination of the input features. We have defined the priors on these weights above. We then observe the likelihood of calculating `theta`

given the actual label, `y[i]`

.

```
# Bayesian poisson regression (LR)
@model function poisson_regression(x, y, n, σ²)
~ Normal(0, σ²)
b0 ~ Normal(0, σ²)
b1 ~ Normal(0, σ²)
b2 ~ Normal(0, σ²)
b3 for i in 1:n
= b0 + b1 * x[i, 1] + b2 * x[i, 2] + b3 * x[i, 3]
theta ~ Poisson(exp(theta))
y[i] end
end;
```

# Sampling from the posterior

We use the `NUTS`

sampler to sample values from the posterior. We run multiple chains using the `MCMCThreads()`

function to nullify the effect of a problematic chain. We then use the Gelman, Rubin, and Brooks Diagnostic to check the convergence of these multiple chains.

```
# Retrieve the number of observations.
= size(data)
n, _
# Sample using NUTS.
= 4
num_chains = poisson_regression(data, data_labels, n, 10)
m = sample(m, NUTS(), MCMCThreads(), 2_500, num_chains; discard_adapt=false, progress=false) chain
```

Chains MCMC chain (2500×16×4 Array{Float64, 3}): Iterations = 1:1:2500 Number of chains = 4 Samples per chain = 2500 Wall duration = 17.36 seconds Compute duration = 15.03 seconds parameters = b0, b1, b2, b3 internals = lp, n_steps, is_accept, acceptance_rate, log_density, hamiltonian_energy, hamiltonian_energy_error, max_hamiltonian_energy_error, tree_depth, numerical_error, step_size, nom_step_size Summary Statistics parameters mean std mcse ess_bulk ess_tail rhat e ⋯ Symbol Float64 Float64 Float64 Float64 Float64 Float64 ⋯ b0 1.5914 0.6391 0.0540 617.5024 181.5894 1.0076 ⋯ b1 0.6565 1.1365 0.1214 485.8614 162.7494 1.0113 ⋯ b2 1.0382 1.0238 0.1143 493.4301 168.6433 1.0108 ⋯ b3 0.2059 0.9259 0.1028 512.0198 168.6931 1.0110 ⋯ 1 column omitted Quantiles parameters 2.5% 25.0% 50.0% 75.0% 97.5% Symbol Float64 Float64 Float64 Float64 Float64 b0 1.5391 1.6051 1.6273 1.6480 1.6912 b1 0.4066 0.4809 0.5212 0.5620 0.7226 b2 0.7906 0.8615 0.8983 0.9358 1.0931 b3 0.1294 0.2914 0.3296 0.3664 0.4367

The `sample()`

call above assumes that you have at least `nchains`

threads available in your Julia instance. If you do not, the multiple chains will run sequentially, and you may notice a warning. For more information, see the Turing documentation on sampling multiple chains.

# Viewing the Diagnostics

We use the Gelman, Rubin, and Brooks Diagnostic to check whether our chains have converged. Note that we require multiple chains to use this diagnostic which analyses the difference between these multiple chains.

We expect the chains to have converged. This is because we have taken sufficient number of iterations (1500) for the NUTS sampler. However, in case the test fails, then we will have to take a larger number of iterations, resulting in longer computation time.

`gelmandiag(chain)`

Gelman, Rubin, and Brooks diagnostic parameters psrf psrfci Symbol Float64 Float64 b0 1.0524 1.0955 b1 1.1261 1.2190 b2 1.1664 1.2992 b3 1.1620 1.2907

From the above diagnostic, we can conclude that the chains have converged because the PSRF values of the coefficients are close to 1.

So, we have obtained the posterior distributions of the parameters. We transform the coefficients and recover theta values by taking the exponent of the meaned values of the coefficients `b0`

, `b1`

, `b2`

and `b3`

. We take the exponent of the means to get a better comparison of the relative values of the coefficients. We then compare this with the intuitive meaning that was described earlier.

```
# Taking the first chain
= chain[:, :, 1]
c1
# Calculating the exponentiated means
= exp(mean(c1[:b0]))
b0_exp = exp(mean(c1[:b1]))
b1_exp = exp(mean(c1[:b2]))
b2_exp = exp(mean(c1[:b3]))
b3_exp
print("The exponent of the meaned values of the weights (or coefficients are): \n")
println("b0: ", b0_exp)
println("b1: ", b1_exp)
println("b2: ", b2_exp)
println("b3: ", b3_exp)
print("The posterior distributions obtained after sampling can be visualised as :\n")
```

```
The exponent of the meaned values of the weights (or coefficients are):
b0: 5.415721701210463
b1: 1.5858918967107365
b2: 2.411973958121643
b3: 1.4145978418198353
The posterior distributions obtained after sampling can be visualised as :
```

Visualising the posterior by plotting it:

`plot(chain)`