728x90

차원 축소:

원본 데이터의 특성을 적은 수의 새로운 특성으로 변환하는 비지도 학습. 저장 공간을 줄이고 시각화 하기 좋음, 다른 알고리즘의 성능 향상

주성분 분석(Principal Component Analysis : PCA):

데이터에서 가장 분산이 큰 방향을 찾는 방법.( 이 방향을 주성분이라 한다) 일반적으로 주성분은 원본 데이터에 있는 특성 개수보다 작다.

설명된 분산:

주성분 분석에서 주성분이 얼마나 원본 데이터의 분산을 잘 나타내는지 기록한 것. 사이킷런의 PCA class는 주성분 개수나 설명된 분산의 비율을 지정하여 주성분 분석을 수행할 수 있다.

 

* 이미지를 예로 들면 모든 픽셀이 특성이 되는데 이를 모두 기록하기는 어렵다. 이들 특성 중 주성분을 분석하여 분산에 맞게 저장하는 방법을 학습한다. 또한 이렇게 저장된 내용으로 다시 원본 데이터에 가깝게 복구가 가능하다.

* 분산이 크다는 것은 data가 가장 멀리 퍼진 방향을 나타낸다. 점들이 직선에 가깝게 퍼져 있다면 이러한 직선이 data의 특성을 잘 나타낸다고 볼 수 있다.

 

PCA Class

!wget https://bit.ly/fruits_300_data -O fruits_300.npy
import numpy as np

fruits = np.load('fruits_300.npy')
fruits_2d = fruits.reshape(-1, 100*100)

from sklearn.decomposition import PCA

pca = PCA(n_components=50)
pca.fit(fruits_2d)

PCA(n_components=50)

PCA가 찾은 주성분이 componenctes_에 들어가 있다.

print(pca.components_.shape)

(50, 10000)

배열의 차원이 50이다.(주성분 50)

import matplotlib.pyplot as plt

def draw_fruits(arr, ratio=1):
    n = len(arr)    # n은 샘플 개수입니다
    # 한 줄에 10개씩 이미지를 그립니다. 샘플 개수를 10으로 나누어 전체 행 개수를 계산합니다. 
    rows = int(np.ceil(n/10))
    # 행이 1개 이면 열 개수는 샘플 개수입니다. 그렇지 않으면 10개입니다.
    cols = n if rows < 2 else 10
    fig, axs = plt.subplots(rows, cols, 
                            figsize=(cols*ratio, rows*ratio), squeeze=False)
    for i in range(rows):
        for j in range(cols):
            if i*10 + j < n:    # n 개까지만 그립니다.
                axs[i, j].imshow(arr[i*10 + j], cmap='gray_r')
            axs[i, j].axis('off')
    plt.show()
draw_fruits(pca.components_.reshape(-1, 100, 100))

주성분을 50으로 잡았으니 특성의 개수를 10,000에서 50으로 줄일 수 있다.

transform()을 이용하여 원본 데이터의 차원을 50으로 줄일 수 있다.

print(fruits_2d.shape)
fruits_pca = pca.transform(fruits_2d)
print(fruits_pca.shape)

(300, 10000)

(300, 50)

 

원본 데이터 재구성

fruits_inverse = pca.inverse_transform(fruits_pca)
print(fruits_inverse.shape)
fruits_reconstruct = fruits_inverse.reshape(-1, 100, 100)

for start in [0, 100, 200]:
    draw_fruits(fruits_reconstruct[start:start+100])
    print("\n")

줄어든 특성을 이용하여 다시 원본 데이터를 복구하였는데 거의 비슷한 결과를 볼 수 있다.

미분 후 적분한 것처럼 손실은 있다.

설명된 분산

print(np.sum(pca.explained_variance_ratio_))
plt.plot(pca.explained_variance_ratio_)
plt.show()

0.9214965686302707

50개의 주성분이 있으나 처음 10개의 주성분이 대부분의 분산을 표현하고 있다.

다른 알고리즘과 함께 사용하기

from sklearn.linear_model import LogisticRegression

lr = LogisticRegression()

target = np.array([0] * 100 + [1] * 100 + [2] * 100)

from sklearn.model_selection import cross_validate

scores = cross_validate(lr, fruits_2d, target)
print(np.mean(scores['test_score']))
print(np.mean(scores['fit_time']))

0.9966666666666667 : test score

1.5750249862670898 : fit time

scores = cross_validate(lr, fruits_pca, target)
print(np.mean(scores['test_score']))
print(np.mean(scores['fit_time']))

1.0 : 50개의 주성분으로 분석했을 때 정확도가 100%로 나왔다

0.025466299057006835 : fit time 역시 엄청 줄었다.

pca = PCA(n_components=0.5)
pca.fit(fruits_2d)

PCA(n_components=0.5)

처음에는 주성분의 개수를 50개로 지정했는데 분산의 50%가 채워질 때까지 주성분의 개수를 늘리도록 변경하였다.

이렇게 변경한 다음 주성분의 개수가 몇개나 필요한 지 확인해보자.

print(pca.n_components_)

2

두개의 주성분이면 충분하다고 한다.

fruits_pca = pca.transform(fruits_2d)
print(fruits_pca.shape)

(300, 2)

scores = cross_validate(lr, fruits_pca, target)
print(np.mean(scores['test_score']))
print(np.mean(scores['fit_time']))

0.9933333333333334 : test score

0.036731719970703125 : fit time

특성을 두개만 사용해도 99.3%의 정확도를 나타낸다.

from sklearn.cluster import KMeans

km = KMeans(n_clusters=3, random_state=42)
km.fit(fruits_pca)

KMeans(n_clusters=3, random_state=42)

print(np.unique(km.labels_, return_counts=True))

(array([0, 1, 2], dtype=int32), array([110, 99, 91]))

for label in range(0, 3):
    draw_fruits(fruits[km.labels_ == label])
    print("\n")

for label in range(0, 3):
    data = fruits_pca[km.labels_ == label]
    plt.scatter(data[:,0], data[:,1])
plt.legend(['apple', 'banana', 'pineapple'])
plt.show()

두개만 가지고 분류했는데 분산이 잘 이루어져 있다.

파인애플과 사과는 경계가 거의 붙어있어 혼동이 있을 수 있다.

(그런데 바나나는 왜 섞여 들어간거지?)

728x90

+ Recent posts