Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/deprecated/scripts/bayes_change_of_var.py
1192 views
1
# Based on https://github.com/probml/pmtk3/blob/master/demos/bayesChangeOfVar.m
2
# MC on change of variables and empirical distribution, highlighting that
3
# modes are not, in general, preserved.
4
5
import superimport
6
7
import numpy as np
8
import matplotlib.pyplot as plt
9
from scipy.stats import norm
10
import os
11
from pyprobml_utils import save_fig
12
13
# Ensure stochastic reproducibility.
14
np.random.seed(42)
15
16
# Define a mapping from x-space to y-space.
17
def ginv(x):
18
"""transform func"""
19
return 1 / (1 + np.exp(5 - x))
20
21
# Define a probability density on x-space, and sample from it.
22
mu = 6
23
sigma = 1
24
n = 10 ** 6
25
x_samples = norm.rvs(size=n, loc=mu, scale=sigma)
26
27
# Calculate a histogram for the samples in x-space and a histogram
28
# for their transformations to y-space.
29
hist_x, bin_edges_x = np.histogram(x_samples, bins=50, density=True)
30
hist_y, bin_edges_y = np.histogram(ginv(x_samples), bins=50, density=True)
31
32
# Plot the histograms, the mapping function, and an indication of how
33
# the x-distribution's mean maps to y-space.
34
linewidth = 5
35
plt.bar(bin_edges_x[:-1], hist_x, color='red', align='edge', width=bin_edges_x[1] - bin_edges_x[0])
36
plt.barh(bin_edges_y[:-1], hist_y, color='green', align='edge', height=bin_edges_y[1] - bin_edges_y[0])
37
x_range = np.arange(0, 10, 0.01)
38
plt.plot(x_range, ginv(x_range), 'blue', linewidth=linewidth)
39
plt.vlines(mu, ymin=0, ymax=ginv(mu), color='yellow', linewidth=linewidth)
40
plt.hlines(ginv(mu), xmin=0, xmax=mu, color='yellow', linewidth=linewidth)
41
plt.text(9, 1/10, r'$p_X$');
42
plt.text(2/3, 2/10, r'$p_Y$');
43
plt.text(9, ginv(9) - 1/10, r'$g$');
44
45
## Save the figure.
46
save_fig('bayesChangeOfVar.pdf')
47
plt.show()
48
49
50