Ruby
実装
class Perceptron
def and(x1,x2)
w1,w2,theta = 0.5, 0.5, -0.7
tmp = x1 * w1 + x2 * w2 + theta
if tmp <= 0
0
else
1
end
end
def nand(x1,x2)
w1,w2,theta = -0.5, -0.5, 0.7
tmp = x1 * w1 + x2 * w2 + theta
if tmp <= 0
0
else
1
end
end
def or(x1,x2)
w1,w2,theta = 0.5, 0.5, 0.0
tmp = x1 * w1 + x2 * w2 + theta
if tmp <= 0
0
else
1
end
end
def xor(x1,x2)
s1 = self.nand(x1,x2)
s2 = self.or(x1,x2)
y = self.and(s1,s2)
end
end
Ruby with Numpy
実装
require 'numpy'
class Nperceptron
attr_reader :np
def initialize
@np = Numpy
end
def and(x1,x2)
x = np.array([x1,x2])
w = np.array([0.5,0.5])
b = -0.7
tmp = (np.sum(x * w) + b).to_f
if tmp <= 0
0
else
1
end
end
def nand(x1,x2)
x = np.array([x1,x2])
w = np.array([-0.5,-0.5])
b = 0.7
tmp = (np.sum(x * w) + b).to_f
if tmp <= 0
0
else
1
end
end
def or(x1,x2)
x = np.array([x1,x2])
w = np.array([0.5,0.5])
b = 0.0
tmp = (np.sum(x * w) + b).to_f
if tmp <= 0
0
else
1
end
end
def xor(x1,x2)
s1 = self.nand(x1,x2)
s2 = self.or(x1,x2)
y = self.and(s1,s2)
end
end
考察
・本筋とは関係ないけれど、@np.sum(x * w) + b
がrubyのクラスではObjectでありFloatではなかったので、to_f
する必要があった。
(numpy
やpycall
のgemのバージョンが変わることで変わるかもしれないけど、参考までに)
def what_is_class
np_array = np.array([0.5,0.5])
sum = np.sum(np_array * np_array)
puts "np: #{np.class}" #=> Module
puts "np_array: #{np_array.class}" #=> <class 'numpy.ndarray'>
puts "sum: #{sum.class}" #=> Object
end