[PCA] Principal Component Analysis (PCA) example code

2026. 3. 12. 05:42·연구 Research/데이터과학 Data Science

 

 

Iris dataset (2d feature)로 PCA를 적용한 예시이다.

 

import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris

# 1. Load sample data (Iris dataset)
data = load_iris()
X = data.data

# 2. Standardize the data (Mean=0, Variance=1)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 3. Apply PCA (reduce to 2 components)
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

# 4. Check results
print(f"Original shape: {X.shape}")
print(f"Reduced shape: {X_pca.shape}")
print(f"Explained variance ratio: {pca.explained_variance_ratio_}")


import numpy as np

def pca_from_scratch(X, n_components):
    # Step 1: Mean Centering
    X_meaned = X - np.mean(X, axis=0)
    
    # Step 2: Compute Covariance Matrix
    cov_mat = np.cov(X_meaned, rowvar=False)
    
    # Step 3: Compute Eigenvalues and Eigenvectors
    eigen_values, eigen_vectors = np.linalg.eigh(cov_mat)
    
    # Step 4: Sort Eigenvalues and Eigenvectors in descending order
    sorted_index = np.argsort(eigen_values)[::-1]
    sorted_eigenvectors = eigen_vectors[:, sorted_index]
    
    # Step 5: Select top N components
    eigenvector_subset = sorted_eigenvectors[:, 0:n_components]
    
    # Step 6: Transform the data
    X_reduced = np.dot(X_meaned, eigenvector_subset)
    return X_reduced

# Example usage
X_scratch = pca_from_scratch(X, 2)

 

원래 데이터셋은 다음과 같다.

 

 

 

 

 

# Visualize Principal Axes
plt.figure(figsize=(8, 6))

# Plot the data points
for color, i, target_name in zip(colors, [0, 1, 2], data.target_names):
    plt.scatter(X_pca[data.target == i, 0], X_pca[data.target == i, 1], 
                color=color, alpha=.8, lw=2, label=target_name)

# Plot principal axes
origin = [0, 0]
scale = np.sqrt(pca.explained_variance_)  # Scale by explained variance

for i, (component, var) in enumerate(zip(pca.components_, scale)):
    plt.arrow(origin[0], origin[1], 
              component[0] * var * 3, component[1] * var * 3,
              head_width=0.2, head_length=0.2, fc=f'C{i}', ec=f'C{i}', 
              linewidth=2.5, alpha=0.7, label=f'PC{i+1}')

plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of IRIS Dataset with Principal Axes')
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.grid(True, alpha=0.3)
plt.axhline(y=0, color='k', linewidth=0.5)
plt.axvline(x=0, color='k', linewidth=0.5)
plt.savefig("pca_iris_with_axes.eps")
plt.show()

 

저작자표시 비영리 변경금지 (새창열림)

'연구 Research > 데이터과학 Data Science' 카테고리의 다른 글

[알고리즘] KDTree로 가장 가까운 포인트 찾기  (0) 2024.12.28
[데이터과학] scipy interpolation 종류 정리  (0) 2023.08.25
[matplotlib] x,y축 format 지정하는 방법  (0) 2023.06.08
[Matplotlib] 3D scatter plot 그리는 코드  (0) 2023.04.28
[데이터과학] Pandas에서 dataframe 생성 및 export  (0) 2023.04.27
'연구 Research/데이터과학 Data Science' 카테고리의 다른 글
  • [알고리즘] KDTree로 가장 가까운 포인트 찾기
  • [데이터과학] scipy interpolation 종류 정리
  • [matplotlib] x,y축 format 지정하는 방법
  • [Matplotlib] 3D scatter plot 그리는 코드
보통의공대생
보통의공대생
수학,프로그래밍,기계항공우주 등 공부하는 기록들을 남깁니다.
  • 보통의공대생
    뛰는 놈 위에 나는 공대생
    보통의공대생
  • 전체
    오늘
    어제
    • 분류 전체보기 (479) N
      • 공지 (1)
      • 영어 공부 English Study (40)
        • 텝스 TEPS (7)
        • 글 Article (21)
        • 영상 Video (10)
      • 연구 Research (100)
        • 최적화 Optimization (3)
        • 데이터과학 Data Science (8)
        • 인공지능 Artificial Intelligent (40)
        • 제어 Control (45)
      • 프로그래밍 Programming (36)
        • 매트랩 MATLAB (25)
        • 파이썬 Python (33)
        • 줄리아 Julia (2)
        • C++ (3)
        • 리눅스 우분투 Ubuntu (6)
      • 항공우주 Aeronautical engineeri.. (21)
        • 항법 Navigation (0)
        • 유도 Guidance (0)
      • 기계공학 Mechanical engineering (3) N
        • 열역학 Thermodynamics (0)
        • 고체역학 Statics & Solid mechan.. (10)
        • 동역학 Dynamics (1)
        • 유체역학 Fluid Dynamics (0)
      • 수학 Mathematics (35)
        • 선형대수학 Linear Algebra (18)
        • 미분방정식 Differential Equation (3)
        • 확률및통계 Probability & Sta.. (2)
        • 미적분학 Calculus (1)
        • 복소해석학 Complex Analysis (5)
        • 실해석학 Real Analysis (1)
      • 수치해석 Numerical Analysis (29)
      • 확률 및 랜덤프로세스 Random process (2)
      • 추론 & 추정 이론 Estimation (3)
      • 기타 (96)
        • 설계 프로젝트 System Design (8)
        • 논문작성 Writing (57)
        • 세미나 Seminar (2)
        • 생산성 Productivity (3)
      • 실험 Experiment (1)
      • 유학 생활 Daily (8)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    논문작성법
    Linear algebra
    Statics
    JAX
    pytorch
    우분투
    논문작성
    MATLAB
    옵시디언
    Julia
    LaTeX
    teps
    수치해석
    Dear abby
    텝스
    IEEE
    딥러닝
    생산성
    텝스공부
    ChatGPT
    WOX
    obsidian
    인공지능
    고체역학
    머신러닝
    Zotero
    matplotlib
    Numerical Analysis
    에러기록
    Python
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
보통의공대생
[PCA] Principal Component Analysis (PCA) example code
상단으로

티스토리툴바