퍼셉트론 perceptron 이해하기 위한 AND
, NAND
, OR
, XOR
함수와 테스트 파이썬 코드
퍼셉트론(Perceptron)은 인공신경망의 가장 기본적인 형태로, 간단한 논리 게이트(AND, NAND, OR 등)는 단일 퍼셉트론으로 구현할 수 있지만, XOR은 하나의 퍼셉트론으로는 구현할 수 없습니다. XOR은 선형 분리가 불가능하기 때문에 다층 퍼셉트론(Multi-Layer Perceptron, MLP)이 필요합니다.
아래는 AND, NAND, OR, 그리고 XOR 논리 연산을 퍼셉트론 방식으로 구현한 예제입니다. XOR은 2개의 퍼셉트론 계층으로 구현합니다.
# 퍼셉트론 기반 논리 게이트 구현 (AND, NAND, OR, XOR)
def perceptron(x1, x2, weights, bias):
tmp = x1 * weights[0] + x2 * weights[1] + bias
return 1 if tmp > 0 else 0
def AND(x1, x2):
return perceptron(x1, x2, weights=[0.5, 0.5], bias=-0.7)
def NAND(x1, x2):
return perceptron(x1, x2, weights=[-0.5, -0.5], bias=0.7)
def OR(x1, x2):
return perceptron(x1, x2, weights=[0.5, 0.5], bias=-0.2)
def XOR(x1, x2):
s1 = NAND(x1, x2)
s2 = OR(x1, x2)
return AND(s1, s2)
# 테스트
def test_logic_gates():
inputs = [(0, 0), (0, 1), (1, 0), (1, 1), (0.2, 0.2), (0.8, 0.8)]
print("x1 x2 | AND NAND OR XOR")
print("--------------------------")
for x1, x2 in inputs:
and_result = AND(x1, x2)
nand_result = NAND(x1, x2)
or_result = OR(x1, x2)
xor_result = XOR(x1, x2)
print(f" {x1} {x2} | {and_result} {nand_result} {or_result} {xor_result}")
def test_step_function():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5.0, 5.0, 0.1)
def setp_function(x):
return np.where(x > 0, 1, 0)
y = setp_function(x)
plt.plot(x, y)
plt.title("Step Function")
plt.xlabel("x")
plt.ylabel("y(step function)")
plt.grid()
plt.show()
def test_sigmoid_function():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5.0, 5.0, 0.1)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
y = sigmoid(x)
plt.plot(x, y)
plt.title("Sigmoid Function")
plt.xlabel("x")
plt.ylabel("y(sigmoid function)")
plt.grid()
plt.show()
def test_relu_function():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5.0, 5.0, 0.1)
def relu(x):
return np.maximum(0, x)
# ReLU
y = relu(x)
plt.plot(x, y)
plt.title("relu Function")
plt.xlabel("x")
plt.ylabel("y")
plt.grid()
plt.show()
if __name__ == "__main__":
test_logic_gates()
test_step_function()
test_sigmoid_function()
test_relu_function()
수행결과
x1 x2 | AND NAND OR XOR
--------------------------
0 0 | 0 1 0 0
0 1 | 0 1 1 1
1 0 | 0 1 1 1
1 1 | 1 0 1 0