Path: blob/master/deprecated/scripts/bayes_change_of_var.py
1192 views
# Based on https://github.com/probml/pmtk3/blob/master/demos/bayesChangeOfVar.m1# MC on change of variables and empirical distribution, highlighting that2# modes are not, in general, preserved.34import superimport56import numpy as np7import matplotlib.pyplot as plt8from scipy.stats import norm9import os10from pyprobml_utils import save_fig1112# Ensure stochastic reproducibility.13np.random.seed(42)1415# Define a mapping from x-space to y-space.16def ginv(x):17"""transform func"""18return 1 / (1 + np.exp(5 - x))1920# Define a probability density on x-space, and sample from it.21mu = 622sigma = 123n = 10 ** 624x_samples = norm.rvs(size=n, loc=mu, scale=sigma)2526# Calculate a histogram for the samples in x-space and a histogram27# for their transformations to y-space.28hist_x, bin_edges_x = np.histogram(x_samples, bins=50, density=True)29hist_y, bin_edges_y = np.histogram(ginv(x_samples), bins=50, density=True)3031# Plot the histograms, the mapping function, and an indication of how32# the x-distribution's mean maps to y-space.33linewidth = 534plt.bar(bin_edges_x[:-1], hist_x, color='red', align='edge', width=bin_edges_x[1] - bin_edges_x[0])35plt.barh(bin_edges_y[:-1], hist_y, color='green', align='edge', height=bin_edges_y[1] - bin_edges_y[0])36x_range = np.arange(0, 10, 0.01)37plt.plot(x_range, ginv(x_range), 'blue', linewidth=linewidth)38plt.vlines(mu, ymin=0, ymax=ginv(mu), color='yellow', linewidth=linewidth)39plt.hlines(ginv(mu), xmin=0, xmax=mu, color='yellow', linewidth=linewidth)40plt.text(9, 1/10, r'$p_X$');41plt.text(2/3, 2/10, r'$p_Y$');42plt.text(9, ginv(9) - 1/10, r'$g$');4344## Save the figure.45save_fig('bayesChangeOfVar.pdf')46plt.show()47484950