using CSV, DataFrames
= CSV.read("golf.dat", DataFrame; delim=' ', ignorerepeated=true)
df 1:5, :] df[
Row | distance | n | y |
---|---|---|---|
Int64 | Int64 | Int64 | |
1 | 2 | 1443 | 1346 |
2 | 3 | 694 | 577 |
3 | 4 | 455 | 337 |
4 | 5 | 353 | 208 |
5 | 6 | 272 | 149 |
JuliaGPs packages integrate well with Turing.jl because they implement the Distributions.jl interface. You should be able to understand what is going on in this tutorial if you know what a GP is. For a more in-depth understanding of the JuliaGPs functionality used here, please consult the JuliaGPs docs.
In this tutorial, we will model the putting dataset discussed in Chapter 21 of Bayesian Data Analysis. The dataset comprises the result of measuring how often a golfer successfully gets the ball in the hole, depending on how far away from it they are. The goal of inference is to estimate the probability of any given shot being successful at a given distance.
using CSV, DataFrames
df = CSV.read("golf.dat", DataFrame; delim=' ', ignorerepeated=true)
df[1:5, :]
Row | distance | n | y |
---|---|---|---|
Int64 | Int64 | Int64 | |
1 | 2 | 1443 | 1346 |
2 | 3 | 694 | 577 |
3 | 4 | 455 | 337 |
4 | 5 | 353 | 208 |
5 | 6 | 272 | 149 |
We’ve printed the first 5 rows of the dataset (which comprises only 19 rows in total). Observe it has three columns:
distance
– how far away from the hole. I’ll refer to distance
as d
throughout the rest of this tutorialn
– how many shots were taken from a given distancey
– how many shots were successful from a given distanceWe will use a Binomial model for the data, whose success probability is parametrised by a transformation of a GP. Something along the lines of: \[ \begin{aligned} f & \sim \operatorname{GP}(0, k) \\ y_j \mid f(d_j) & \sim \operatorname{Binomial}(n_j, g(f(d_j))) \\ g(x) & := \frac{1}{1 + e^{-x}} \end{aligned} \]
To do this, let’s define our Turing.jl model:
using AbstractGPs, LogExpFunctions, Turing
@model function putting_model(d, n; jitter=1e-4)
v ~ Gamma(2, 1)
l ~ Gamma(4, 1)
f = GP(v * with_lengthscale(SEKernel(), l))
f_latent ~ f(d, jitter)
y ~ product_distribution(Binomial.(n, logistic.(f_latent)))
return (fx=f(d, jitter), f_latent=f_latent, y=y)
end
putting_model (generic function with 2 methods)
We first define an AbstractGPs.GP
, which represents a distribution over functions, and is entirely separate from Turing.jl. We place a prior over its variance v
and length-scale l
. f(d, jitter)
constructs the multivariate Gaussian comprising the random variables in f
whose indices are in d
(plus a bit of independent Gaussian noise with variance jitter
– see the docs for more details). f(d, jitter)
has the type AbstractMvNormal
, and is the bit of AbstractGPs.jl that implements the Distributions.jl interface, so it’s legal to put it on the right-hand side of a ~
. From this you should deduce that f_latent
is distributed according to a multivariate Gaussian. The remaining lines comprise standard Turing.jl code that is encountered in other tutorials and Turing documentation.
Before performing inference, we might want to inspect the prior that our model places over the data, to see whether there is anything obviously wrong. These kinds of prior predictive checks are straightforward to perform using Turing.jl, since it is possible to sample from the prior easily by just calling the model:
19-element Vector{Int64}:
594
270
154
103
70
49
39
21
14
20
24
31
50
54
103
112
106
74
70
We make use of this to see what kinds of datasets we simulate from the prior:
using Plots
function plot_data(d, n, y, xticks, yticks)
ylims = (0, round(maximum(n), RoundUp; sigdigits=2))
margin = -0.5 * Plots.mm
plt = plot(; xticks=xticks, yticks=yticks, ylims=ylims, margin=margin, grid=false)
bar!(plt, d, n; color=:red, label="", alpha=0.5)
bar!(plt, d, y; label="", color=:blue, alpha=0.7)
return plt
end
# Construct model and run some prior predictive checks.
m = putting_model(Float64.(df.distance), df.n)
hists = map(1:20) do j
xticks = j > 15 ? :auto : nothing
yticks = rem(j, 5) == 1 ? :auto : nothing
return plot_data(df.distance, df.n, m().y, xticks, yticks)
end
plot(hists...; layout=(4, 5))
In this case, the only prior knowledge I have is that the proportion of successful shots ought to decrease monotonically as the distance from the hole increases, which should show up in the data as the blue lines generally go down as we move from left to right on each graph. Unfortunately, there is not a simple way to enforce monotonicity in the samples from a GP, and we can see this in some of the plots above, so we must hope that we have enough data to ensure that this relationship holds approximately under the posterior. In any case, you can judge for yourself whether you think this is the most useful visualisation that we can perform – if you think there is something better to look at, please let us know!
Moving on, we generate samples from the posterior using the default NUTS
sampler. We’ll make use of ReverseDiff.jl, as it has better performance than ForwardDiff.jl on this example. See Turing.jl’s docs on Automatic Differentiation for more info.
using Random, ReverseDiff
m_post = m | (y=df.y,)
chn = sample(Xoshiro(123456), m_post, NUTS(; adtype=AutoReverseDiff()), 1_000, progress=false)
┌ Info: Found initial step size
└ ϵ = 0.2
Chains MCMC chain (1000×33×1 Array{Float64, 3}):
Iterations = 501:1:1500
Number of chains = 1
Samples per chain = 1000
Wall duration = 147.92 seconds
Compute duration = 147.92 seconds
parameters = v, l, f_latent[1], f_latent[2], f_latent[3], f_latent[4], f_latent[5], f_latent[6], f_latent[7], f_latent[8], f_latent[9], f_latent[10], f_latent[11], f_latent[12], f_latent[13], f_latent[14], f_latent[15], f_latent[16], f_latent[17], f_latent[18], f_latent[19]
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 ⋯
Symbol Float64 Float64 Float64 Float64 Float64 Float64 ⋯
v 2.8019 1.2781 0.0604 447.1359 695.8370 0.9999 ⋯
l 3.5776 0.9968 0.0975 99.0035 104.5329 1.0025 ⋯
f_latent[1] 2.5443 0.1044 0.0038 759.1492 580.5865 0.9994 ⋯
f_latent[2] 1.7056 0.0746 0.0024 978.9541 584.5681 0.9996 ⋯
f_latent[3] 0.9769 0.0866 0.0050 296.1646 356.9508 1.0025 ⋯
f_latent[4] 0.4787 0.0801 0.0043 348.8566 647.5708 1.0003 ⋯
f_latent[5] 0.1949 0.0769 0.0026 886.3665 726.8519 1.0003 ⋯
f_latent[6] -0.0085 0.0995 0.0067 226.0623 424.0574 1.0005 ⋯
f_latent[7] -0.2471 0.0840 0.0035 562.4772 570.8933 1.0078 ⋯
f_latent[8] -0.5136 0.0921 0.0046 470.3300 336.7384 1.0073 ⋯
f_latent[9] -0.7265 0.1052 0.0056 386.3241 403.0347 1.0054 ⋯
f_latent[10] -0.8624 0.0989 0.0040 621.3075 598.6442 1.0053 ⋯
f_latent[11] -0.9501 0.0949 0.0031 991.0415 582.7107 1.0004 ⋯
f_latent[12] -1.0407 0.1094 0.0048 516.4460 326.2720 0.9998 ⋯
f_latent[13] -1.1915 0.1211 0.0060 412.8273 382.3954 1.0004 ⋯
f_latent[14] -1.4158 0.1179 0.0043 749.2159 602.7765 1.0005 ⋯
f_latent[15] -1.6236 0.1210 0.0067 361.9174 367.8756 1.0010 ⋯
⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱
1 column and 4 rows omitted
Quantiles
parameters 2.5% 25.0% 50.0% 75.0% 97.5%
Symbol Float64 Float64 Float64 Float64 Float64
v 1.1006 1.8502 2.5868 3.5028 5.9022
l 1.9488 2.9584 3.3903 4.0312 6.1431
f_latent[1] 2.3442 2.4750 2.5412 2.6113 2.7543
f_latent[2] 1.5614 1.6566 1.7076 1.7549 1.8505
f_latent[3] 0.8022 0.9188 0.9770 1.0375 1.1456
f_latent[4] 0.3165 0.4253 0.4790 0.5323 0.6334
f_latent[5] 0.0505 0.1442 0.1939 0.2438 0.3491
f_latent[6] -0.1944 -0.0762 -0.0138 0.0593 0.1860
f_latent[7] -0.4010 -0.3060 -0.2498 -0.1930 -0.0765
f_latent[8] -0.7105 -0.5716 -0.5058 -0.4509 -0.3537
f_latent[9] -0.9519 -0.7975 -0.7173 -0.6467 -0.5409
f_latent[10] -1.0627 -0.9294 -0.8638 -0.7926 -0.6789
f_latent[11] -1.1261 -1.0213 -0.9486 -0.8875 -0.7594
f_latent[12] -1.2554 -1.1134 -1.0396 -0.9683 -0.8256
f_latent[13] -1.4260 -1.2797 -1.1950 -1.1095 -0.9385
f_latent[14] -1.6462 -1.4917 -1.4186 -1.3336 -1.1888
f_latent[15] -1.8718 -1.7031 -1.6169 -1.5314 -1.4072
⋮ ⋮ ⋮ ⋮ ⋮ ⋮
4 rows omitted
We can use these samples and the posterior
function from AbstractGPs
to sample from the posterior probability of success at any distance we choose:
d_pred = 1:0.2:21
samples = map(generated_quantities(m_post, chn)[1:10:end]) do x
return logistic.(rand(posterior(x.fx, x.f_latent)(d_pred, 1e-4)))
end
p = plot()
plot!(d_pred, reduce(hcat, samples); label="", color=:blue, alpha=0.2)
scatter!(df.distance, df.y ./ df.n; label="", color=:red)
We can see that the general trend is indeed down as the distance from the hole increases, and that if we move away from the data, the posterior uncertainty quickly inflates. This suggests that the model is probably going to do a reasonable job of interpolating between observed data, but less good a job at extrapolating to larger distances.