Skip to content

Instantly share code, notes, and snippets.

@peterc
Created June 7, 2023 20:30
Show Gist options
  • Save peterc/84e9c5b463fd832a337bc3c7c5677ad6 to your computer and use it in GitHub Desktop.
Save peterc/84e9c5b463fd832a337bc3c7c5677ad6 to your computer and use it in GitHub Desktop.
Basic implementation of a perceptron in Ruby
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