Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chiral
Created October 1, 2015 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiral/248040ef4fdb1f82179c to your computer and use it in GitHub Desktop.
Save chiral/248040ef4fdb1f82179c to your computer and use it in GitHub Desktop.
3 layer perceptron for iris data by torch7. iris.csv can be obtained from https://gist.github.com/chiral/5b3609e884e3af8b412a
-- loarocks install csv
csv = require "csv"
nn = require "nn"
-- prepare data set
dataset={}
size=0
ans={setosa=1,versicolor=2,virginica=3}
local f = csv.open("iris.csv")
for cols in f:lines() do
local input=torch.Tensor(4)
local output=torch.Tensor(3)
for i,v in ipairs(cols) do
if i>=2 and i<=5 then
input[i-1] = v
end
if i==6 then
for j=1,3 do
output[j] = j==ans[v] and 1 or 0
end
end
print (input,output)
end
size=size+1
dataset[size]={input,output}
end
function dataset:size() return size end
-- make model
nhidden = 5
model = nn.Sequential();
model:add(nn.Linear(4,nhidden))
model:add(nn.Tanh())
model:add(nn.Linear(nhidden,3))
model:add(nn.SoftMax())
print (model)
criterion = nn.MSECriterion()
trainer = nn.StochasticGradient(model, criterion)
trainer.learningRate = 0.01
trainer.maxIteration = 1000
trainer:train(dataset)
test1_in = torch.Tensor(4)
test1_in[1] = 6.7
test1_in[2] = 2.5
test1_in[3] = 5.8
test1_in[4] = 1.8
-- answer = 3
test1_out = model:forward(test1_in)
print (test1_out) -- OK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment