Home > Study > AI Algorithm Structure > Day3: Perceptron_MLP

Day3: Perceptron_MLP

#


๐Ÿ“Œ Perceptron์ด๋ž€?


  • 1957๋…„ ํ”„๋žญํฌ ๋กœ์  ๋ธŒ๋ผํŠธ๊ฐ€ ๊ณ ์•ˆํ•œ ์ตœ์ดˆ์˜ ์ธ๊ณต์‹ ๊ฒฝ๋ง ๋ชจ๋ธ ์ค‘ ํ•˜๋‚˜.
  • ์ƒ๋ฌผํ•™์  ๋‰ด๋Ÿฐ์„ ์ˆ˜ํ•™์ ์œผ๋กœ ๋ชจ๋ธ๋งํ•œ ์ธ๊ณต ๋‰ด๋Ÿฐ์œผ๋กœ, ์—ฌ๋Ÿฌ ์ž…๋ ฅ ์‹ ํ˜ธ๋ฅผ ๋ฐ›์•„ ๊ฐ๊ฐ์˜ ๊ฐ€์ค‘์น˜๋ฅผ ๊ณฑํ•œ ํ›„ ์ด๋ฅผ ํ•ฉ์‚ฐํ•˜์—ฌ, ํ™œ์„ฑํ™” ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๋‹จ์ผ ์‹ ํ˜ธ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
  • ํผ์…‰ํŠธ๋ก ์˜ ์ถœ๋ ฅ์€ ์‹ ํ˜ธ ์œ ๋ฌด (1 ๋˜๋Š” 0)๋กœ ํ‘œํ˜„๋œ๊ณ , ์ด์ง„ ๋ถ„๋ฅ˜ ๋ฌธ์ œ ํ•ด๊ฒฐ์— ํšจ๊ณผ์ ์ด๋‹ค.

๐Ÿ“ Perceptron AND_GATE ์‹ค์Šต


๐Ÿ” 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 x1, target in zip(X, y):
                prediction = self.predict(x1)
                update = self.lr * (target - prediction)
                self.weights += update * x1
                self.bias += update
                total_error += int(update != 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)}")

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” AND ๊ฒŒ์ดํŠธ ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”

from matplotlib.colors import ListedColormap

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

    h = .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)

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” ์˜ค๋ฅ˜ ์‹œ๊ฐํ™”

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()

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ“ Perceptron OR_GATE ์‹ค์Šต


๐Ÿ” OR ๊ฒŒ์ดํŠธ ๋ชจ๋ธ ํ›ˆ๋ จ ํ›„ ๊ฒฐ๊ณผ ํ™•์ธ

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 x1, target in zip(X, y):
                prediction = self.predict(x1)
                update = self.lr * (target - prediction)
                self.weights += update * x1
                self.bias += update
                total_error += int(update != 0)
            self.errors.append(total_error)
            print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")

# OR ๊ฒŒ์ดํŠธ ๋ฐ์ดํ„ฐ
X_or = np.array([[0,0],[0,1],[1,0],[1,1]])
y_or = np.array([0,1,1,1])

# ํผ์…‰ํŠธ๋ก  ๋ชจ๋ธ ํ›ˆ๋ จ
ppn_or = Perceptron(input_size=2)
ppn_or.train(X_or, y_or)

# ์˜ˆ์ธก ๊ฒฐ๊ณผ ํ™•์ธ
print("\nOR Gate Test:")
for x in X_or:
    print(f"Input: {x}, Predicted Output: {ppn_or.predict(x)}")

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” OR ๊ฒŒ์ดํŠธ ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”

from matplotlib.colors import ListedColormap

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

    h = .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()

# OR ๊ฒŒ์ดํŠธ ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”
plot_decision_boundary(X_or, y_or, ppn_or)

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” ์˜ค๋ฅ˜ ์‹œ๊ฐํ™”

plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_or.errors) + 1), ppn_or.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (OR Gate)')
plt.grid(True)
plt.show()

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ“ Perceptron NAND_GATE ์‹ค์Šต


