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 초코렛과자
: