🐬 ML & Data/🎫 라이트 λ¨Έμ‹ λŸ¬λ‹

[라이트 λ¨Έμ‹ λŸ¬λ‹] Session 6. μ‚¬μ΄ν‚·λŸ° μž…λ¬Έ!

darly213 2020. 2. 3. 20:35
728x90

 μ΄λ²ˆ μ„Έμ…˜μ—μ„œλŠ” μ‚¬μ΄ν‚·λŸ° 라이브러리λ₯Ό μ΄μš©ν•΄μ„œ νΌμ…‰νŠΈλ‘ μ„ ν›ˆλ ¨ν•΄λ΄„μœΌλ‘œμ¨ μ‚¬μ΄ν‚·λŸ°μ„ μ‹œμž‘ν•˜λ„λ‘ ν•˜κ² μŠ΅λ‹ˆλ‹€. 이번 μ„Έμ…˜λ„ μ „κ³Ό λ§ˆμ°¬κ°€μ§€λ‘œ μ €λŠ” Google Colab으둜 μ‹€μŠ΅ν•©λ‹ˆλ‹€. Colabμ—λŠ” 이미 μ‚¬μ΄ν‚·λŸ°μ΄ μ„€μΉ˜λ˜μ–΄μžˆμœΌλ―€λ‘œ λ³„λ„μ˜ μ„€μΉ˜μ—†μ΄ μ‚¬μš©ν•˜μ‹œλ©΄ λ©λ‹ˆλ‹€!

https://colab.research.google.com

 

Google Colaboratory

 

colab.research.google.com

1. 데이터 μ£Όμž…κ³Ό ν‘œμ€€ν™”

 μ΄λ²ˆ μ„Έμ…˜μ—μ„œλŠ” μ„Έμ…˜ 4와 5μ—μ„œ κ΅¬ν˜„ν•œ 것과 λΉ„μŠ·ν•œ νΌμ…‰νŠΈλ‘  λͺ¨λΈμ„ μ‚¬μš©ν•  κ²ƒμž…λ‹ˆλ‹€. μ‚¬μš©ν•  뢓꽃 데이터 셋은 이미 μ‚¬μ΄ν‚·λŸ°μ— ν¬ν•¨λ˜μ–΄μžˆμœΌλ―€λ‘œ, λ”°λ‘œ λ‹€μš΄λ°›μ„ ν•„μš”λŠ” μ—†μŠ΅λ‹ˆλ‹€. 

 κ½ƒ μƒ˜ν”Œ 쀑에 κ½ƒμž… 길이와 λ„ˆλΉ„λ₯Ό ν–‰λ ¬ X에, 꽃 ν’ˆμ’…μ„ 벑터 Y에 ν• λ‹Ήν•©λ‹ˆλ‹€.

from sklearn import datasets
import numpy as np

iris = datasets.load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
print('class label', np.unique(y))

 

np.uniqueν•¨μˆ˜λŠ” iris.target에 μžˆλŠ” μ„Έ 개의 뢓꽃 μ’…λ₯˜λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€. 결과둜 class label [0 1 2] λΌλŠ” λ‚΄μš©μ΄ λ‚˜μ˜€κ³ , κ½ƒμ˜ 라벨이 0κ³Ό 1κ³Ό 2λΌλŠ” 것을 확인할 수 있죠. 각각 Iris-setasa, Iris-versicolor, Iris-virginica μž…λ‹ˆλ‹€. μ‚¬μ΄ν‚·λŸ°μ˜ ν•¨μˆ˜μ™€ 클래슀 λ©”μ†Œλ“œλ“€μ€ λ¬Έμžμ—΄ ν˜•νƒœμ˜ 클래슀 λ ˆμ΄λΈ”λ“€μ„ λ‹€λ£° 수 μžˆμŠ΅λ‹ˆλ‹€. μ΄λ ‡κ²Œ λ‚˜λˆ„λŠ” 데에 μ •μˆ˜ν˜•νƒœ(0, 1, 2처럼)κ°€ ꢌμž₯λ˜λŠ” μ΄μœ λŠ” μ‹€μˆ˜λ₯Ό ν”Όν•  수 있고, λ©”λͺ¨λ¦¬ μ˜μ—­μ΄ μž‘κΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€.

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1, stratify = y)

print('label count of y: ', np.bincount(y))
print('label count of y_train: ', np.bincount(y_train))
print('label count of y_test: ', np.bincount(y_test))

 

μ‚¬μ΄ν‚·λŸ°μ˜ model_selection λͺ¨λ“ˆμ˜ train_test_split ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄ X와 y의 배열을 λžœλ€ν•˜κ²Œ λ‚˜λˆ„κ³ , 30%λŠ” ν…ŒμŠ€νŠΈ λ°μ΄ν„°λ‘œ, 70%λŠ” ν›ˆλ ¨ λ°μ΄ν„°λ‘œ λ‚˜λˆ„μ–΄μˆ©λ‹ˆλ‹€. 배열을 λžœλ€ν•˜κ²Œ λ‚˜λˆ„λŠ” μ΄μœ λŠ” κ°„λ‹¨ν•©λ‹ˆλ‹€. 배열을 μ„žμ§€μ•Šκ³  호둜둝 λŒλ €λ²„λ¦¬λ©΄ ν…ŒμŠ€νŠΈ λ°μ΄ν„°λŠ” setasa만으둜, ν›ˆλ ¨ λ°μ΄ν„°λŠ” λ‹€λ₯Έ 두 κ½ƒλ“€λ§ŒμœΌλ‘œ λ‚˜λ‰  μˆ˜κ°€ μžˆμŠ΅λ‹ˆλ‹€. 그럼 ν•™μŠ΅μ΄ μ œλŒ€λ‘œ 이루어지지 μ•Šκ² μ£ ? 

stratify = yλŠ” 계측화λ₯Ό μ˜λ―Έν•©λ‹ˆλ‹€. κ³„μΈ΅ν™”λŠ” train_test_split ν•¨μˆ˜κ°€ λ‚˜λˆ λ†“μ€ 클래슀 λ ˆμ΄λΈ” λΉ„μœ¨μ„ μž…λ ₯ 데이터 μ…‹κ³Ό λ™μΌν•˜κ²Œ λ§žμΆ”λŠ” κ³Όμ •μž…λ‹ˆλ‹€. numpy에 μžˆλŠ” bincountν•¨μˆ˜λ₯Ό μ΄μš©ν•˜λ©΄ 배열에 μžˆλŠ” κ°’μ˜ λ“±μž₯ 횟수λ₯Ό 확인할 수 μžˆμŠ΅λ‹ˆλ‹€. μœ„ μ½”λ“œλ₯Ό λŒλ €λ³΄μ„Έμš”!

이전 μ„Έμ…˜μ—μ„œ μ΄μ•ΌκΈ°ν–ˆλ˜ κ²ƒμ²˜λŸΌ μ΅œμ ν™” μ•Œκ³ λ¦¬μ¦˜μ€ νŠΉμ„± μŠ€μΌ€μΌμ„ μ‘°μ •ν•΄μ£Όμ–΄μ•Όν•©λ‹ˆλ‹€. 이 과정을 ν‘œμ€€ν™”λΌκ³  ν•©λ‹ˆλ‹€. μ•„λž˜ μ½”λ“œλ₯Ό μ΄μš©ν•΄μ„œ νŠΉμ„±μ„ ν‘œμ€€ν™”ν•΄λ΄…μ‹œλ‹€. 

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

 

processing λͺ¨λ“ˆμ—μ„œ standard scaler 클래슀λ₯Ό λ‘œλ“œν•œ λ‹€μŒ μƒˆλ‘œμš΄ 객체 standard scaler을 sc둜 ν• λ‹Ήν•©λ‹ˆλ‹€. μ΄λŠ” ν‘œκΈ°μ˜ κ°„νŽΈν™”λ₯Ό μœ„ν•œ μž‘μ—…μ΄κΈ°λ„ ν•©λ‹ˆλ‹€. fitλ©”μ†Œλ“œλ₯Ό μ΄μš©ν•΄μ„œ 각 νŠΉμ„± μ°¨μ›λ§ˆλ‹€ μƒ˜ν”Œ 평균과 ν‘œμ€€νŽΈμ°¨λ₯Ό κ³„μ‚°ν•˜κ³ , 이 두가지λ₯Ό transformμ—μ„œ ν›ˆλ ¨μ„ΈνŠΈ ν‘œμ€€ν™”λ₯Ό μ‹€μ‹œν•©λ‹ˆλ‹€. ν›ˆλ ¨κ³Ό ν…ŒμŠ€νŠΈ μ„ΈνŠΈμ˜ μƒ˜ν”Œμ΄ μ„œλ‘œ 같은 λΉ„μœ¨λ‘œ ν‘œμ€€ν™”ν•΄μ£Όμ£ .