๐Ÿ” NAND ๊ฒŒ์ดํŠธ ๋ชจ๋ธ ํ›ˆ๋ จ ํ›„ ๊ฒฐ๊ณผ ํ™•์ธ

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 x1, target in zip(X, y):
                prediction = self.predict(x1)
                update = self.lr * (target - prediction)
                self.weights += update * x1
                self.bias += update
                total_error += int(update != 0)
            self.errors.append(total_error)
            print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")

# NAND ๊ฒŒ์ดํŠธ ๋ฐ์ดํ„ฐ
X_nand = np.array([[0,0],[0,1],[1,0],[1,1]])
y_nand = np.array([1,1,1,0])

# ํผ์…‰ํŠธ๋ก  ๋ชจ๋ธ ํ›ˆ๋ จ
ppn_nand = Perceptron(input_size=2)
ppn_nand.train(X_nand, y_nand)

# ์˜ˆ์ธก ๊ฒฐ๊ณผ ํ™•์ธ
print("\nNAND Gate Test:")
for x in X_nand:
    print(f"Input: {x}, Predicted Output: {ppn_nand.predict(x)}")

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” NAND ๊ฒŒ์ดํŠธ ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”

from matplotlib.colors import ListedColormap

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

    h = .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()

# NAND ๊ฒŒ์ดํŠธ ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”
plot_decision_boundary(X_nand, y_nand, ppn_nand)

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” ์˜ค๋ฅ˜ ์‹œ๊ฐํ™”

plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_or.errors) + 1), ppn_or.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (OR Gate)')
plt.grid(True)
plt.show()

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ“ Perceptron XOR_GATE ์‹ค์Šต


๐Ÿ” XOR ๊ฒŒ์ดํŠธ ๋ชจ๋ธ ํ›ˆ๋ จ ํ›„ ๊ฒฐ๊ณผ ํ™•์ธ

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 x1, target in zip(X, y):
                prediction = self.predict(x1)
                update = self.lr * (target - prediction)
                self.weights += update * x1
                self.bias += update
                total_error += int(update != 0)
            self.errors.append(total_error)
            print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")

# XOR ๊ฒŒ์ดํŠธ ๋ฐ์ดํ„ฐ
X_xor = np.array([[0,0],[0,1],[1,0],[1,1]])
y_xor = np.array([0,1,1,0])

# ํผ์…‰ํŠธ๋ก  ๋ชจ๋ธ ํ›ˆ๋ จ
ppn_xor = Perceptron(input_size=2)
ppn_xor.train(X_xor, y_xor)

# ์˜ˆ์ธก ๊ฒฐ๊ณผ ํ™•์ธ
print("\nXOR Gate Test:")
for x in X_xor:
    print(f"Input: {x}, Predicted Output: {ppn_xor.predict(x)}")

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” XOR ๊ฒŒ์ดํŠธ ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”

from matplotlib.colors import ListedColormap

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

    h = .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()

# XOR ๊ฒŒ์ดํŠธ ๊ฒฐ์ • ๊ฒฝ๊ณ„ ์‹œ๊ฐํ™”
plot_decision_boundary(X_xor, y_xor, ppn_xor)

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ


๐Ÿ” ์˜ค๋ฅ˜ ์‹œ๊ฐํ™”

plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_or.errors) + 1), ppn_or.errors, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs (OR Gate)')
plt.grid(True)
plt.show()

๐Ÿ’ก ์ถœ๋ ฅ ๊ฒฐ๊ณผ

๐Ÿšจ ๋‹จ์ธต Perceptron์˜ ํ•œ๊ณ„์ 

  • XOR GATE๋Š” ํผ์…‰ํŠธ๋ก ์œผ๋กœ ํ•™์Šต์ด ๋˜์ง€ ์•Š๋Š” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค.
  • ํผ์…‰ํŠธ๋ก ์€ ์ง์„  ํ•˜๋‚˜๋กœ โ—์™€ โ—‹๋ฅผ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ์–ด์•ผ ํ•™์Šต์ด ๋œ๋‹ค.
  • ํ•˜์ง€๋งŒ XOR์€ ์ง์„  ํ•˜๋‚˜๋กœ๋Š” ์ ˆ๋Œ€ โ—์™€ โ—‹๋ฅผ ๋‚˜๋ˆŒ ์ˆ˜ ์—†๋‹ค.