问题描述
我正在研究最佳运输方式,我必须解决这个问题:
其中
其中
已被模拟。我可以将转移计划T和函数u近似为
,并尝试使用神经网络找到theta和w。使用Arrow_Huwicz算法,我有以下简单程序:我们在[1,N]中绘制一些k,然后在w和
中迭代最小化此函数,以便在步骤n,和 直到达到itermaxdef Arrow_Hurwicz_algorithm(dim,NMC,S12,itermax):
w = torch.autograd.Variable(torch.rand(dim,1),requires_grad=True)
theta = torch.autograd.Variable(torch.rand(dim,requires_grad=True)
step_size = 1e-6
for i in range(itermax):
k = randrange(NMC)
L = JN(S12,k,theta,w)
L.backward()
theta.data -= step_size * theta.grad.data # step
F = JN(S12,w)
F.backward()
w.data += step_size * w.grad.data
w.grad.data.zero_()
theta.grad.data.zero_()
optw = w.detach().numpy()[0][0]
optth = theta.detach().numpy()[0][0]
return JN2(S12,optth,optw)
我如何在pytorch中使用Adam随机梯度来处理同一件事?
解决方法
首先,我想指出the use of torch.Variable is deprecated。
Pytorch反向传播器只能最小化一个功能。但幸运的是,梯度是线性运算,因此我们可以改为最小化-J
。这将产生类似:
def Arrow_Hurwicz_algorithm(dim,NMC,S12,itermax):
w = torch.rand(dim,1,requires_grad=True)
theta = torch.rand(dim,requires_grad=True)
step_size = 1e-6
w_opt = torch.optim.Adam([w],lr=step_size)
theta_opt = torch.optim.Adam([theta],lr=step_size)
for i in range(itermax):
k = randrange(NMC)
L = JN(S12,k,theta,w)
# Minimizing JN w/ respect to theta
L.backward()
theta_opt.step()
# Maximizing JN with respect to w
F = JN(S12,w)
(-F).backward()
w_opt.step()
optw = w.detach().numpy()[0][0]
optth = theta.detach().numpy()[0][0]
return JN2(S12,optth,optw)