从上面的代码可知,参数 W 和 b 均定义为一般线性回归模型分布,两者都服从正态分布 Normal(0,1)。我们称之为先验,创建 Pyro 的随机函数(在我们的例子中是 PyTorch 中的 RegressionModel),为它添加先验 ({『linear.weight』: w_prior, 『linear.bias』: b_prior}),并根据输入数据 x 从这个模型 p(y|x) 中抽样。
这个模型的 guide 部分可能像下面这样:
def guide(data):
w_mu = Variable(torch.randn(1, p).type_as(data.data), requires_grad=True)
w_log_sig = Variable(0.1 * torch.ones(1, p).type_as(data.data), requires_grad=True)
b_mu = Variable(torch.randn(1).type_as(data.data), requires_grad=True)
b_log_sig = Variable(0.1 * torch.ones(1).type_as(data.data), requires_grad=True)
mw_param = pyro.param("guide_mean_weight", w_mu)
sw_param = softplus(pyro.param("guide_log_sigma_weight", w_log_sig))
mb_param = pyro.param("guide_mean_bias", b_mu)
sb_param = softplus(pyro.param("guide_log_sigma_bias", b_log_sig))
w_dist = Normal(mw_param, sw_param)
b_dist = Normal(mb_param, sb_param)
dists = {'linear.weight': w_dist, 'linear.bias': b_dist}
lifted_module = pyro.random_module("module", regression_model, dists)
return lifted_module()
我们定义了想要「训练」的分布的可变分布。如你所见,我们为 W 和 b 定义了相同的分布,目的是让它们更接近实际情况(据我们假设)。这个例子中,我让分布图更窄一些(服从正态分布 Normal(0, 0.1))
然后,我们用这种方式对模型进行训练:
for j in range(3000): epoch_loss = 0.0 perm = torch.randperm(N) # shuffle data data = data[perm] # get indices of each batch all_batches = get_batch_indices(N, 64) for ix, batch_start in enumerate(all_batches[:-1]): batch_end = all_batches[ix + 1] batch_data = data[batch_start: batch_end] epoch_loss += svi.step(batch_data)
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-70150-3.html
中国人抵制苹果手机