# Bivariate normal in Turing

**URL:** <https://discourse.julialang.org/t/bivariate-normal-in-turing/53446>\
**Category:** Probabilistic Programming\
**Created:** [January 16, 2021, 7:31pm UTC](https://discourse.julialang.org/t/bivariate-normal-in-turing/53446 "2021-01-16T19:31:38Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![drbenvincent](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/drbenvincent/32/3046_2.png) [@drbenvincent](https://discourse.julialang.org/u/drbenvincent)\
**Post date:** [January 16, 2021, 9:12pm UTC](https://discourse.julialang.org/t/bivariate-normal-in-turing/53446/5 "2021-01-16T21:12:31Z")

</div>

Turns out I was clumsy. So fixing a mistake in the covariance matrix solves the positive definite problem

```julia
using Turing, StatsPlots #, LinearAlgebra

@model function pearson_correlation(x, ::Type{T}=Float64) where T
    rows = size(x, 1)
    # priors
    μ = Vector{T}(undef, 2)
    μ[1] ~ Normal(0, 100)
    μ[2] ~ Normal(0, 100)
    σ₁ ~ Uniform(0, 100)
    σ₂ ~ Uniform(0, 100)
    r ~ Uniform(-0.99, 0.99)
    # covariance matrix
    Σ = [σ₁*σ₁ r*σ₁*σ₂;
         r*σ₁*σ₂ σ₂*σ₂]
    # if !isposdef(Σ)
    # Turing.@addlogprob! -Inf
    # return 
    # end
    # likelihood
    for i = 1:rows
        x[i,:] ~ MvNormal(μ, Σ)
    end
end

x = [0.8 102; 1 98; 0.5 100; 0.9 105; 0.7 103; 0.4 110; 1.2 99; 1.4 87; 0.6 113; 1.1 89; 1.3 93]

chain = sample(pearson_correlation(x), HMC(0.05, 10), 10000)

plot(layout=(1,2))
scatter!(x[:,1], x[:,2], legend=false, subplot=1, xlabel="Response Time (sec)", ylabel="IQ", title="Data space")
histogram!(chain[:r], subplot=2, bins=[-1:0.02:1;], normalize=:pdf, alpha=0.5, xlabel="Correlation", ylabel="Posterior density", title="Parameter space", legend=false)

```

Overall looks good

 ![Screenshot 2021-01-16 at 21.16.56](https://global.discourse-cdn.com/julialang/original/3X/f/d/fde6253100554ca2e04923dec95265264ce9d82a.png)

EDIT: There were some warmup issues with HMC, but works great with NUTS.

---

_[View the full topic](https://discourse.julialang.org/t/bivariate-normal-in-turing/53446)._
