✅ AND Gate Perceptorn

이 실습에서는 퍼셉트론(Perceptron) 알고리즘을 이용해 AND 게이트를 학습시키고, 학습 결과를 기반으로 입력에 대한 예측 값을 출력합니다.

퍼셉트론은 입력 값에 대해 가중치를 곱한 후, 바이어스를 더하고 활성화 함수(계단 함수)를 통해 출력을 결정하는 가장 기본적인 인공신경망 구조입니다.

import numpy as np
import matplotlib.pyplot as plt

class Perceptron:
    def __init__(self, input_size, lr=0.1, epochs=10):
        self.weights = np.zeros(input_size)
        self.bias = 0
        self.lr = lr
        self.epochs = epochs
        self.errors = []

    def activation(self, x):
        return np.where(x > 0, 1, 0)

    def predict(self, x):
        linear_output = np.dot(x, self.weights) + self.bias
        return self.activation(linear_output)

    def train(self, X, y):
        for epoch in range(self.epochs):
            total_error = 0
            for xi, target in zip(X, y):
                prediction = self.predict(xi)
                update = self.lr * (target - prediction)
                self.weights += update * xi
                self.bias += update
                total_error += int(update != 0.0)
            self.errors.append(total_error)
            print(f"Epoch {(epoch+1)}/{self.epochs}, Errors: {total_error}")

# AND 게이트 데이터
X_and = np.array([[0,0], [0,1], [1,0], [1,1]])
y_and = np.array([0, 0, 0, 1])

# 퍼셉트론 모델 훈련
ppn_and = Perceptron(input_size=2)
ppn_and.train(X_and, y_and)

# 예측 결과 확인
print("\\nAND Gate Test:")
for x in X_and:
    print(f"Input: {x}, Predicted Output: {ppn_and.predict(x)}")

학습 초반에는 오차가 있었지만, 6번째 에폭부터는 모든 데이터를 정확히 분류하게 되면서 오류가 0으로 수렴합니다. 이는 퍼셉트론이 AND 게이트와 같은 선형적으로 구분 가능한 문제를 잘 학습할 수 있음을 보여줍니다. 퍼셉트론이 학습한 모델은 모든 AND 게이트 입력에 대해 정확히 예측하고 있습니다.

image.png

경계 결정 시각화

퍼셉트론이 AND 게이트의 논리 연산을 어떻게 학습했는지, 그리고 입력 공간을 어떻게 구분하는지를 시각적으로 확인할 수 있습니다.

from matplotlib.colors import ListedColormap

def plot_decision_boundary(X, y, model):
    cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF'])
    cmap_bold = ListedColormap(['#FF0000', '#0000FF'])

    h = 0.02  # mesh grid 간격
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))

    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    plt.figure(figsize=(8, 6))
    plt.contourf(xx, yy, Z, cmap=cmap_light)

    # 실제 데이터 포인트 표시
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
                edgecolor='k', s=100, marker='o')
    plt.xlabel('Input 1')
    plt.ylabel('Input 2')
    plt.title('Perceptron Decision Boundary')
    plt.show()

# AND 게이트 결정 경계 시각화
plot_decision_boundary(X_and, y_and, ppn_and)

image.png

오류 시각화

퍼셉트론 학습에서 각 에폭(epoch)마다 발생한 오차(예측 실패 개수)를 시각화함으로써, 모델이 학습을 통해 얼마나 잘 수렴했는지를 확인할 수 있습니다.

# 오류 시각화
plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_and.errors) + 1), ppn_and.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (AND Gate)')
plt.grid(True)
plt.show()

image.png