Skip to content

Instantly share code, notes, and snippets.

@sykwer
Last active November 21, 2017 20:44
Show Gist options
  • Save sykwer/b2ea2b700fdf0ed5b90a36eebb714ba4 to your computer and use it in GitHub Desktop.
Save sykwer/b2ea2b700fdf0ed5b90a36eebb714ba4 to your computer and use it in GitHub Desktop.
東大2年の簡単なパーセプトロンの課題
#! /usr/bin/env ruby
require "matrix"
# training data
v1 = [Vector[1, 3, 0], 1]
v2 = [Vector[1, 4, 3], 1]
v3 = [Vector[1, 6, 4], 1]
v4 = [Vector[1, 1, 2], 2]
v5 = [Vector[1, 3, 5], 2]
v6 = [Vector[1, 4, 6], 2]
all_data = [v1, v2, v3, v4, v5, v6]
# -> vector, bool
def learn(weights, data)
w1 = weights[0]
w2 = weights[1]
v = data[0]
label = data[1]
outputs = [v.dot(w1), v.dot(w2)]
success = !outputs[0].eql?(outputs[1]) && outputs.find_index(outputs.max).eql?(label - 1)
return [weights, true] if success
if (label == 1)
new_weights = [weights[0] + v, weights[1] - v]
elsif (label == 2)
new_weights = [weights[0] - v, weights[1] + v]
else
raise "wrong label"
end
return [new_weights, false]
end
# Let's learn!
epoch = 0
weights_trained = [Vector[1, 0, 0], Vector[1, 0, 0]]
loop do
never_failed = true
all_data.each do |data|
weights_trained, success = learn(weights_trained, data)
never_failed = false if !success
end
epoch += 1
break if never_failed
end
puts "epoch: #{epoch}"
puts weights_trained
@sykwer
Copy link
Author

sykwer commented Nov 21, 2017

上のコードで重みが出力されるので、そこから決定境界を求めればいい
問題は以下

2017-11-22 5 39 50

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment