forked from kiat/BigDataAnalytics
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathisland2.py
More file actions
48 lines (39 loc) · 1.25 KB
/
island2.py
File metadata and controls
48 lines (39 loc) · 1.25 KB
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
# http://people.duke.edu/~ccc14/sta-663-2016/16A_MCMC.html
import numpy as np
import seaborn as sns
def make_islands(n, low=10, high=101):
islands = np.random.randint(low, high, n+2)
islands[0] = 0
islands[-1] = 0
return islands
def hop(islands, start=1, niter=1000):
pos = start
pop = islands[pos]
thetas = np.zeros(niter+1, dtype='int')
thetas[0] = pos
for i in range(niter):
# generate sample from proposal distribution
k = np.random.choice([-1, 1], 1)
next_pos = pos + k
# evaluate unnormalized target distribution at proposed position
next_pop = islands[next_pos]
# calculate acceptance probability
p = min(1, next_pop/pop)
# use uniform random to decide accept/reject proposal
if np.random.random() < p:
pos = next_pos
pop = next_pop
thetas[i+1] = pos
return thetas
islands = make_islands(10)
thetas = hop(islands, start=1, niter=10000)
# Generic Metropolis scheme
# data = islands[1:-1]
# data = data/data.sum()
# sns.barplot(x=np.arange(len(data)), y=data)
# pass
# Estimated population proportions by doing hops
data = np.bincount(thetas)[1:]
data = data/data.sum()
sns.barplot(x=np.arange(len(data)), y=data)
pass