import numpy as np
import matplotlib.pyplot as plt
import torch
import seaborn as sns
import pandas as pd
=torch.distributions
t_dist
sns.reset_defaults()="talk", font_scale=1)
sns.set_context(context%matplotlib inline
%config InlineBackend.figure_format='retina'
Basic Imports
Creating dataset
= torch.linspace(-5, 5, 200)
x = 3*x + 4
true_y = true_y+ 2*torch.randn(200)
observed_y
= 30, alpha=0.5)
plt.scatter(x, observed_y, s = 'k')
plt.plot(x, true_y, color
sns.despine()
MLE
import pyro
import pyro.distributions as dist
import pyro.distributions.constraints as constraints
pyro.clear_param_store()
def mle_model(x, y=None):
= pyro.param("theta_0", torch.randn(1))
theta_0 = pyro.param("theta_1", torch.randn(1))
theta_1 = theta_0 + theta_1*x
y_hat_mean
with pyro.plate("data", len(x)):
return pyro.sample("obs", dist.Normal(y_hat_mean, 1), obs=y)
#pyro.render_model(mle_model, model_args=(x, observed_y))
= mle_model(x)
m "theta_0").item(), pyro.param("theta_1").item() pyro.param(
(-0.100727379322052, 1.5172470808029175)
for i in range(5):
= 5, alpha = 0.4)
plt.scatter(x, mle_model(x).detach(), s plt.plot(x, )
def guide(x, y):
# register the two variational parameters with Pyro.
"theta_0", dist.Normal(0., 1.))
pyro.sample("theta_1", dist.Normal(0., 1.)) pyro.sample(
=(x, observed_y)) pyro.render_model(guide, model_args
from pyro.optim import Adam
from pyro.infer import SVI, Trace_ELBO
= {"lr": 0.005, "betas": (0.90, 0.999)}
adam_params = Adam(adam_params)
optimizer
# setup the inference algorithm
= SVI(mle_model, guide, optimizer, loss=Trace_ELBO())
svi
= 5000
n_steps # do gradient steps
for step in range(n_steps):
svi.step(x, y)if step%110==0:
print(pyro.param("theta_0").item(), pyro.param("theta_1").item())
/Users/nipun/miniforge3/lib/python3.9/site-packages/pyro/util.py:288: UserWarning: Found non-auxiliary vars in guide but not model, consider marking these infer={'is_auxiliary': True}:
{'theta_1', 'theta_0'}
warnings.warn(
ValueError: Error while computing log_prob at site 'obs':
Value is not broadcastable with batch_shape+event_shape: torch.Size([100]) vs torch.Size([200]).
Trace Shapes:
Param Sites:
theta_0 1
theta_1 1
Sample Sites:
obs dist 200 |
value 100 |
= torch.linspace(-5, 5, 100)
x = pyro.param("theta_1").item()*x + pyro.param("theta_0").item()
predicted_y #observed_y = true_y+ 2*torch.randn(100)
= 30, alpha=0.5)
plt.scatter(x, observed_y, s = 'k')
plt.plot(x, predicted_y, color = 'k')
plt.plot(x, true_y, color
sns.despine()
= 2
data_dim = 1
latent_dim = 100
num_datapoints = dist.Normal(
z =torch.zeros([latent_dim, num_datapoints]),
loc=torch.ones([latent_dim, num_datapoints]),)
scale
= dist.Normal(
w =torch.zeros([data_dim, latent_dim]),
loc=5.0 * torch.ones([data_dim, latent_dim]),
scale )
= w.sample()
w_sample= z.sample()
z_sample
= dist.Normal(loc = w_sample@z_sample, scale=2)
x = x.sample([100])
x_sample 0], x_sample[:, 1], alpha=0.2, s=30) plt.scatter(x_sample[:,
Generative model for PPCA in Pyro
import pyro.distributions as dist
import pyro.distributions.constraints as constraints
import pyro
pyro.clear_param_store()
def ppca_model(data, latent_dim):
= data.shape
N, data_dim = pyro.param("W", torch.zeros((data_dim, latent_dim)))
W #print(W.shape, data_dim, (data_dim, latent_dim))
for i in range(N):
= pyro.sample("z_{}".format(i), dist.Normal(loc = torch.zeros(latent_dim), scale = 1.))
z_vec #print(W.shape, z.shape, W@z)
fr"\$x_{i}\$", dist.Normal(W@z_vec, 2.), obs=data[i])
pyro.sample(
=(torch.randn(150, 3), 1)) pyro.render_model(ppca_model, model_args
pyro.clear_param_store()
def ppca_model2(data, latent_dim):
= data.shape
N, data_dim = pyro.param("W", torch.zeros((data_dim, latent_dim)))
W #print(W.shape, data_dim, (data_dim, latent_dim))
= pyro.sample("z", dist.Normal(loc = torch.zeros([latent_dim, N]), scale = 1.))
z_vec
print(W.shape, z_vec.shape, (W@z_vec).t().shape, data.shape)
return pyro.sample("obs", (W@z_vec).t(), obs=data)
=(torch.randn(150, 3), 1)) pyro.render_model(ppca_model2, model_args
torch.Size([3, 1]) torch.Size([1, 150]) torch.Size([150, 3]) torch.Size([150, 3])
AttributeError: 'ProvenanceTensor' object has no attribute 'log_prob'
= torch.tensor([0.]), scale = 1.).sample() dist.Normal(loc
tensor([-1.2529])
pyro.clear_param_store()
= 2
D = 1
d
= torch.zeros(100, D)
data
def ppca(data):
= pyro.param("A", torch.zeros((D, d)))
A = pyro.param("mu", torch.zeros(D))
mu
for i in pyro.plate("data", len(data)):
= pyro.sample("latent_{}".format(i), dist.Normal(torch.zeros(d), 1.0).to_event(1))
z "observed_{}".format(i), dist.Normal(A @ z + mu, 1.0).to_event(1), obs=data[i])
pyro.sample(
={'data':data}) pyro.render_model(ppca, model_kwargs
ppca(data)
data.shape
torch.Size([100, 2])
= 1000
N = np.random.normal(loc = 5, scale = 1., size = N) x
= {}
o for i in range(N-2):
= x[:i+2].std() o[i]
pd.Series(o).plot()=1)
plt.axhline(y sns.despine()
= np.array(list(o.values())) x2
= {}
o2 for i in range(N-3):
= x2[:i+2].std() o2[i]
pd.Series(o2).plot()