【发布时间】:2020-12-04 19:10:56
【问题描述】:
我目前正在学习 PyTorch 以利用其开源 autograd 功能,作为我自己的练习,我想实现一个我已经在 MATLAB 中实现的简单优化算法。作为一个简单的例子,假设我正在尝试解决问题min_x 1/2 x'Ax - b'x,即在给定A 和b 的情况下,找到最小化数量x'Ax - b'x 的向量x。在 MATLAB 中使用精确线搜索的简单梯度下降算法可能如下所示:
% initialize x = zeros(n, 1) where n is the length of b
while residual > tolerance
grad = A*x - b; % compute the gradient of the objective
alpha = norm(grad)^2/(grad'*A*grad); % compute step-size alpha by exact line search
x = x - alpha*grad; % do a gradient step
residual = norm(grad); % compute residual
objective = x'*A*x - b'*x; % compute objective value at current iteration
如何在 PyTorch 中实现这种优化算法?具体来说,我想做一个相同的优化循环,用 Torch 的 autograd 功能替换我自己的梯度计算。换句话说,我想在 PyTorch 中执行与上面完全相同的算法,除了我自己不计算梯度,我只是使用 PyTorch 的 autograd 功能来计算梯度。这样,我不想调用任何给定的优化器(如 SGD 或 Adam)——只需自己编写算法,唯一的区别是梯度是由 PyTorch 计算的。我计划将上述 numpy/MATLAB 实现的结果与显式梯度计算与 PyTorch 实现与我假设的梯度的数值近似进行比较。
非常感谢!
【问题讨论】:
标签: algorithm matlab optimization pytorch autograd