Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env ruby
require "matrix"
class SimplePerceptron
def initialize(r = 0.5, v = 0)
@r = r
@v = v
@w_v = Vector[]
end
def step(x)
@v <= x ? 1 : 0
end
def add_bias(vec)
Vector.elements(vec.to_a() << 1)
end
def del_bias(vec)
v = vec.to_a()
v.pop()
return v
end
def init_w(n)
random = Random.new
array = []
n.times do
array.push(random.rand(-1.0..1.0))
end
@w_v = Vector.elements(array)
end
def fit(x_vs, ys)
init_w(x_vs[0].length + 1)
while ys != x_vs.map{|x_v| predict(x_v)} do
x_vs.zip(ys).each do |x_v, y|
@w_v = @w_v + @r * (y - predict(x_v)) * Vector.elements(add_bias(x_v))
del_bias(x_v)
end
end
end
def predict(x_v)
add_bias(x_v)
re = step(@w_v.inner_product(x_v))
del_bias(x_v)
return re
end
end
def main()
x_train = [[1, 1], [1, 0], [0, 1], [0, 0]]
y_train = [1, 1, 1, 0] # OR
sp = SimplePerceptron.new
sp.fit(x_train, y_train)
x_train.each do |x|
puts sp.predict(x)
end
end
if __FILE__ == $0
main()
end
#!/usr/bin/env ruby
require 'test/unit'
require './perceptron.rb'
class TC_SimplePerceptron < Test::Unit::TestCase
def setup
@obj = SimplePerceptron.new
end
def test_step
assert_equal(1, @obj.step(1) )
assert_equal(0, @obj.step(-2) )
end
def test_add_bias
assert_equal(Vector[1, 2, 3, 1], @obj.add_bias(Vector[1,2,3]))
end
def test_del_bias
assert_equal([1, 2, 3], @obj.del_bias(Vector[1,2,3,1]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.