尝试调用方法';随机';(零值)单位为Lua

尝试调用方法';随机';(零值)单位为Lua,lua,torch,Lua,Torch,下面是我的代码 require 'dpnn' require 'cunn' local deviceNumber = tonumber(os.getenv("CUDA_CARD_NR")) cutorch.setDevice(deviceNumber) local module = nn.Sequential():cuda() module:add(nn.Linear(2,1):cuda()) module:add(nn.Sigmoid():cuda()) criterion

下面是我的代码

require 'dpnn'
 require 'cunn'

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

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

 criterion = nn.BCECriterion():cuda() -- Binary Cross Entorpy Criteria

 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)
但我不知道

lua:13:尝试调用方法“random”(一个nil) 价值)

不是“某个错误”,您不应该有问题找出什么是错误的,因为错误消息确切地告诉您什么是错误的

您试图调用名为
random
的方法,该方法恰好是
nil
值。 这意味着没有具有该名称的函数,因此不能调用它


根据参考文档(您应该在来到这里之前检查过),函数的实际名称为
rand

请参见-可能缺少库名?谢谢您的回答。实际上我想要一个cuda张量,随机值为1和0。我还尝试了
torch.CudaTensor():rand()
它也不起作用。你能告诉我做这件事的正确方法是什么吗?那么你得到了同样的错误还是什么?不工作不是很有用。实际上它不能满足我的需要。我想要随机数中的二进制数字0或1,它不是由
torch.CudaTensor():rand()
生成的。我不知道torch,但根据参考资料,应该有一个函数bernoulli(),可以满足您的需要。这至少适用于其他张量类型。