Skip to content

Instantly share code, notes, and snippets.

@buyoh
Created February 12, 2016 03:23
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 buyoh/90acdea17fb443b2d0e2 to your computer and use it in GitHub Desktop.
Save buyoh/90acdea17fb443b2d0e2 to your computer and use it in GitHub Desktop.
require 'matrix'
#
# perceptron
#
@data=[]
@dim=3
@eta=0.75
# read data
while cin=gets
cl=cin.split(",")
cc=cl.shift=="t" ? 1 : -1
cv=Vector.elements([1.0]+cl.map!(&:to_f))
@data+=[[cc,cv]]
end
@num=@data.size
@w=Vector.elements([1.0]*@dim)
def linear(x)
r=0
@dim.times{|i|
r+=@w[i]*x[i]
}
return r
end
200.times{
flg=false;
@num.times{|i|
f=linear(@data[i][1]) *@data[i][0]
@w+=@eta*@data[i][1]*@data[i][0] if f<0
flg|=(f<0)
}
break if !flg
}
puts "result"
p @w
puts "test"
@num.times{|i|
puts sprintf("[%3d] %10.6f <- %2d %s",i,linear(@data[i][1]),@data[i][0],@data[i][1].to_s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment