Last active
August 29, 2015 13:57
-
-
Save yuitest/9747263 to your computer and use it in GitHub Desktop.
Wikipedia に載ってた形式ニューロン(Threshold Logic Unit) をそのまま Python で書いた後に、ちょいちょい推敲してみる。
This file contains hidden or 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 python | |
from tlu import TLU | |
if __name__ == '__main__': | |
# training_sets from | |
# http://en.wikipedia.org/wiki/Perceptron#Example | |
threshold = 0.5 | |
learning_rate = 0.1 | |
weights = [0, 0, 0] | |
training_set = [ | |
(1, (1, 0, 0)), | |
(1, (1, 0, 1)), | |
(1, (1, 1, 0)), | |
(0, (1, 1, 1)), | |
] | |
tlu = TLU(threshold, weights) | |
while not tlu.train(training_set, learning_rate): | |
pass | |
print(tlu.dump()) |
This file contains hidden or 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
# coding: utf-8 | |
from itertools import izip | |
class TLU(object): | |
def __init__(self, threshold, weights): | |
self.threshold = threshold | |
self.weights = tuple(weights) | |
def fire(self, inputs): | |
t = sum(value * w for value, w in izip(inputs, self.weights)) | |
return self.threshold < t | |
def train1(self, desired, inputs, rate): | |
result = self.fire(inputs) | |
diff = desired - result | |
if diff == 0: | |
return True | |
diff_r = diff * rate | |
dw = (diff_r * v for v in inputs) | |
weights2 = (w + d for w, d in izip(self.weights, dw)) | |
self.weights = tuple(weights2) | |
return False | |
def train(self, trainingset, rate): | |
is_perfect = True | |
for desired, inputs in trainingset: | |
is_perfect &= self.train1(desired, inputs, rate) | |
return is_perfect | |
def dump(self): | |
return (self.threshold, self.weights) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment