Hello,
This is my code:
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import pyro
import pyro.distributions as dist
from pyro.infer.mcmc import MCMC, HMC, NUTS
from pyro.infer.mcmc.api import MCMC
import pyro.poutine as poutinefrom pyro.infer.mcmc.util import predictive
from pyro.distributions.util import sum_rightmostfrom torch.autograd import Variable
import matplotlib.pyplot as pltpyro.set_rng_seed(42)
N = 50 # Size of the dataset
X_data = torch.rand(N,1) # Sampling of N uniformly distributed points
a, b = 10, 5
sigma = 5
Y_data = a * X_data + b + dist.Normal(loc=0, scale=sigma).sample([N,1]) # Computing Y_data with normal noiseclass NNModel(nn.Module):
def __init__(self, input_dim, output_dim): super(NNModel, self).__init__() self.L1 = nn.Linear(input_dim, output_dim) def forward(self, x): output = self.L1(x) return output.squeeze(-1)
def model(x):
L1w_prior = dist.Normal(loc=torch.zeros_like(Net.L1.weight), scale=torch.ones_like(Net.L1.weight)) L1b_prior = dist.Normal(loc=torch.zeros_like(Net.L1.bias), scale=torch.ones_like(Net.L1.bias)) sigma = pyro.sample('sigma', dist.Uniform(0,1)) priors = {'L1.weight': L1w_prior, 'L1.bias': L1b_prior, 'sigma': sigma} lifted_module = pyro.random_module("module", Net, priors) lifted_net = lifted_module() with pyro.plate("map", len(x)): prediction = lifted_net(x) return pyro.sample("obs", dist.Normal(prediction, sigma))
def conditioned_model(model, x, y):
return poutine.condition(model, data={“obs”:y})(x)Net = NNModel(1,1)
nuts_kernel = NUTS(conditioned_model)
mcmc = MCMC(nuts_kernel, num_samples=60, warmup_steps=0, num_chains=1)mcmc.run(model, X_data, Y_data)
mcmc.summary()from pyro.infer.mcmc.util import predictive
samples = mcmc.get_samples()trace = predictive(conditioned_model, samples, model, X_data, Y_data, return_trace=True)
I am getting this error:
RuntimeError: t() expects a tensor with <= 2 dimensions, but self is 3D
when I am run this line:
trace = predictive(conditioned_model, samples, model, X_data, Y_data, return_trace=True)
I tried to fix the error by reshaping the size of the weights and bias samples (with view), but I still get a different error at the end.
Thank you for your attention.