In [1]:
    
require 'nn';
require 'torch';
    
In [54]:
    
local matio = require 'matio'
data = matio.load('ex4data1.mat')
    
In [55]:
    
trainset = {}
trainset.data = data.X
trainset.label = data.y[{ {}, 1}]
    
In [56]:
    
trainset
    
In [57]:
    
setmetatable(trainset,
    {__index = function(t,i)
                return {t.data[i], t.label[i]}
        end}
);
 
function trainset:size()
    return self.data:size(1)
end
    
    Out[57]:
In [58]:
    
mean = {}
stdv = {}
for i=1,400 do
    mean[i] = trainset.data[{ {},{i} }]:mean()
    stdv[i] = trainset.data[{ {}, {i} }]:std()
    --print(i .. 'th mean: ' .. mean[i])
    --print(i .. 'th std dev: ' .. stdv[i])
    trainset.data[{ {},{i} }]:add(-mean[i])
    if stdv[i] ~= 0 then
        trainset.data[{ {},{i} }]:div(stdv[i])
    end
end
    
In [59]:
    
net = nn.Sequential()
net:add(nn.Linear(400,25))
net:add(nn.Sigmoid())
net:add(nn.Linear(25,10))
net:add(nn.Sigmoid())
net:add(nn.LogSoftMax())
    
In [60]:
    
criterion = nn.ClassNLLCriterion()
    
In [61]:
    
trainer = nn.StochasticGradient(net, criterion)
trainer.learningRate = 0.001
trainer.maxIteration = 1e2
    
In [62]:
    
trainer:train(trainset)
    
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
    Out[62]:
In [63]:
    
correction = 0
for i=1,trainset:size() do
    local answer = trainset.label[i]
    local prediction = net:forward(trainset.data[i])
    local confidences, indices = torch.sort(prediction, true)
    if (answer == indices[1]) then
        correction = correction + 1
    end
end
print(correction, 100*correction/trainset:size() .. '%')
    
    Out[63]:
In [ ]: