尝试在 Lua 中调用方法 'random' (空值)

以下是我的代码

require 'dpnn'
require 'cunn'

local deviceNumber = tonumber(os.getenv("CUDA_CARD_NR"))
print(deviceNumber)
cutorch.setDevice(deviceNumber)

local module = nn.Sequential():cuda()
module:add(nn.Linear(2,1):cuda())
module:add(nn.Sigmoid():cuda())

criterion = nn.BCECriterion():cuda() -- 二元交叉熵准则

local targets = torch.CudaTensor(10):random(0,1)
local inputs = torch.CudaTensor(10,2):uniform(-1,1)

function trainEpoch(module,criterion,inputs,targets)
  for i=1,inputs:size(1) do
    local idx = math.random(1,inputs:size(1))
    local input, target = inputs[idx], targets:narrow(1,idx,1)
    -- forward
    local output= module:forward(input)
    local loss= criterion:forward(output,target)
    -- backward
    local gradOutput = criterion:backward(output,target)
    module:zeroGradParameters()
    local gradInput = module:backward(input,gradOutput)
    --update
    module:updateGradParameters(0.9) -- momentum
    module:updateParameters(0.1) -- W = W -0.1*dL/dW
  end
end

for i=1,100 do
  trainEpoch(module,criterion,inputs,targets)
end

我使用以下命令运行以上代码

CUDA_CARD_NR=1 luajit feedforwad.lua

它给出以下错误

luajit: feedforwad.lua:13: attempt to call method 'random' (a nil value)
stack traceback:
    feedforwad.lua:13: in main chunk
    [C]: at 0x004064f0

我知道这一行有错误

local targets = torch.CudaTensor(10):random(0,1)

但我找不到错误在哪里。

点赞
用户2858170
用户2858170

,so you should change your code to call that function instead.

Do note that this is not just "some error". It's a specific error message that gives you information on what went wrong and how to fix it. Take advantage of it and use it to debug your code.

2017-01-23 06:36:32