2. ν›ˆλ ¨!

데이터 ν‘œμ€€ν™” 이후에 λ“œλ””μ–΄! νΌμ…‰νŠΈλ‘  λͺ¨λΈμ„ ν›ˆλ ¨μ‹œν‚΅λ‹ˆλ‹€. μ‚¬μ΄ν‚·λŸ° μ•Œκ³ λ¦¬μ¦˜μ€ λŒ€λΆ€λΆ„ OvR(one-versus-rest)방식을 μ±„ν‹±ν•˜μ—¬ 닀쀑뢄λ₯˜λ₯Ό μ§€μ›ν•©λ‹ˆλ‹€. μ•„λž˜ μ½”λ“œλŠ” μ„Έ 개의 뢓꽃 클래슀λ₯Ό ν•œ λ²ˆμ— μ•Œκ³ λ¦¬μ¦˜μ— λ„£μŠ΅λ‹ˆλ‹€.

from sklearn.linear_model import Perceptron

ppn = Perceptron(max_iter = 40, eta0 = 0.1, tol = 1e-3, random_state = 1)
ppn.fit(X_train_std, y_train)

 

μ‚¬μ΄ν‚·λŸ°μ— ν¬ν•¨λœ νΌμ…‰νŠΈλ‘ μ€ μ•žμ„  μ„Έμ…˜μ—μ„œ 직접 κ΅¬ν˜„ν•œ νΌμ…‰νŠΈλ‘ κ³Ό 거의 μœ μ‚¬ν•©λ‹ˆλ‹€. linear_modelμ—μ„œ νΌμ…‰νŠΈλ‘  클래슀λ₯Ό λ‘œλ“œν•œ λ‹€μŒ, ppn λ³€μˆ˜μ— νΌμ…‰νŠΈλ‘ μ„ λ‹΄μŒμœΌλ‘œμ¨ 객체럴 μƒμ„±ν•œ ν›„ fit λ©”μ„œλ“œλ₯Ό ν†΅ν•΄μ„œ νΌμ…‰νŠΈλ‘  λͺ¨λΈμ„ ν›ˆλ ¨ν•©λ‹ˆλ‹€. etaλŠ” ν•™μŠ΅λ₯ μ„, max_iter은 epochλ₯Ό λœ»νž™λ‹ˆλ‹€. tol은 μ’…λ£Œμ‘°κ±΄μ„ μ§€μ •ν•˜λ‚˜ μ΄λŠ” κ²½κ³ λ©”μ„Έμ§€λ₯Ό ν”Όν•˜κΈ° μœ„ν•¨μ΄λ―€λ‘œ ꡳ이 깊게 μ•Œ ν•„μš”λŠ” μ—†μŠ΅λ‹ˆλ‹€.

κ·Έ λ‹€μŒμ€ predict λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•΄μ„œ μ˜ˆμΈ‘μ„ λ§Œλ“€μ–΄λƒ…λ‹ˆλ‹€. μ½”λ“œλŠ” μ•„λž˜μ™€ κ°™μŠ΅λ‹ˆλ‹€.

y_pred = ppn.predict(X_test_std)
print('잘λͺ» λΆ„λ₯˜λœ μƒ˜ν”Œ 개수 : %d' %(y_test != y_pred).sum())

from sklearn.metrics import accuracy_score
print('정확도 : %.2f' %accuracy_score(y_test, y_pred))

