运行 #StochasticGradient 时出错:Torch,lua

我正在尝试在 Torch 中第一次训练前馈神经网络。这是我的数据集:http://ocw.mit.edu/courses/sloan-school-of-management/15-097-prediction-machine-learning-and-statistics-spring-2012/datasets/transfusion.csv

这是我的代码(基于 http://mdtux89.github.io/2015/12/11/torch-tutorial.html):

require 'nn'
mlp = nn.Sequential()
inputSize = 4
hiddenLayer1Size = 4
hiddenLayer2Size = 4

mlp:add(nn.Linear(inputSize,hiddenLayer1Size)) -- 行,列
mlp:add(nn.Tanh())
mlp:add(nn.Linear(hiddenLayer1Size,hiddenLayer2Size))
mlp:add(nn.Tanh())

nclasses = 1

mlp:add(nn.Linear(hiddenLayer2Size,nclasses))
mlp:add(nn.LogSoftMax())

output = mlp:forward(torch.rand(1,4))
print(output)

-- 使用内置随机梯度下降进行训练,2个参数:网络,准则函数。--
LRate = 0.1

criterion = nn.ClassNLLCriterion()
trainer = nn.StochasticGradient(mlp, criterion)
trainer.learningRate = LRate

function string:splitAtCommas()
  local sep, values = ",", {}
  local pattern = string.format("([^%s]+)", sep)
  self:gsub(pattern, function(c) values[#values+1] = c end)
  return values
end

function loadData(dataFile)
  local dataset,i = {},0
  for line in io.lines(dataFile) do
    local values = line:splitAtCommas()
    local y = torch.Tensor(1)
    y[1] = values[#values] -- 目标类是行中的最后一个数字
    values[#values] = nil
    local x = torch.Tensor(values) -- 输入数据包括其他数字
    dataset[i] = {x, y}
    i = i + 1
  end
  function dataset:size() return (i - 1) end -- 要求中提到
  return dataset
end

dataset = loadData("transfusion.csv")

trainer:train(dataset)

这是 错误报告

# StochasticGradient:training
/Users/drdre/torch/install/share/lua/5.1/nn/THNN.lua:109: Assertion `cur_target >= 0 && cur_target < n_classes' failed.  at /Users/drdre/torch/extra/nn/lib/THNN/generic/ClassNLLCriterion.c:38
stack traceback:
    [C]: in function 'v'
    /Users/drdre/torch/install/share/lua/5.1/nn/THNN.lua:109: in function 'ClassNLLCriterion_updateOutput'
    ...dre/torch/install/share/lua/5.1/nn/ClassNLLCriterion.lua:41: in function 'forward'
    ...re/torch/install/share/lua/5.1/nn/StochasticGradient.lua:35: in function 'f'
    [string "local f = function() return trainer:train(dat..."]:1: in main chunk
    [C]: in function 'xpcall'
    /Users/drdre/torch/install/share/lua/5.1/itorch/main.lua:209: in function </Users/drdre/torch/install/share/lua/5.1/itorch/main.lua:173>
    /Users/drdre/torch/install/share/lua/5.1/lzmq/poller.lua:75: in function 'poll'
    /Users/drdre/torch/install/share/lua/5.1/lzmq/impl/loop.lua:307: in function 'poll'
    /Users/drdre/torch/install/share/lua/5.1/lzmq/impl/loop.lua:325: in function 'sleep_ex'
    /Users/drdre/torch/install/share/lua/5.1/lzmq/impl/loop.lua:370: in function 'start'
    /Users/drdre/torch/install/share/lua/5.1/itorch/main.lua:381: in main chunk
    [C]: in function 'require'
    (command line):1: in main chunk
    [C]: at 0x0105e4cd10

点赞
用户1688185
用户1688185

使用 nclasses = 2y[1] = values[#values] + 1。参见文档

一个期望输出 y (一个从 1 到 n 的整数,在这种情况下 n = 2 类)

2016-06-10 07:56:41