Notice
Recent Posts
Recent Comments
Link
03-08 20:12
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Archives
Today
Total
관리 메뉴

AI 전문가가 되고싶은 사람

퍼셉트론 학습 알고리즘 구현 본문

머신러닝 교과서

퍼셉트론 학습 알고리즘 구현

Kimseungwoo0407 2024. 8. 3. 20:56

2-1 객체 지향 퍼셉트론 API

1. Perceptron 객체를 초기화한 후 fit 메서드로 데이터에서 학습하고, 별도의 predict 메서드로 예측을 만든다.

2.사용 패키지

3. 구현

학습률 eta(n)와 에포크 횟수(훈련 데이터셋을 반복하는 횟수) n_iter로 새로운 Perceptron 객체를 초기화한다.

import numpy as np

class Perceptron:
    def __init__(self, eta=0.01,n_iter=50, random_state=1):
        self.eta = eta
        self.n_iter = n_iter
        self.random_state = random_state

# fit 메서드에서 절편 self.b_를 0으로 초기화하고 self.w_ 가중치를 벡터 R^m으로 초기화한다.
# m은 데이터셋에 있는 차원 개수
    def fit(self, X, y):
        rgen = np.random.RandomState(self.random_state)
        # 초기 가중치 벡터는 표준편차가 0.01인 정규 분포에서 뽑은 랜덤한 작은 수를 담고있다.
        # 기술적으로 0으로 학습률을 초기화할 수 있다.
        # 0으로 초기화되면 결정 경계에 영향을 미치기 못하고 가중치 벡터의 방향이 아니라 크기에만 영향을 미친다.
        self.w_ = rgen.normal(loc=0.0, scale=0.01,
                              size = X.shape[1])
        self.b_ = np.float_(0.)
        self.errors_ = []

        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X,y):
                update= self.eta * (target - self.predict(xi))
                self.w_ += update * xi
                self.b_ += update
                errors += int(update != 0.0)
            # 에포크마다 self.errors_ 리스트에 잘못 분류된 횟수를 기록한다.
            # 나중에 훈련하는 동안 얼마나 퍼셉트론을 잘 수행했는지 분석 가능하다.
            self.errors_.append(errors)
        return self
        
    # 벡터 점곱 계산
    def net_input(self,X):
        return np.dot(X,self.w_) + self.b_
        
	# 클래스 레이블은 predict 메서드에서 예측
    # fit에서 훈련하는 동안 가중치를 업데이트하기 위해 predict 메서드를 호출하여 클래스 레이블에 대한 예측 얻는다.
    def predict(self, X):
        return np.where(self.net_input(X) >= 0.0, 1, 0)

 

2-2 붓꽃 데이터셋에서 퍼셉트론 훈련

퍼셉트론이 이진 분류기이기 때문에 붓꽃 데이터셋에서 두 개의 꽃 Setosa와 Versicolor만 사용하여 분류한다. 퍼셉트론 알고리즘도 다중 클래스 분류로 확장할 수 있다. 예를 들어 OvA 전략이 있다.

import os
import pandas as pd

try:
    s = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
    print('From URL:', s)
    df = pd.read_csv(s,
                     header=None,
                     encoding='utf-8')

except HTTPError:
    s = 'iris.data'
    print('From local Iris path:', s)
    df = pd.read_csv(s,
                     header=None,
                     encoding='utf-8')

df.tail()

 

1. 50개의 Iris-setosa와 50개의 Iris-versicolor 꽃에 해당하는 처음 100개의 클래스 레이블 추출

2. 클래스 레이블을 두 개의 정수 클래스 1(versicolor)과 0(setosa)으로 바꾼 후 벡터 y에 저장

3. 판다스 DataFrame의 values 속성은 넘파이 배열을 반환

4. 100개의 훈련 샘플에서 첫 번째 특성 열(꽃받침 길이)과 세 번째 특성 열(꽃잎 길이)을 추출하여 특성 행렬 X에 저장

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

# setosa와 versicolor를 선택합니다
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', 0, 1)

# 꽃받침 길이와 꽃잎 길이를 추출합니다
X = df.iloc[0:100, [0, 2]].values

# 산점도를 그립니다
plt.scatter(X[:50, 0], X[:50, 1],
            color='red', marker='o', label='Setosa')
plt.scatter(X[50:100, 0], X[50:100, 1],
            color='blue', marker='s', label='Versicolor')

plt.xlabel('Sepal length [cm]')
plt.ylabel('Petal length [cm]')
plt.legend(loc='upper left')

plt.show()

 

2차원 부분 공간에서 선형 결정 경계로 Setosa와 Versicolor 꽃을 구분하기 충분할 것 같다.

따라서 퍼셉트론 같은 선형 분류기가 이 데이터셋의 꽃을 분류할 수 있다.

퍼셉트론은 여섯 번째 에포크 이후에 수렴했고 훈련 샘플을 완벽하게 분류했다.

ppn = Perceptron(eta=0.1, n_iter=10)

ppn.fit(X, y)

plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of updates')

plt.show()

from matplotlib.colors import ListedColormap


def plot_decision_regions(X, y, classifier, resolution=0.02):

    # 마커와 컬러맵을 설정합니다
    markers = ('o', 's', '^', 'v', '<')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    lab = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    lab = lab.reshape(xx1.shape)
    plt.contourf(xx1, xx2, lab, alpha=0.3, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # 샘플의 산점도를 그립니다
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0],
                    y=X[y == cl, 1],
                    alpha=0.8,
                    c=colors[idx],
                    marker=markers[idx],
                    label=f'Class {cl}',
                    edgecolor='black')
plot_decision_regions(X, y, classifier=ppn)
plt.xlabel('Sepal length [cm]')
plt.ylabel('Petal length [cm]')
plt.legend(loc='upper left')