Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
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
Tags
more
Archives
Today
Total
관리 메뉴

Silver bullet

Dimensionality Reduction & PCA 본문

AI/AI

Dimensionality Reduction & PCA

밀크쌀과자 2024. 7. 11. 15:45

PCA (Principal Companent Analysis, 주성분 분석) - 비지도 학습

: 차원 축소를 통해 최소 차원의 정보로 원래 차원 정보를 모사(approximate)하는 알고리즘

 

- 차원 축소(Dimension Reduction) : 고차원 벡터에서 일부 차원의 값을 모두 0으로 만들어 저차원 벡터로 줄이는 것

- 이 때, 원래의 고차원 벡터의 특성을 최대한 살리기 위해 가장 분산이 높은 방향으로 회전 변환(rotation transform)을 진행

- PCA는 때로 전처리 도구처럼 사용되기도 한다.

 


PCA 붓꽃 데이터 실습

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

from sklearn import decomposition
from sklearn import datasets

import warnings
warnings.filterwarnings("ignore") # 불필요한 Warning 메시지를 꺼줍니다.

iris = datasets.load_iris()
x = iris.data
y = iris.target

model = decomposition.PCA(n_components=1)

n_component : 몇개의 차원으로 축소할지

 

model.fit(x)
x1 = model.transform(x) # 모델에 맞춰서 원래 데이터를 차원이동 시켜줍니다.

x1[:10]
# pip install seaborn
import seaborn as sns

# bins : Specification of hist bins, or None to use Freedman-Diaconis rule.
# kde : Whether to plot a gaussian kernel density estimate
sns.distplot(x1[y==0], color="b", bins=20, kde=False)
sns.distplot(x1[y==1], color="g", bins=20, kde=False)
sns.distplot(x1[y==2], color="r", bins=20, kde=False)

plt.xlim(-6, 6)

plt.show()


model = decomposition.PCA(n_components=3)
model.fit(x)
x = model.fit_transform(x)

x
# PCA plot of 2 PCs

plt.scatter(x[:, 0], x[:, 1], c=iris.target)
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.show()

decomposition.PCA(n_components=2)

# PCA plot of 3 PCs

fig = plt.figure()
ax = Axes3D(fig, elev=48, azim=134) # Set the elevation and azimuth of the axes. (축의 고도와 방위각)

ax.scatter(x[:, 0], x[:, 1], x[:, 2], c=iris.target, edgecolor='w', s=100)
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')
ax.set_zlabel('PC3')
ax.dist = 12 # 값이 커지면 전체 plot 이 작아짐

plt.show()

몇 개의 PC 면 충분할까?

# 각각의 새로운 축이 데이터셋의 분산(variance)을 얼마나 표현하는지 확인이 가능
# [PC1, PC2, PC3, ...]

# Hint: Explain variance
model.explained_variance_ratio_
array([0.92461872, 0.05306648, 0.01710261])

보통 값을 더했을때 90% 넘어가면 쓸만하다고 보고, 더욱 안정적인 것을 원한다면 95% 이상이여야 한다.

# 몇 개의 PC면 충분할까?
# np.argmax : 최대값의 인덱스를 리턴
# np.cumsum : 누적된 합계를 계산

np.argmax(np.cumsum(model.explained_variance_ratio_) >= 0.95 ) + 1
# 95% 이상의 variance 를 설명하기 위한 축의 갯수를 확인할 수 있음
2

Boston house dataset의 경우,

boston = datasets.load_boston()
x = boston.data
y = boston.target

model = decomposition.PCA(n_components=10)
model.fit(x)
x = model.transform(x)

model.explained_variance_ratio_
array([8.05823175e-01, 1.63051968e-01, 2.13486092e-02, 6.95699061e-03,
       1.29995193e-03, 7.27220158e-04, 4.19044539e-04, 2.48538539e-04,
       8.53912023e-05, 3.08071548e-05])
np.argmax(np.cumsum(model.explained_variance_ratio_) >= 0.95 ) + 1
2

매번 계산하지 않고 제일 쉬운 방법

# Better option (indicate the ratio of variance you wish to preserve)

iris = datasets.load_iris()
x = iris.data
y = iris.target

model = decomposition.PCA(n_components=0.95) # Explains 95% of total variance
model.fit(x)
x = model.transform(x)
x

float 값을 적어주면 분산으로 계산해서 자동으로 PCA를 해줌