-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdifficult_pdf.py
More file actions
61 lines (45 loc) · 1.39 KB
/
difficult_pdf.py
File metadata and controls
61 lines (45 loc) · 1.39 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
49
50
51
52
53
54
55
56
57
58
59
60
61
import numpy as np
import matplotlib.pyplot as plt
from pdfs import n_pdf
from ksdensity import ksdensity
from functools import partial
def F_inverse(x, a):
"inverse cdf for exponential function"
#((a**2)/2) * np.exp(-(2*u)/(a**2)) # pdf
return - ((a**2)/(2)) * np.log(1 - x)
def inverse_cdf_sample(N, f):
"""
Inverse cdf method
N - number of samples
f - inverse cdf function
"""
uniform = np.random.rand(N)
sampled = f(uniform)
return sampled
def sample_gaussian(N, mean=0, variance=1):
"""Generate N samples from a generic gaussian"""
std_dev = np.sqrt(variance)
originals = np.random.randn(N)
transformed = (originals * std_dev) + mean
return transformed
N = 10000
a_array = [0.2, 0.5, 1.0, 2.0, 4.0, 8.0]
sigma = 0.4
x_values = np.linspace(-5., 5., 1000)
fig = plt.figure()
plt.title('Kernel smoothed X distribution (N={})'.format(N))
for a in a_array:
f = partial(F_inverse, a=a)
u_array = inverse_cdf_sample(N, f)
x_array = []
for u in u_array:
x_val = sample_gaussian(1, variance=u)
x_array.extend(x_val)
ks_density = ksdensity(x_array, width=sigma)
plt.plot(x_values, ks_density(x_values), label="alpha={}".format(a))
plt.xlabel('x')
plt.ylabel('probability density')
plt.legend()
img_dir = "/mnt/c/Users/ltray/Documents/Cambridge/3F3/img/"
plt.savefig(img_dir + "difficult.png")
plt.show()