'주성분분석'에 해당되는 글 2건

  1. 2020.04.09 :: [python] PCA
  2. 2019.02.21 :: 주성분 분석
Python 2020. 4. 9. 21:46

차원 축소 및 주성분 분석을 위해 많이 사용하는 PCA

자꾸 코드를 까먹어서 기억을 위해 적어둠

----------------------------------------9/3 코드가 너무 엉망이여서 수정

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

df = pd.read_csv('') # read file
# pca는 꼭 표준화를 시켜준다
pca_df = StandardScaler().fit_transform(df)

# 2차원 
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(pca_df)
principalDf = pd.DataFrame(data = principalComponents
             , columns = ['principal component 1', 'principal component 2'])
finalDF = pd.concat([principalDF, df[input y column name]], axis=1)
# pca 그리기
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,1,1) 
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_title('2 component PCA', fontsize = 20)
targets = [0, 1] # y class에 맞춰서 변경
colors = ['r', 'g'] # targets 길이와 같이 color 입력
for target, color in zip(targets,colors):
    indicesToKeep = finalDf[y column name] == target
    ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
               , finalDf.loc[indicesToKeep, 'principal component 2']
               , c = color
               , s = 50)
ax.legend(targets)
ax.grid()

# 3차원
from mpl_toolkits.mplot3d import Axes3D
pca = PCA(n_components=3)
principalComponents = pca.fit_transform(pca_df)
principalDf = pd.DataFrame(data = principalComponents
             , columns = ['principal component 1', 'principal component 2','principal component 3'])
finalDF = pd.concat([principalDF, df[input y column name]], axis=1)
# pca 그리기
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,1,1, projection="3d") 
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_ylabel('Principal Component 3', fontsize = 15)
ax.set_title('3 component PCA', fontsize = 20)
targets = [0, 1] # y class에 맞춰서 변경
colors = ['r', 'g'] # targets 길이와 같이 color 입력
for target, color in zip(targets,colors):
    indicesToKeep = finalDf[y column name] == target
    ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
               , finalDf.loc[indicesToKeep, 'principal component 2']
               , finalDf.loc[indicesToKeep, 'principal component 3']
               , c = color)
ax.legend(targets)
ax.grid()
posted by 초코렛과자
:
R 2019. 2. 21. 22:08

주성분 분석(Principal Component Analysis, PCA)은 상관관계가 있는 고차원 자료를 자료의 변동을 최대한 보존하는 저차원 자료로 변환시키는 방법으로, 자료의 차원을 축약시키는데 주로 사용


# 주성분 분석

library(datasets)

data("USArrests")

# 주성분분석 함수 princomp

# cor=T의 의미 : 주성분분석을 공분산행렬이 아닌 상관계수 행렬을 사용하여 수행하도록 한다

fit <- princomp(USArrests, cor=T)


# 첫번째 변수가 전체의 약 62%를 설명, 3번째까지 하면 약 96%를 설명한다고 해석

summary(fit)


# Y1 = 0.536Muder + 0.583Assault + 0.278UrbanPop + 0.543Rape

# Y2 = 0.418Muder + 0.188Assault -0.873UrbanPop - 0.167Rape

loadings(fit)


plot(fit, type='l')

fit$scores

biplot(fit)


'R' 카테고리의 다른 글

시계열분석 example  (0) 2019.02.24
다차원척도법  (0) 2019.02.21
다변량분석 - 상관분석  (0) 2019.02.18
step 함수를 이용한 전진선택법 적용 example  (0) 2019.02.17
다중선형분석 example 2  (0) 2019.02.17
posted by 초코렛과자
: