【问题标题】:Minimizing a function with two layers用两层最小化一个函数
【发布时间】:2020-08-24 09:02:42
【问题描述】:

我正在研究优化运输,我必须解决这个问题:

在哪里

的模拟位置。

我可以将转移计划和函数 u 近似为 并尝试用神经网络找到 theta 和 w。

使用 Arrow_Huwicz 算法我有以下简单的程序:我们在 [1,N] 中绘制一些 k 并在 w 和 中迭代地最小化这个函数,这样在第 n 步, 和 直到达到itermax

def 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, 1), 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,k,theta,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 随机梯度执行相同的操作?

【问题讨论】:

标签: machine-learning pytorch gradient


【解决方案1】:

首先我想指出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, 1, 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,k,theta,w)
        (-F).backward()
        w_opt.step()

    optw = w.detach().numpy()[0][0]
    optth = theta.detach().numpy()[0][0]
    return JN2(S12,optth,optw)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2021-04-01
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多