Machine Learning Meetup Notes Ruby Zhao

From Noisebridge
Jump to: navigation, search
class ML
  @@weights = [0, 0, 0]

  def dot_product(a, b)
    [a, b].transpose.map { |e| e = e[0]*e[1] }.inject{|s, n| s += n}
  end

  def training_set
    [[[1, 0, 0], 1], [[1, 0, 1], 1], [[1, 1, 0], 1], [[1, 1, 1], 0]]
  end

  def weights
    @@weights
  end

  def threshold
    0.5
  end

  def learning_rate
    0.1
  end

  def perceive_all
    counter = 0
    while counter < 4
      counter = 0
      training_set.each do |set|
        counter += perceive(set[0], set[1])
      end
    end
    puts "final weights: " + weights.join(":")
  end

  def perceive(input, output)
    result = dot_product(input, weights) > threshold ? 1 : 0
    diff = result - output
    return 1 if diff == 0

    input.each_with_index do |inp, index|
      weights[index] += (-1 * diff * learning_rate) if inp != 0
    end

    0
  end
end
Personal tools