Last active
February 1, 2022 23:01
-
-
Save SealtielFreak/7817ff13fd7627fa1c2c1e7e7ecca62c to your computer and use it in GitHub Desktop.
IA on Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
=begin | |
Perceptron simple with self-learning | |
Demonstration of an OR gate programmed in Ruby | |
with a simple perceptron | |
=end | |
inputs = [[-1, -1], [-1, 1], [1, -1], [1, 1]] | |
answares = [-1, -1, -1, 1] | |
weigth = Array.new(inputs.first.length, 0) | |
bias = 0 | |
step = 1 | |
umbral = nil | |
module Perceptron | |
def activation(x, umbral = nil) | |
unless umbral.nil? | |
return 1 if x > umbral | |
else | |
return 1 if x >= 0 | |
end | |
-1 | |
end | |
def error_r(waiting, output, r) | |
(waiting - output) * r | |
end | |
def neuron_process(input, weigth, bias, umbral = nil) | |
activation Array.new(input.length) { |i| input[i] * weigth[i] }.sum + bias, umbral | |
end | |
def exercise(input, weigth, umbral, answare, error) | |
weigth.length.times { |i| weigth[i] += error * input[i] } | |
[weigth, umbral + error] | |
end | |
end | |
def time_elapsed(&block) | |
firts = Time.now | |
block.call | |
Time.now - firts | |
end | |
def bar(n = 80, dec = "-") | |
puts dec * n | |
end | |
def title_bar(title = "", dec = "-") | |
puts dec * 20 + title + dec * (60 - title.length) | |
end | |
raise 'diferent length' unless inputs.length == answares.length | |
include Perceptron | |
found = false | |
attemps = 0 | |
title_bar "setup" | |
puts "inputs: #{inputs}" | |
puts "answares: #{answares}" | |
title_bar "init traiding" | |
time = time_elapsed do | |
100.times do |i| | |
outputs = [] | |
attemps = i | |
answares.length.times do |i| | |
outputs[i] = neuron_process(inputs[i], weigth, bias, umbral) | |
error = error_r(answares[i], outputs[i], step) | |
weigth, bias = exercise(inputs[i], weigth, bias, answares[i], error) if error != 0.0 | |
end | |
found = true if outputs == answares | |
break if found | |
end | |
end | |
puts "Time: #{time}'s" | |
title_bar "results" | |
puts "Times training: #{attemps}" | |
weigth.length.times { |i| puts "w[#{i}] = #{weigth[i]}" } | |
puts "bias = #{bias}" | |
title_bar "testing" | |
inputs.length.times do |i| | |
puts "input[#{i}]: #{inputs[i]} = #{neuron_process(inputs[i], weigth, bias)}" | |
end | |
title_bar "results" | |
if found | |
puts "Success" | |
else | |
puts "Failure" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment