'PCA'에 해당되는 글 3건

  1. 2021.05.18 :: plotly를 이용한 pca
  2. 2020.04.09 :: [python] PCA
  3. 2019.02.21 :: 주성분 분석
Python 2021. 5. 18. 09:46

https://plotly.com/python/pca-visualization/

 

PCA Visualization

Visualize Principle Component Analysis (PCA) of your high-dimensional data in Python with Plotly.

plotly.com

여기에 잘 나와있다. matplotlib를 이용하는것보다 훨씬 코드가 간단해진다.

 

2D

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

df = pd.read_csv("")
pca_df = StandardScaler().fit_transform(df)

pca = PCA(n_components=2)
principalComponents = pca.fit_transform(pca_df)
fig = px.scatter(principalComponents, x=0, y=1, color=df['label'])
fig.show()

3D

pca = PCA(n_components=3)
components = pca.fit_transform(df)

total_var = pca.explained_variance_ratio_.sum() * 100

fig = px.scatter_3d(
    components, x=0, y=1, z=2, color=df['label'],
    title=f'Total Explained Variance: {total_var:.2f}%',
    labels={'0': 'PC 1', '1': 'PC 2', '2': 'PC 3'}
)
fig.show()

'Python' 카테고리의 다른 글

dataframe 범위별 구간 만들기  (0) 2021.06.02
pandas read csv시 thousand 숫자형으로 읽기  (0) 2021.05.24
dataframe zero value column remove  (0) 2021.05.09
dataframe merge - reduce 이용  (0) 2021.04.22
seaborn boxplot 그리기  (0) 2021.04.13
posted by 초코렛과자
:
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 초코렛과자
: