Asymmetric MCMC
xxxxxxxxxx1
1
using Plots, Distributions, LinearAlgebra,Random,LaTeXStrings,StatsBase,DataFramesxxxxxxxxxx5
1
begin2
using REPL3
REPL.REPLCompletions.latex_symbols["\\_y"] = "ᵧ"4
nothing5
endModel parameter : θ = [α,β]
Data : y
Prior : p(θ)
Likelihood : p(y|θ) = Gamma(y;α,β)
Posterior : p(θ|y) = p(y|θ)p(θ) / p(y)
Gamma(y;α,β) = βᵅ yᵅ⁻¹e⁻ᵝʸ / Γ(α)
Gamma(y;α,β) = pdf(Gamma(α,β),y) : Julia
Likelihood : p(y|α,β=1) = p_y_α(y,α,β)
p_y_α (generic function with 1 method)xxxxxxxxxx1
1
p_y_α(y,α,β) = pdf(Gamma(α,β),y)초기값 및 상수설정
5xxxxxxxxxx18
1
begin2
Random.seed!(0)3
n=504
α = LinRange(0.1,5,n)5
Δα = (α[end] - α[1])/(n-1)6
#주어진 값에 가장 가까운 α 의 index구하기7
Iₐ(x) = Int(ceil(x/Δα))8
αₖ = 29
αᵢ = repeat([ α[Iₐ(αₖ)] ],n)10
β = 111
y = LinRange(0,10,n)12
Δy = (y[end] - y[1])/(n-1)13
#주어진 값에 가장 가까운 y 의 index구하기14
Iᵧ(x) = Int(ceil(x/Δy))15
yₖ = 1.516
yᵢ = repeat([ y[Iᵧ(yₖ)] ],n) 17
μ = 518
endLikelihood 그래프 (β=1)
| α | y | p | |
|---|---|---|---|
| Float64 | Float64 | Float64 | |
| 1 | 0.1 | 0.0 | Inf |
| 2 | 0.1 | 0.204082 | 0.358265 |
| 3 | 0.1 | 0.408163 | 0.156547 |
| 4 | 0.1 | 0.612245 | 0.0886201 |
| 5 | 0.1 | 0.816327 | 0.0557771 |
xxxxxxxxxx5
1
begin2
Dₚ = DataFrame(α=repeat(α, inner=length(α)), y=repeat(y,outer=length(y)))3
Dₚ.p = p_y_α.(Dₚ.y,Dₚ.α,β)4
first(Dₚ,5)5
endxxxxxxxxxx7
1
begin 2
plot(Dₚ.α,Dₚ.y,Dₚ.p,st=:surface,fc=:heat,3
xlabel="α",ylabel="y",zlabel="p(y|α,β=1)",camera=(40,70),4
title="Likelihood Gamma distribution, β=1 surface") 5
plot!(αᵢ,y,[p_y_α(yᵢ,αₖ,β) for yᵢ in y ],linewidth=3,linecolor=:red,6
label="p(y|α=2,β=1)") 7
end모델 파라미터 θ = [α,β]에 대한 사전확률분포(prior)를 다음과 같이 가정한다.
P(β=1) = 1
p(α) = sin(π×α)²
두 모델 파라미터의 사전확률분포는 적분값이 1이 아니기 때문에 부적절한 사전확률분포(improper priors)라고 한다.
p(α|y) = p(y|α)p(α)/p(y) 식에서 normalization constant p(y)는 계산이 어려울 수 있어나 p(y)에 대해 알지 못해도 Metropolis-Hastings 알고리즘을 사용하여 사후확률분포 p(α|y)에서 α를 샘플링 할 수 있다.
특히 정규화 상수 p(y)를 무시하고 비정규화된 사후확률분포(posterior)에서 α를 샘플링 할 수 있다.
p(α|y) ∝ p(y|α)p(α) = Gamma(y;α,β)×sin(π×α)² = pdf(Gamma(α,β),x)×sin(π×α)²
Posterior : p(α,β=1|y) = p_α_y(y,α,β) = p_y_α(y,α,β) * p_α(α)
p_α_y (generic function with 1 method)xxxxxxxxxx4
1
begin2
p_α(α) = sin(π*α)^23
p_α_y(y,α,β) = p_y_α(y,α,β)*p_α(α)4
endPosterior Surface
| α | y | p | |
|---|---|---|---|
| Float64 | Float64 | Float64 | |
| 1 | 0.1 | 0.0 | Inf |
| 2 | 0.1 | 0.204082 | 0.0342113 |
| 3 | 0.1 | 0.408163 | 0.0149489 |
| 4 | 0.1 | 0.612245 | 0.00846246 |
| 5 | 0.1 | 0.816327 | 0.00532624 |
xxxxxxxxxx5
1
begin2
D = DataFrame(α=repeat(α, inner=length(α)), y=repeat(y,outer=length(y)))3
D.p = p_α_y.(D.y,D.α,β)4
first(D,5)5
endxxxxxxxxxx16
1
begin2
plot(D.α,D.y,D.p,st=:surface,fc=:heat,xlabel="α",ylabel="y",zlabel="p(α,β=$β|y)",3
camera=(30,70),4
title="Posterior distribution") 5
# reshape α,y 순서 중요함,row,column개념으로 p 데이터가 생성 되었음6
# Iᵧ(yₖ) : yₖ에 가장 가까운 y의 index를 가져옴7
iᵧ = Iᵧ(yₖ)8
# the column-major iteration order 9
# julia는 reshape시에 column을 우선시 해서 row를 채우고 다음 column으로 넘어간다.10
# 예) p₁₁,p₁₂,p₁₃,p₂₁,p₂₂11
pᵧₖ = reshape(D.p,(length(y),length(α)))[iᵧ,:]12
plot!(α,yᵢ,pᵧₖ,linewidth=3,linecolor=:red,13
label="p(α,β=$β|y=$yₖ)") 14
plot!(α,repeat([y[end]],n),[p_α(αᵢ) for αᵢ in α ],linewidth=3,linecolor=:blue,15
label="p(α,β=$β)") 16
endAsymmetric Proposal Distribution
f(y;μ) = q(y,μ) = pdf(Exponential(μ),y)
q (generic function with 1 method)xxxxxxxxxx1
1
q(y,μ) = pdf(Exponential(μ),y)xxxxxxxxxx6
1
begin2
plot(α,α->p_α_y(yₖ,α,β),linecolor=:blue,linewidth=3,3
label="Target, p(α,β=$β|y=$yₖ)")4
plot!(α,y->q(y,μ),linewidth=3,linecolor=:red,5
label="Proposal, q(α,$μ)")6
endRun Metropolis-Hastings Sampler
x = α 를 샘플링 한다.
β = 1
yₖ = 1.5
μ = 5
1xxxxxxxxxx11
1
begin2
# Samples3
Nₛ = 50004
n_burn = 5005
min_α = α[1]6
max_α = α[end]7
#Initialize sampler8
αₛ = zeros(Nₛ)9
αₛ[1] = μ10
t = 111
endxxxxxxxxxx22
1
while t < Nₛ2
t = t+13
#sample from proposal4
#제안 분포로 부터 α를 뽑는다5
# α\asteraccent => α⃰6
α⃰=rand(Exponential(μ))7
8
# Correction factor α9
c = q(αₛ[t-1],μ)/q(α⃰,μ)10
11
# Calculate the (correcte) Acceptance Ratio12
#α → α⃰ 로 전이하는 것을 받아 들이는 비율13
A = min(1,p_α_y(yₖ,α⃰,β)/p_α_y(yₖ,αₛ[t-1],β) * c)14
15
#Accept or reject?16
u = rand(Uniform(0,1))17
if u < A18
αₛ[t] = α⃰19
else20
αₛ[t] = αₛ[t-1]21
end22
endxxxxxxxxxx18
1
begin2
p1=plot(αₛ,1:Nₛ,linetype=:step,yflip=true,xlim=(min_α,max_α),3
label="α samples",xlabel="Samples, α",ylabel="t",4
title="Markov Chain Path",titlefontsize=10)5
plot!(α,α->n_burn,linewidth=2,linestyle=:dash,linecolor=:red,6
label="Burnin")7
8
h = fit(Histogram, αₛ[n_burn:end],α)9
p2=plot(h.edges,h.weights./sum(h.weights),st=:bar,linewidth=0.1,10
xlim=(min_α,max_α),11
title="Samples",titlefontsize=10,xlabel="Samples, α",12
label="Sampled Distribution",legendfontsize=6,13
ylabel="p(α,β=$β|y=$yₖ)")14
plot!(α,pᵧₖ./sum(pᵧₖ),linewidth=2,15
label="Target Posterior") 16
17
plot(p1,p2,layout=(2,1))18
end