이 경우 잘λͺ» λΆ„λ₯˜λœ μƒ˜ν”Œμ€ ν•˜λ‚˜κ°€ 되고, μ •ν™•λ„λŠ” 0.98, 98%κ°€ λ‚˜μ˜΅λ‹ˆλ‹€. μ‚¬μ΄ν‚·λŸ°μ˜ λΆ„λ₯˜κΈ°(classfier)λŠ” 정확도λ₯Ό κ³„μ‚°ν•˜λŠ” score λ©”μ†Œλ“œλ₯Ό κ°–κ³  μžˆμŠ΅λ‹ˆλ‹€. 이λ₯Ό μ΄μš©ν•˜λ©΄ μ•„λž˜μ™€ 같이도 μ“Έ 수 μžˆμŠ΅λ‹ˆλ‹€.

print('정확도 : %.2f' % ppn.score(X_test_std, y_test))

 

3. κ·Έλž˜ν”„μ™€ 결정경계λ₯Ό ν†΅ν•œ μ‹œκ°ν™”

μ•žμ„  μ„Έμ…˜μ—μ„œ λ§Œλ“  plot_decision_regions ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄μ„œ κ·Έλž˜ν”„λ₯Ό μ‹œκ°ν™”ν•˜λ„λ‘ ν•˜κ² μŠ΅λ‹ˆλ‹€. λ‹€λ₯Έ 점은 μ—¬κΈ°μ„œλŠ” μƒ˜ν”Œμ„ μž‘μ€ μ›μœΌλ‘œ ν‘œμ‹œν•˜λŠ” 것 λΏμž…λ‹ˆλ‹€. 

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt


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

    # λ§ˆμ»€μ™€ μ»¬λŸ¬λ§΅μ„ μ„€μ •ν•©λ‹ˆλ‹€.
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # κ²°μ • 경계λ₯Ό κ·Έλ¦½λ‹ˆλ‹€.
    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))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, 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=cl, 
                    edgecolor='black')

    # ν…ŒμŠ€νŠΈ μƒ˜ν”Œμ„ λΆ€κ°ν•˜μ—¬ κ·Έλ¦½λ‹ˆλ‹€.
    if test_idx:
        X_test, y_test = X[test_idx, :], y[test_idx]

        plt.scatter(X_test[:, 0],
                    X_test[:, 1],
                    c='',
                    edgecolor='black',
                    alpha=1.0,
                    linewidth=1,
                    marker='o',
                    s=100, 
                    label='test set')

 

μˆ˜μ •λœ ν•¨μˆ˜μ— ν‘œμ‹œν•œ ν…ŒμŠ€νŠΈ μƒ˜ν”Œ 인덱슀λ₯Ό μ•„λž˜μ™€ 같이 μ§€μ •ν•΄μ€λ‹ˆλ‹€. 

X_combined_std = np.vstack((X_train_std, X_test_std))
y_combined = np.hstack((y_train, y_test))

plot_decision_regions(X=X_combined_std, y=y_combined,
                      classifier=ppn, test_idx=range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')

plt.tight_layout()
plt.show()

κ·Έλ¦Ό 1. λ§Œλ“€μ–΄μ§„ κ·Έλž˜ν”„

 

μ΄λ ‡κ²Œ μœ„μ™€κ°™μ΄ 예쁜 μ„ ν˜•κ²°κ³„ κ·Έλž˜ν”„κΉŒμ§€ μ‚¬μ΄ν‚·λŸ°μ„ ν†΅ν•΄μ„œ μ™„μ„±ν•΄λ³΄μ•˜μŠ΅λ‹ˆλ‹€. μ•žμ—μ„œλ„ μ΄μ•ΌκΈ°ν–ˆλ“― λͺ¨λ“  μ½”λ“œλ₯Ό 이해할 ν•„μš”λŠ” μ—†μœΌλ‚˜, μ–ΈκΈ‰λœ ν•¨μˆ˜μ˜ μ“°μž„ μ •λ„λŠ” κΌ­ μ•Œμ•„λ‘μ‹œλŠ” 것을 μΆ”μ²œν•©λ‹ˆλ‹€! λ‹€μŒ μ‹œκ°„μ—λŠ” λ‘œμ§€μŠ€ν‹± νšŒκ·€λ₯Ό μ†Œκ°œν•˜κ³ , κ΅¬ν˜„ν•΄λ³΄λ„λ‘ ν•˜κ² μŠ΅λ‹ˆλ‹€! λ‹€μŒ μ‹œκ°„μ— λ΄¬μš”! :)

 

728x90