Perceptron:Example
Python으로 구현한 Perceptron클래스를 사용하여 논리 회로 (Logic gate)를 구현한다.
About
And_gate_graph.png
위 그림의 그래프를 사용하여 1차 방정식을 만든다.
$$ \begin{eqnarray} \mbox{output} & = & \left{ \begin{array}{ll} 0 & \mbox{if } (-x - y + 1.5) \leq \mbox{ threshold} \ 1 & \mbox{if } (-x - y + 1.5) > \mbox{ threshold} \end{array} \right. \end{eqnarray} $$
Python source code
# -*- coding: utf-8 -*-
class Perceptron(object):
def __init__(self):
self.param = []
self.weight = []
self.threshold = 0
pass
def setInput(self, param):
self.param = param
def setWeight(self, weight):
self.weight = weight
def setThreshold(self, threshold=0):
self.threshold = threshold
def run(self):
result = 0
index = 0
for cursor in self.param:
result += float(cursor) * float(self.weight[index])
index += 1
if result > self.threshold:
return True
else:
return False
class NotAndGate(Perceptron):
def __init__(self, x, y):
if x is True or x == 1:
exchange_x = 1
else:
exchange_x = 0
if y is True or y == 1:
exchange_y = 1
else:
exchange_y = 0
self.setWeight([-1, -1, 1])
self.setInput([exchange_x, exchange_y, 1.5])
self.setThreshold(0)
def __str__(self):
return '{} {} -> {}'.format(self.param[0], self.param[1], self.run())
def getNotAndGate(x, y):
gate = NotAndGate(x, y)
return gate.run()
def getNotGate(x):
return getNotAndGate(x, x)
def getAndGate(x, y):
return getNotGate(getNotAndGate(x, y))
def getOrGate(x, y):
return getNotAndGate(getNotAndGate(x, x), getNotAndGate(y, y))
def getExclusiveOrGate(x, y):
z = getNotAndGate(x, y)
return getNotAndGate(getNotAndGate(x, z), getNotAndGate(y, z))
def printResult(func, x, y):
print '{} {} -> {}'.format(x, y, func(x, y))
def printResult2(msg, func):
print msg
printResult(func, 0, 0)
printResult(func, 1, 0)
printResult(func, 0, 1)
printResult(func, 1, 1)
if __name__ == '__main__':
printResult2('NAND GATE:', getNotAndGate)
printResult2('AND GATE:', getAndGate)
printResult2('OR GATE:', getOrGate)
printResult2('XOR GATE:', getExclusiveOrGate)
Output
출력은 아래와 같다.
NAND GATE:
0 0 -> True
1 0 -> True
0 1 -> True
1 1 -> False
AND GATE:
0 0 -> False
1 0 -> False
0 1 -> False
1 1 -> True
OR GATE:
0 0 -> False
1 0 -> True
0 1 -> True
1 1 -> True
XOR GATE:
0 0 -> False
1 0 -> True
0 1 -> True
1 1 -> False