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.
#Import Turing, Distributions and DataFramesusingTuring, Distributions, DataFrames, Distributed# Import MCMCChain, Plots, and StatsPlots for visualizations and diagnostics.usingMCMCChains, Plots, StatsPlots# Set a seed for reproducibility.usingRandomRandom.seed!(12);
Precompiling Turing...
798.1 ms ? OptimizationBase
1397.7 ms ? Optimization
2129.7 ms ? OptimizationOptimJL
Info Given Turing was explicitly requested, output will be shown live
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
WARNING: Method definition (::Type{OptimizationBase.OptimizerMissingError})(Any) in module OptimizationBase at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:23 overwritten at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:177.
ERROR: Method overwriting is not permitted during Module precompilation. Use `__precompile__(false)` to opt-out of precompilation.
5690.8 ms ? Turing
5849.2 ms ? Turing → TuringOptimExt
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
WARNING: Method definition (::Type{OptimizationBase.OptimizerMissingError})(Any) in module OptimizationBase at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:23 overwritten at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:177.
ERROR: Method overwriting is not permitted during Module precompilation. Use `__precompile__(false)` to opt-out of precompilation.
Precompiling Optimization...
826.3 ms ? OptimizationBaseInfo Given Optimization was explicitly requested, output will be shown live
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
WARNING: Method definition (::Type{OptimizationBase.OptimizerMissingError})(Any) in module OptimizationBase at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:23 overwritten at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:177.
ERROR: Method overwriting is not permitted during Module precompilation. Use `__precompile__(false)` to opt-out of precompilation.
1470.8 ms ? Optimization
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
WARNING: Method definition (::Type{OptimizationBase.OptimizerMissingError})(Any) in module OptimizationBase at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:23 overwritten at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:177.
ERROR: Method overwriting is not permitted during Module precompilation. Use `__precompile__(false)` to opt-out of precompilation.
Precompiling OptimizationBase...
Info Given OptimizationBase was explicitly requested, output will be shown live
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
WARNING: Method definition (::Type{OptimizationBase.OptimizerMissingError})(Any) in module OptimizationBase at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:23 overwritten at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:177.
ERROR: Method overwriting is not permitted during Module precompilation. Use `__precompile__(false)` to opt-out of precompilation.
808.4 ms ? OptimizationBase
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
WARNING: Method definition (::Type{OptimizationBase.OptimizerMissingError})(Any) in module OptimizationBase at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:23 overwritten at /home/runner/.julia/packages/OptimizationBase/sfIfa/src/solve.jl:177.
ERROR: Method overwriting is not permitted during Module precompilation. Use `__precompile__(false)` to opt-out of precompilation.
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
┌ Warning: Replacing docs for `CommonSolve.solve :: Tuple{SciMLBase.OptimizationProblem, Any, Vararg{Any}}` in module `OptimizationBase`
└ @ Base.Docs docs/Docs.jl:243
WARNING: redefinition of constant OptimizationBase.OPTIMIZER_MISSING_ERROR_MESSAGE. This may fail, cause incorrect answers, or produce other errors.
┌ Warning: Replacing docs for `CommonSolve.init :: Tuple{SciMLBase.OptimizationProblem, Any, Vararg{Any}}` in module `OptimizationBase`
└ @ Base.Docs docs/Docs.jl:243┌ Warning: Replacing docs for `CommonSolve.solve! :: Tuple{SciMLBase.AbstractOptimizationCache}` in module `OptimizationBase`
└ @ Base.Docs docs/Docs.jl:243Precompiling OptimizationOptimJL...
801.1 ms ? OptimizationBase
992.1 ms ? Optimization
Info Given OptimizationOptimJL was explicitly requested, output will be shown live
┌ Warning: Module Optimization with build ID ffffffff-ffff-ffff-cf18-fe6d9680b488 is missing from the cache.
│ This may mean Optimization [7f7a1694-90dd-40f0-9382-eb1efda571ba] does not support precompilation but is imported by a module that does.
└ @ Base loading.jl:2541
1138.6 ms ? OptimizationOptimJL
┌ Warning: Module Optimization with build ID ffffffff-ffff-ffff-cf18-fe6d9680b488 is missing from the cache.
│ This may mean Optimization [7f7a1694-90dd-40f0-9382-eb1efda571ba] does not support precompilation but is imported by a module that does.
└ @ Base loading.jl:2541Precompiling TuringOptimExt...
792.4 ms ? OptimizationBase
1003.2 ms ? Optimization
1135.9 ms ? OptimizationOptimJL
3764.0 ms ? Turing
Info Given TuringOptimExt was explicitly requested, output will be shown live
┌ Warning: Module Turing with build ID ffffffff-ffff-ffff-5460-2d185493f461 is missing from the cache.
│ This may mean Turing [fce5fe82-541a-59a6-adf8-730c64b5f9a0] does not support precompilation but is imported by a module that does.
└ @ Base loading.jl:2541
644.8 ms ? Turing → TuringOptimExt
┌ Warning: Module Turing with build ID ffffffff-ffff-ffff-5460-2d185493f461 is missing from the cache.
│ This may mean Turing [fce5fe82-541a-59a6-adf8-730c64b5f9a0] does not support precompilation but is imported by a module that does.
└ @ Base loading.jl:2541
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.
theta_noalcohol_meds =1# no alcohol, took medicinetheta_alcohol_meds =3# alcohol, took medicinetheta_noalcohol_nomeds =6# no alcohol, no medicinetheta_alcohol_nomeds =36# alcohol, no medicine# no of samples for each of the above casesq =100#Generate data from different Poisson distributionsnoalcohol_meds =Poisson(theta_noalcohol_meds)alcohol_meds =Poisson(theta_alcohol_meds)noalcohol_nomeds =Poisson(theta_noalcohol_nomeds)alcohol_nomeds =Poisson(theta_alcohol_nomeds)nsneeze_data =vcat(rand(noalcohol_meds, q),rand(alcohol_meds, q),rand(noalcohol_nomeds, q),rand(alcohol_nomeds, q),)alcohol_data =vcat(zeros(q), ones(q), zeros(q), ones(q))meds_data =vcat(zeros(q), zeros(q), ones(q), ones(q))df =DataFrame(; nsneeze=nsneeze_data, alcohol_taken=alcohol_data, nomeds_taken=meds_data, product_alcohol_meds=meds_data .* alcohol_data,)df[sample(1:nrow(df), 5; replace=false), :]
5×4 DataFrame
Row
nsneeze
alcohol_taken
nomeds_taken
product_alcohol_meds
Int64
Float64
Float64
Float64
1
2
1.0
0.0
0.0
2
1
0.0
0.0
0.0
3
2
0.0
0.0
0.0
4
30
1.0
1.0
1.0
5
0
1.0
0.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.
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.data =Matrix(df[:, [:alcohol_taken, :nomeds_taken, :product_alcohol_meds]])data_labels = df[:, :nsneeze]data
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:
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].
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.n, _ =size(data)# Sample using NUTS.num_chains =4m =poisson_regression(data, data_labels, n, 10)chain =sample(m, NUTS(), MCMCThreads(), 2_500, num_chains; discard_adapt=false, progress=false)
Chains MCMC chain (2500×18×4 Array{Float64, 3}):
Iterations = 1:1:2500
Number of chains = 4
Samples per chain = 2500
Wall duration = 23.48 seconds
Compute duration = 19.5 seconds
parameters = b0, b1, b2, b3
internals = 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, lp, logprior, loglikelihood
Use `describe(chains)` for summary statistics and quantiles.
WarningSampling With Multiple Threads
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.
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 chainc1 = chain[:, :, 1]# Calculating the exponentiated meansb0_exp =exp(mean(c1[:b0]))b1_exp =exp(mean(c1[:b1]))b2_exp =exp(mean(c1[:b2]))b3_exp =exp(mean(c1[:b3]))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: 4.974790086171622
b1: 2.039663574957162
b2: 3.03621474143374
b3: 1.1795785224047115
The posterior distributions obtained after sampling can be visualised as :
Visualising the posterior by plotting it:
plot(chain)
Interpreting the Obtained Mean Values
The exponentiated mean of the coefficient b1 is roughly half of that of b2. This makes sense because in the data that we generated, the number of sneezes was more sensitive to the medicinal intake as compared to the alcohol consumption. We also get a weaker dependence on the interaction between the alcohol consumption and the medicinal intake as can be seen from the value of b3.
Removing the Warmup Samples
As can be seen from the plots above, the parameters converge to their final distributions after a few iterations. The initial values during the warmup phase increase the standard deviations of the parameters and are not required after we get the desired distributions. Thus, we remove these warmup values and once again view the diagnostics. To remove these warmup values, we take all values except the first 200. This is because we set the second parameter of the NUTS sampler (which is the number of adaptations) to be equal to 200.
chains_new = chain[201:end, :, :]
Chains MCMC chain (2300×18×4 Array{Float64, 3}):
Iterations = 201:1:2500
Number of chains = 4
Samples per chain = 2300
Wall duration = 23.48 seconds
Compute duration = 19.5 seconds
parameters = b0, b1, b2, b3
internals = 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, lp, logprior, loglikelihood
Use `describe(chains)` for summary statistics and quantiles.
plot(chains_new)
As can be seen from the numeric values and the plots above, the standard deviation values have decreased and all the plotted values are from the estimated posteriors. The exponentiated mean values, with the warmup samples removed, have not changed by much and they are still in accordance with their intuitive meanings as described earlier.