-
Notifications
You must be signed in to change notification settings - Fork 7
/
fit-blackjax-nuts.py
executable file
·116 lines (89 loc) · 2.44 KB
/
fit-blackjax-nuts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python3
# fit-blackjax-nuts.py
# Fit using NUTS from BlackJAX
import os
import pandas as pd
import numpy as np
import scipy as sp
import scipy.stats
from scipy.optimize import minimize
import jax
from jax import grad, jit
import jax.numpy as jnp
import jax.scipy as jsp
import blackjax
df = pd.read_parquet(os.path.join("..", "pima.parquet"))
print(df)
n, p = df.shape
print(n, p)
y = pd.get_dummies(df["type"])["Yes"].to_numpy(dtype='float32')
X = df.drop(columns="type").to_numpy()
X = np.hstack((np.ones((n,1)), X))
print(X)
print(y)
# Now do computations in JAX
X = X.astype(jnp.float32)
y = y.astype(jnp.float32)
@jit
def ll(beta):
return jnp.sum(-jnp.log(1 + jnp.exp(-(2*y - 1)*jnp.dot(X, beta))))
np.random.seed(41) # for reproducibility
init = np.random.randn(p)*0.1
print(init)
init = init.astype(jnp.float32)
print(ll(init))
print("MAP:")
@jit
def lprior(beta):
return (jsp.stats.norm.logpdf(beta[0], loc=0, scale=10) +
jnp.sum(jsp.stats.norm.logpdf(beta[jnp.array(range(1,p))], loc=0, scale=1)))
@jit
def lpost(beta):
return ll(beta) + lprior(beta)
print(lpost(init))
# Use JAX auto-diff to compute gradient and Hessian
glp = jit(grad(lpost))
print(glp(init))
from jax import jacfwd, jacrev
def hessian(f):
return jacfwd(jacrev(f))
hess = hessian(lpost)
beta = init
# Newton method (log reg is convex)
for i in range(500):
g = glp(beta)
step = -jsp.linalg.solve(hess(beta), g)
for j in range(15):
if (lpost(beta+step) > lpost(beta)):
break
else:
step = step/2
beta += step
if (jnp.linalg.norm(g) < 0.01):
break
print(beta)
print(ll(beta))
print(jnp.linalg.norm(glp(beta)))
print("Next, NUTS. Be patient...")
def mcmc(init, kernel, iters = 10000):
key = jax.random.PRNGKey(42)
keys = jax.random.split(key, iters)
@jit
def step(s, k):
s, _ = kernel(k, s)
return s, s
_, states = jax.lax.scan(step, init, keys)
return states[0]
pre = jnp.array([10.,1.,1.,1.,1.,1.,5.,1.]).astype(jnp.float32)
samp = blackjax.nuts(lpost, 1e-3, pre)
bjInit = samp.init(beta)
out = mcmc(bjInit, jit(samp.step))
print(out)
odf = pd.DataFrame(np.asarray(out), columns=["b0","b1","b2","b3","b4","b5","b6","b7"])
odf.to_parquet("fit-blackjax-nuts.parquet")
print("Posterior summaries:")
summ = scipy.stats.describe(out)
print(summ)
print("\nMean: " + str(summ.mean))
print("Variance: " + str(summ.variance))
# eof