|
| 1 | +""" |
| 2 | +Code to replicate the results in section 4.1: "Gaussian Toy Model" of the paper |
| 3 | +Sampling-Based Accuracy Testing of Posterior Estimators for General Inference |
| 4 | +""" |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +from tarp import get_drp_coverage |
| 9 | + |
| 10 | +# Set random seed |
| 11 | +np.random.seed(0) |
| 12 | + |
| 13 | +# latex rendering: |
| 14 | +plt.rc('font', **{'size': 10, 'family': 'serif', 'serif': ['Computer Modern']}) |
| 15 | +plt.rc('text', usetex=True) |
| 16 | + |
| 17 | + |
| 18 | +def generate_psd_matrix(n): |
| 19 | + # generate random array of appropriate size |
| 20 | + arr_size = int(n * (n - 1) / 2) |
| 21 | + arr = np.random.rand(arr_size) |
| 22 | + |
| 23 | + # convert array to symmetric matrix |
| 24 | + mat = np.zeros((n, n)) |
| 25 | + triu_indices = np.triu_indices(n, k=1) |
| 26 | + mat[triu_indices] = arr |
| 27 | + mat += mat.T |
| 28 | + |
| 29 | + # check if matrix is positive semidefinite |
| 30 | + eigenvals = np.linalg.eigvalsh(mat) |
| 31 | + if np.all(eigenvals >= 0): |
| 32 | + return mat |
| 33 | + else: |
| 34 | + # if not, add identity matrix to make it PSD |
| 35 | + mat = mat + np.eye(n) * abs(eigenvals.min()) * 2 |
| 36 | + return mat |
| 37 | + |
| 38 | + |
| 39 | +def generate_correlated_samples(num_samples, num_sims, num_dims): |
| 40 | + """ Generate samples and true parameter values """ |
| 41 | + theta = np.random.uniform(low=-5, high=5, size=(num_sims, num_dims)) |
| 42 | + cov = [generate_psd_matrix(num_dims) for _ in range(num_sims)] |
| 43 | + cov = np.concatenate(cov).reshape(num_sims, num_dims, num_dims) |
| 44 | + samples = [np.random.multivariate_normal(mean=theta[i], cov=cov[i], size=num_samples) for i in range(num_sims)] |
| 45 | + samples = np.stack(samples) |
| 46 | + samples = samples.transpose(1, 0, 2) |
| 47 | + theta = [np.random.multivariate_normal(mean=theta[i], cov=cov[i], size=1) for i in range(num_sims)] |
| 48 | + theta = np.stack(theta)[:,0] |
| 49 | + return samples, theta |
| 50 | + |
| 51 | + |
| 52 | +def main(): |
| 53 | + """ Main function """ |
| 54 | + samples, theta = generate_correlated_samples(num_samples=1000, num_sims=100, num_dims=10) |
| 55 | + alpha, ecp = get_drp_coverage(samples, theta, references='random', metric='euclidean') |
| 56 | + |
| 57 | + fig, ax = plt.subplots(1, 1, figsize=(4, 4)) |
| 58 | + ax.plot([0, 1], [0, 1], ls='--', color='k') |
| 59 | + ax.plot(alpha, ecp, label='DRP') |
| 60 | + ax.legend() |
| 61 | + ax.set_ylabel("Expected Coverage") |
| 62 | + ax.set_xlabel("Credibility Level") |
| 63 | + plt.show() |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + main() |
| 68 | + |
| 69 | + |
| 70 | + |
0 commit comments