import torch
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import arviz as az
%matplotlib inline
# Retina display
%config InlineBackend.figure_format = 'retina'
import warnings
'ignore') warnings.filterwarnings(
from tueplots import bundles
plt.rcParams.update(bundles.beamer_moml())
# Also add despine to the bundle using rcParams
'axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
plt.rcParams[
# Increase font size to match Beamer template
'font.size'] = 16
plt.rcParams[# Make background transparent
'figure.facecolor'] = 'none' plt.rcParams[
= 5000
N = torch.rand(N, 2)
U = U[:, 0]
U1 = U[:, 1]
U2
= torch.sqrt(-2 * torch.log(U1))
R = 2 * np.pi * U2
theta
= R * torch.cos(theta)
X = R * torch.sin(theta)
Y
='X', plot_kwargs={'color': 'C0'})
az.plot_kde(X.numpy(), label='Y', plot_kwargs={'color': 'C1'})
az.plot_kde(Y.numpy(), label
# Plot true density
= torch.linspace(-4, 4, 100)
x = torch.distributions.Normal(0, 1)
norm ='True density', color='C2')
plt.plot(x, norm.log_prob(x).exp().numpy(), label
plt.legend()
<matplotlib.legend.Legend at 0x7f52ce18d2e0>
### Multivariate Sampling
from scipy.stats import gaussian_kde
= torch.tensor([1., -1.])
true_mean = torch.tensor([[1., 0.5], [0.5, 1.]])
true_cov = torch.distributions.MultivariateNormal(true_mean, true_cov)
true_dist
= true_dist.sample((N,))
samples
# Generate samples from the true distribution
= 4000 # Number of samples
N = true_dist.sample((N,))
samples
= samples.numpy()
sample_data
# Calculate KDE using scipy's gaussian_kde
=sample_data[:, 0], y=sample_data[:, 1], kind="kde", space=0, color='C0') sns.jointplot(x
# Find the cholesky decomposition of the covariance matrix
= torch.cholesky(true_cov)
L print(L)
tensor([[1.0000, 0.0000],
[0.5000, 0.8660]])
@L.T L
tensor([[1.0000, 0.5000],
[0.5000, 1.0000]])
X
tensor([ 0.6383, 0.1196, -0.6610, ..., -1.2854, -0.0679, -0.8292])
Y.shape
torch.Size([5000])
= torch.stack([X, Y], dim=1)
Z_I
= Z_I @ L.T + true_mean Z_mu_sigma
Z_mu_sigma.shape
torch.Size([5000, 2])
=Z_mu_sigma.numpy()[:, 0], y=Z_mu_sigma.numpy()[:, 1], kind="kde", space=0, color='C0') sns.jointplot(x
np.cov(Z_mu_sigma.numpy().T)
array([[1.05325545, 0.51403749],
[0.51403749, 1.01457316]])
=0) np.mean(Z_mu_sigma.numpy(), axis
array([ 0.9873801, -0.992024 ], dtype=float32)