Hi,
I am trying to implement a custom loss function with has two different parts, but I am not sure how to put them together.
→ The first part of the loss function is the ELBO, for which I want to use loss = pyro.infer.Trace_ELBO()
.
→ The second part is a l2 regularizer described as:
def L2_regularizer(my_parameters, lam=torch.tensor(1.)):
reg_loss = 0.0
for param in my_parameters:
reg_loss = reg_loss + param.pow(2.0).sum()
return lam*reg_loss
My model and guide look as follows:
def model(data):
x_loc = torch.zeros(N*3,)
x_scale = 2*torch.ones(N*3,)
x = pyro.sample("x", dist.Normal(x_loc, x_scale).to_event(1))
....
....
def guide(data):
x_loc = pyro.param("x_loc", torch.rand(N*3,))
x_scale = pyro.param("x_scale", 0.5*torch.ones(N*3,), constraint=constraints.positive)
x = pyro.sample("x", dist.Normal(x_loc, x_scale).to_event(1))
The parameters that I want to use in the L2_regularizer
are the x_loc
(which I define inside the guide).
How can put these two loss functions together? Any help would be appreciated.
Thank you,
Atharva