Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/deprecated/scripts/ars_demo.py
1192 views
1
# -*- coding: utf-8 -*-
2
# Author: Ang Ming Liang
3
4
import superimport
5
6
import numpy as np
7
import matplotlib.pyplot as plt
8
from arspy.ars import adaptive_rejection_sampling
9
10
a , b = -2, 0
11
domain = [-float('inf'), 0]
12
n_samples = 20000
13
sigma = 3
14
15
def halfgaussian_logpdf(x):
16
out = np.log(np.exp(-x**2/sigma))*np.heaviside(-x,1)
17
return out
18
19
xs = np.arange(-3*sigma, 3*sigma, 0.1)
20
y = np.exp(halfgaussian_logpdf(xs))
21
22
samples = adaptive_rejection_sampling(logpdf=halfgaussian_logpdf, a=a, b=b, domain=domain, n_samples=n_samples)
23
24
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18,6))
25
26
# Title
27
ax1.set_title("f(x) half-guassian")
28
29
# Fix the plot size
30
ax1.set_xlim(-3*sigma, 3*sigma)
31
ax1.set_ylim(0,1)
32
33
ax1.plot(xs, y)
34
35
# Title
36
ax2.set_title("samples from f(x) (by ARS)")
37
38
# Fix the plot size
39
ax2.set_xlim(-3*sigma, 3*sigma)
40
ax2.set_ylim(0,1100)
41
42
ax2.hist(samples, bins=75)
43
44
plt.show()
45
46
47