Last active
November 21, 2017 20:44
-
-
Save sykwer/b2ea2b700fdf0ed5b90a36eebb714ba4 to your computer and use it in GitHub Desktop.
東大2年の簡単なパーセプトロンの課題
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/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
上のコードで重みが出力されるので、そこから決定境界を求めればいい
問題は以下