使用 torch7 演示的线性回归

linear-regression with torch7 demo

我正在关注这个演示- https://github.com/torch/demos/blob/master/linear-regression/example-linear-regression.lua

feval = function(x_new)
   -- set x to x_new, if differnt
   -- (in this simple example, x_new will typically always point to x,
   -- so the copy is really useless)
   if x ~= x_new then
      x:copy(x_new)
   end

   -- select a new training sample
   _nidx_ = (_nidx_ or 0) + 1
   if _nidx_ > (#data)[1] then _nidx_ = 1 end

   local sample = data[_nidx_]
   local target = sample[{ {1} }]      -- this funny looking syntax allows
   local inputs = sample[{ {2,3} }]    -- slicing of arrays.
   dl_dx:zero()
   local loss_x = criterion:forward(model:forward(inputs), target)
   model:backward(inputs, criterion:backward(model.output, target))
   return loss_x, dl_dx
end 

我对这个功能有些疑惑

  1. 代码中使用的参数 x_new(或其副本 x)在哪里?
  2. _nidx_ = (_nidx_ or 0) + 1是什么意思?
  3. 第一次调用函数时nidx的值是多少?
  4. dl_dx更新在哪里?理想情况下,它应该在 local loss_x 更新之后,但它没有明确地写

编辑:

我的第 4 点现在很清楚了。对于那些有兴趣的人- (来源-深度学习,牛津,实用 3 实验室 sheet)

  1. x是一个全局变量,见第126行。该函数似乎只是更新它,而不是使用它。
  2. 这是一个常见的 lua 习惯用法:如果参数不存在,则将其设置为参数或默认值。函数中的典型用法:

    function foo(a, b)
        local a = a or 0
        local b = b or "foo"
    end
    

这个想法是,使用 andor evalua 的表达式根据值赋给第一个或第二个参数。如果 x 不是 nilfalse 并且 x (nil 或 false),则 x and y 产生 y

如果 x 不存在(nil 或 false),

x or y 产生 y,否则产生 x。因此,or 用于默认参数。

两者可以改写为:

-- x and y
if x then
    return y
else
    return x
end
-- x or y
if x then
    return x
else
    return y
end
  1. 你有 _nidx_ = (_nidx or 0) + 1,所以在第一次调用函数时,_nidx_ 是 nil,因为它没有被定义。之后,它(全局)设置为 1 (0 + 1)

  2. 我不太清楚你的意思。它在第 152 行重置并由函数本身返回。它是一个全局变量,所以它可能有外部用途?

Where is the argument x_new (or its copy x) used in the code?

x 是模型参数的张量。它之前是通过 x, dl_dx = model:getParameters() 获得的。 model:forward()model:backward() 自动使用这个参数张量。 x_new 是一组新的模型参数,由优化器 (SGD) 提供。如果它与您模型的参数张量不同,您的模型参数将通过 x:copy(x_new) 设置为这些新参数(将张量的 x_new 值就地复制到 x)。

What does nidx = (nidx or 0) + 1 mean?

它增加 _nidx_ 的值 1 ((_nidx_) + 1) 或将其设置为 1 ((0) + 1) 如果 _nidx_尚未定义。

what is the value of nidx when the function is first called?

在该功能之前从未设置过。尚未设置的变量在 lua.

中的值为 nil

Where is dl_dx updated? Ideally it should have been just after local loss_x is updated, but it isnt written explicitly

dl_dx 是模型的梯度张量。 model:backward() 在给定损失的情况下计算每个参数的梯度,并将其添加到模型的梯度张量中。由于 dl_dx 是模型的梯度张量,它的值会增加。请注意,梯度值是 added,这就是为什么您需要调用 dl_dx:zero()(将 dl_dx 的值就地设置为零),否则您的梯度每次调用 feval.

值都会增加