Data Analysis & ML/Python을 활용한 통계분석

[통계분석] PCA(주성분분석) (ADP실기 준비)

YSY^ 2020. 12. 24. 17:53

주성분분석

  • 고차원의 데이터를 저차원의 데이터로 환원시키는 기법
  • 데이터를 어떤 기준을 바탕으로 변환을 하고, 그 변환으로 인해 '주성분'이 추출된다.
  • 따라서 추출된 주성분은 원래 가지고 있는 데이터와 다르다. 변환된 데이터이다.
  • 따라서 변수의 의미가 중요한 경우에는 PCA를 사용하면 안 된다. 왜냐면, PCA는 데이터에 변환을 가하는 것이기 때문이다.
  • PCA는 탐색적 분석이다. 즉, 변인을 탐색해서 변환을 통해 주성분을 결정하는 방법이다.
  • PCA의 본질은 차원 축소이다. 차원이 축소됐다는 것은 원본 데이터가 아니라 변환(projection) 된 데이터, 즉 주성분을 이용해 분석 혹은 모델링을 진행하겠다는 것이다.
import pandas as pd
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
df = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target'])

from sklearn.preprocessing import StandardScaler  # 표준화 패키지 라이브러리 
x = df.drop(['target'], axis=1).values # 독립변인들의 value값만 추출
y = df['target'].values # 종속변인 추출

x = StandardScaler().fit_transform(x) # x객체에 x를 표준화한 데이터를 저장

features = ['sepal length', 'sepal width', 'petal length', 'petal width']
pd.DataFrame(x, columns=features).head()

 

최적의 주성분 개수 구하기

from sklearn.decomposition import PCA
pca = PCA()
pca.fit(x)
PC_score = pca.transform(x)
# pca의 eigen_vector
pca.components_

array([[ 0.52237162, -0.26335492, 0.58125401, 0.56561105],
[ 0.37231836, 0.92555649, 0.02109478, 0.06541577],
[-0.72101681, 0.24203288, 0.14089226, 0.6338014 ],
[-0.26199559, 0.12413481, 0.80115427, -0.52354627]])

pca.explained_variance_ #explained_variacne를 통해서 PC값의 설명력을 확인 할 수 있다.
# array([2.93035378, 0.92740362, 0.14834223, 0.02074601])
  • PC값이 클수록 설명력이 높다.
  • 첫 번째 PC 값이 가장 크므로 가장 설명력이 높다.
ratio = pca.explained_variance_ratio_ #explained_variance 비율로 확인
ratio
# array([0.72770452, 0.23030523, 0.03683832, 0.00515193])
  • PC1 이 72.7%의 설명력을 가지고 있으며, PC2가 23%의 설명력을 가지고 있다. 즉, 주성분 2개가 전체의 96%를 설명한다.
# 설명력 정도 확인
df_v = pd.DataFrame(ratio, index=['PC1','PC2','PC3','PC4'], columns=['pc_ratio'])
df_v.plot.pie(y='pc_ratio')
df_v

ax = plt.plot( ['PC1','PC2','PC3','PC4'], ratio)
plt.ylabel('Variance(%)')
plt.xlabel('Principal Component')
plt.title('PCA Plot')
plt.show()

ax = plt.bar(x = range(len(ratio)), height=ratio, tick_label=['PC1','PC2','PC3','PC4'])
plt.ylabel('Variance(%)')
plt.xlabel('Principal Component')
plt.title('PCA Plot(bar)')
plt.show()

 

최적의 주성분 개수로 분석하기

# 주성분 2개로 분석
from sklearn.decomposition import PCA
import numpy as np
pca = PCA(n_components=2) # 주성분의 개수 결정
pc = pca.fit_transform(x)
pc_y = np.c_[pc,y]
principalDf = pd.DataFrame(pc_y, columns = ['pc1', 'pc2','diagnosis'])
principalDf

 

import seaborn as sns
sns.scatterplot(data=principalDf,x='pc1',y='pc2',hue='diagnosis')

 

# 로지스틱 분석
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix

clf2 = LogisticRegression(max_iter=1000, random_state=0, 
                        multi_class='multinomial')
clf2.fit(pc,y)
pred = clf2.predict(pc) #PC_score[:,:2]
confusion_matrix(y,pred)

728x90
반응형