AI/머신러닝 - 예제

[머신러닝 - 예제] 손글씨 데이터셋 - 서포트 벡터머신(SVM)

caramel-bottle 2023. 12. 28.

1. digits

digits 데이터셋은 사이킷런에서 제공한다.

 

scikit learn의 digits dataset은 UCL ML hand-written digits datasets의 copy라고 한다.

https://archive.ics.uci.edu/dataset/80/optical+recognition+of+handwritten+digits

 

UCI Machine Learning Repository

This dataset is licensed under a Creative Commons Attribution 4.0 International (CC BY 4.0) license. This allows for the sharing and adaptation of the datasets for any purpose, provided that the appropriate credit is given.

archive.ics.uci.edu


2. dataset 불러오기

from sklearn.datasets import load_digits
import matplotlib.pyplot as plt

# dataset 객체 만들기
digits = load_digits()

2-1. DESCR

# 요약 정보
print(digits['DESCR'])

output>>

.. _digits_dataset:

Optical recognition of handwritten digits dataset
--------------------------------------------------

**Data Set Characteristics:**

    :Number of Instances: 1797
    :Number of Attributes: 64
    :Attribute Information: 8x8 image of integer pixels in the range 0..16.
    :Missing Attribute Values: None
    :Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)
    :Date: July; 1998

This is a copy of the test set of the UCI ML hand-written digits datasets
https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits

The data set contains images of hand-written digits: 10 classes where
each class refers to a digit.

Preprocessing programs made available by NIST were used to extract
normalized bitmaps of handwritten digits from a preprinted form. From a
total of 43 people, 30 contributed to the training set and different 13
to the test set. 32x32 bitmaps are divided into nonoverlapping blocks of
4x4 and the number of on pixels are counted in each block. This generates
an input matrix of 8x8 where each element is an integer in the range
0..16. This reduces dimensionality and gives invariance to small
distortions.

For info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.
T. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.
L. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469,
1994.

.. topic:: References

  - C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their
    Applications to Handwritten Digit Recognition, MSc Thesis, Institute of
    Graduate Studies in Science and Engineering, Bogazici University.
  - E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.
  - Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.
    Linear dimensionalityreduction using relevance weighted LDA. School of
    Electrical and Electronic Engineering Nanyang Technological University.
    2005.
  - Claudio Gentile. A New Approximate Maximal Margin Classification
    Algorithm. NIPS. 2000.

2-2. data

# 'data' value 확인
data = digits['data']
data.shape

output>>

(1797, 64)

 

64개의 데이터는 8 X 8의 픽셀 이미지를 의미한다. 총 1797개의 이미지가 있다.


2-3. target

target = digits['target']
target.shape

output>>

(1797,)

 

정답 데이터는 총 1797개로 0부터 9까지의 숫자이다.


3. 데이터 시각화

# 여러개의 plot을 출력하기 위해 subplots 2x5
fig, axes = plt.subplots(2, 5, figsize=(14, 8))

for i , ax in enumerate(axes.flatten()):
    ax.imshow(data[i].reshape((8, 8)), cmap='gray')
    ax.set_title(target[i])

 

axes는 서브플롯의 축 배열이다. 2D형태의 배열이므로 flatten() 메서드를 사용하여 평탄화를 해준다음 반복문을 통해 각각의 축에 데이터를 출력한다.

 

reshap()을 통해 64개의 1D 배열을 다시 8 x 8 2D 배열로 변환하여 출력한다.

output>>

출력된 데이터를 보니 흐릿하지만 숫자로 보인다.


4. 정규화

digits의 data는 0이상의 숫자들로 이루어져있다.

print(data[1])

output>>

array([ 0.,  0.,  0., 12., 13.,  5.,  0.,  0.,  0.,  0.,  0., 11., 16.,
        9.,  0.,  0.,  0.,  0.,  3., 15., 16.,  6.,  0.,  0.,  0.,  7.,
       15., 16., 16.,  2.,  0.,  0.,  0.,  0.,  1., 16., 16.,  3.,  0.,
        0.,  0.,  0.,  1., 16., 16.,  6.,  0.,  0.,  0.,  0.,  1., 16.,
       16.,  6.,  0.,  0.,  0.,  0.,  0., 11., 16., 10.,  0.,  0.])

 

0부터 16의 숫자 데이터로 이루어져 있는 것을 알 수 있다.

 

같은 형태의 여러 데이터를 다룰 때 0과 1사이의 숫자를 사용하는 것이 속도가 빠르고 좋다.

 

0과 1사이의 숫자로 변환하는 것을 스케일링(Scaling)이라고 부르고 이 과정을 정규화(Normalization)라고 부른다.

 

2023.12.28 - [분류 전체보기] - [머신러닝] 스케일링(Scaling), 정규화(Normalization), 표준화(Standardization)

 

[머신러닝] 스케일링(Scaling), 정규화(Normalization), 표준화(Standardization)

정규화(Normalization)와 표준화(Standardization)는 머신러닝에서 데이터 전처리 과정에 사용되는 기법이다. 데이터의 스케일을 조정하여 모델의 학습이나 예측에 미치는 영향을 최소화하고, 모델의 성

caramelbottle.tistory.com

# scaler 객체 생성
scaler = MinMaxScaler()

# fit_transform()을 사용하여 데이터 변환
scaled = scaler.fit_transform(data)

print(scaled[1])

output>>

[0.         0.         0.         0.75       0.8125     0.3125
 0.         0.         0.         0.         0.         0.6875
 1.         0.5625     0.         0.         0.         0.
 0.1875     0.9375     1.         0.375      0.         0.
 0.         0.46666667 0.9375     1.         1.         0.125
 0.         0.         0.         0.         0.0625     1.
 1.         0.1875     0.         0.         0.         0.
 0.0625     1.         1.         0.375      0.         0.
 0.         0.         0.0625     1.         1.         0.375
 0.         0.         0.         0.         0.         0.6875
 1.         0.625      0.         0.        ]

5. 데이터 분리

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(scaled, target, test_size=0.2, random_state=2023)
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)

output>>

(1437, 64) (1437,)
(360, 64) (360,)

6. Support Vector Machine(SVM)

  • 두 클래스로부터 최대한 멀리 떨어져 있는 결정경계를 찾는 분류기
  • 특정 조건을 만족하는 동시에 클래스를 분류하는 것을 목표로 함

로지스틱 회귀, SVM은 이진 분류만 가능하다. 하지만 OvR, OvO 전략을 사용하여 다중 클래스 분류를 가능하게 하는 기법이 있다.

 

아래에서 사용한 SVC는 decision_function_shape 값이 기본적으로 'ovr'로 되어있어 One vs Rest 기법으로 다중 분류가 가능하다.

from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

model = SVC()

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

accuracy_score(y_test, y_pred)

output>>

0.9916666666666667

6-1. 결과 시각화

fig, axes = plt.subplots(2, 5, figsize=(14, 8))

for i , ax in enumerate(axes.flatten()):
    ax.imshow(X_test[i].reshape((8, 8)), cmap='gray')
    ax.set_title(f'Label: {y_test[i]}, Pred: {y_pred[i]}')

output>>


끝내며

 

SVC나 로지스틱 회귀도 다중 분류가 가능하다(OvR, OvR)

 

SVC에 따로 decision_function_shape 을 설정하지 않으면 OvR이 적용된다.

댓글