Created
June 7, 2023 20:30
-
-
Save peterc/84e9c5b463fd832a337bc3c7c5677ad6 to your computer and use it in GitHub Desktop.
Basic implementation of a perceptron in 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
class Perceptron | |
def initialize(inputs, bias = 0.0) | |
@weights = Array.new(inputs.keys.first.size) { rand } | |
@inputs = inputs | |
@bias = bias | |
end | |
def run(inputs) | |
z = inputs.zip(@weights).map { |i, w| i * w }.reduce(:+) + @bias | |
1.0 / (1.0 + Math.exp(-z)) | |
end | |
def learn(learning_rate) | |
@inputs.each do |i, output| | |
y = run(i) | |
error = y - output | |
@weights = @weights.zip(i).map { |w, i| w - learning_rate * error * i } | |
@bias -= learning_rate * error | |
end | |
end | |
def train(iterations = 1000, learning_rate = 0.1) | |
iterations.times do | |
learn(learning_rate) | |
end | |
end | |
def to_s | |
@inputs.map { |i, j| | |
"#{i} => #{run(i).round}" | |
}.join("\n") | |
end | |
end | |
# Create perceptrons for AND, OR and NOT logic functions | |
and_perceptron = Perceptron.new( | |
[1, 1] => 1, | |
[1, 0] => 0, | |
[0, 1] => 0, | |
[0, 0] => 0 | |
) | |
and_perceptron.train | |
puts and_perceptron | |
puts "-----" | |
or_perceptron = Perceptron.new( | |
[1, 1] => 1, | |
[1, 0] => 1, | |
[0, 1] => 1, | |
[0, 0] => 0 | |
) | |
or_perceptron.train | |
puts or_perceptron | |
puts "-----" | |
not_perceptron = Perceptron.new( | |
[1] => 0, | |
[0] => 1 | |
) | |
not_perceptron.train | |
puts not_perceptron |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment