LoginSignup
1
1

More than 5 years have passed since last update.

[Ruby]機械学習②:パーセプトロン

Last updated at Posted at 2017-11-07

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する必要があった。
(numpypycallの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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1