차원 축소와 군집화

2024. 3. 18. 18:57·Machine Learning/Dimension Reduction

 

 

 
 

차원 축소와 군집화¶

 
In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


np.random.seed(2021)
 
 

1. Data¶

 
 

1.1 Data Load¶

 
 

이번 실습에서 사용할 데이터는 손글씨 데이터입니다.
데이터는 sklearn.datasets의 load_digits를 이용해 받을 수 있습니다.

 
In [2]:
from sklearn.datasets import load_digits

digits = load_digits()
 
In [3]:
data, target = digits["data"], digits["target"]
 
In [4]:
data[0], target[0]
 
Out[4]:
(array([ 0.,  0.,  5., 13.,  9.,  1.,  0.,  0.,  0.,  0., 13., 15., 10.,
        15.,  5.,  0.,  0.,  3., 15.,  2.,  0., 11.,  8.,  0.,  0.,  4.,
        12.,  0.,  0.,  8.,  8.,  0.,  0.,  5.,  8.,  0.,  0.,  9.,  8.,
         0.,  0.,  4., 11.,  0.,  1., 12.,  7.,  0.,  0.,  2., 14.,  5.,
        10., 12.,  0.,  0.,  0.,  0.,  6., 13., 10.,  0.,  0.,  0.]),
 0)
 
 

1.2 데이터 정규화¶

 
 

데이터의 크기에 영향을 받는 PCA를 위해서 데이터를 정규화합니다.

 
In [5]:
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
 
In [6]:
scaled_data = scaler.fit_transform(data)
 
 

1.3 시각화¶

 
 

TSNE를 이용해 시각화 데이터를 생성합니다.

 
In [7]:
from sklearn.manifold import TSNE

tsne = TSNE(n_components=2)
 
In [8]:
tsne_latent = tsne.fit_transform(scaled_data)
 
 
c:\Users\sjy99\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\manifold\_t_sne.py:800: FutureWarning: The default initialization in TSNE will change from 'random' to 'pca' in 1.2.
  warnings.warn(
c:\Users\sjy99\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\manifold\_t_sne.py:810: FutureWarning: The default learning rate in TSNE will change from 200.0 to 'auto' in 1.2.
  warnings.warn(
 
In [9]:
def visualize_latent_space_with_label(latent, pred):
    for label in np.unique(pred):
        index = pred == label
        component_1 = latent[index, 0]
        component_2 = latent[index, 1]
        plt.scatter(component_1, component_2, c=f"C{label}", label=label)
    plt.legend()
 
In [10]:
plt.figure(figsize=(7, 7))
visualize_latent_space_with_label(tsne_latent, target)
 
 
 
 

2. Clustering¶

 
 

우선 데이터에 다른 처리 없이 Kmeans로 군집화를 해보겠습니다.
k means 의 k는 정답을 알고 있는 상태니 10을 주어서 실제로 잘 군집이 되는지 확인해 보겠습니다.

 
 

2.1 학습¶

 
In [11]:
from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=10)
 
In [12]:
kmeans.fit(scaled_data)
 
Out[12]:
KMeans(n_clusters=10)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
KMeans(n_clusters=10)
 
 

2.2 예측¶

 
In [13]:
pred = kmeans.predict(scaled_data)
 
 

3.3 시각화¶

 
In [14]:
plt.figure(figsize=(7, 7))
visualize_latent_space_with_label(tsne_latent, pred)
 
 
 
 

3. PCA & Clustering¶

 
 

이번에는 차원을 축소한 후 군집화를 진행해 보겠습니다.

 
 

3.1 PCA 데이터 생성¶

 
 

우선 차원을 축소시킨 데이터를 생성합니다.

 
In [15]:
from sklearn.decomposition import PCA

pca = PCA(n_components=12)
pca.fit(scaled_data)
 
Out[15]:
PCA(n_components=12)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
PCA(n_components=12)
 
In [16]:
pca_data = pca.transform(scaled_data)
 
 

3.2 K Means 학습¶

 
In [17]:
pca_kmeans = KMeans(n_clusters=10)

pca_kmeans.fit(pca_data)
 
Out[17]:
KMeans(n_clusters=10)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
KMeans(n_clusters=10)
 
 

3.3 예측¶

 
In [18]:
pca_pred = pca_kmeans.predict(pca_data)
 
 

3.4 시각화¶

 
In [19]:
plt.figure(figsize=(7, 7))
visualize_latent_space_with_label(tsne_latent, pca_pred)
 
 
 
 

4. 마무리¶

 
In [24]:
plt.figure(figsize=(21, 7))
plt.subplot(131)
visualize_latent_space_with_label(tsne_latent, target)
plt.title("Raw TSNE")
plt.subplot(132)
visualize_latent_space_with_label(tsne_latent, pred)
plt.title("Raw Clustering")
plt.subplot(133)
visualize_latent_space_with_label(tsne_latent, pca_pred)
plt.title("PCA Clustering")
 
Out[24]:
Text(0.5, 1.0, 'PCA Clustering')
 
 
In [21]:
scaled_data.shape
 
Out[21]:
(1797, 64)
 
In [22]:
pca_data.shape
 
Out[22]:
(1797, 12)
 
In [ ]:
 

'Machine Learning > Dimension Reduction' 카테고리의 다른 글

Eigenface를 이용한 차원 축소와 SVM을 이용한 분류  (0) 2024.03.18
차원 축소 시각화 실습  (0) 2024.03.18
'Machine Learning/Dimension Reduction' 카테고리의 다른 글
  • Eigenface를 이용한 차원 축소와 SVM을 이용한 분류
  • 차원 축소 시각화 실습
Juson
Juson
  • Juson
    Juson의 데이터 공부
    Juson
  • 전체
    오늘
    어제
    • 분류 전체보기 (95)
      • RAG (2)
      • AI (2)
        • NLP (0)
        • Generative Model (0)
        • Deep Reinforcement Learning (2)
        • LLM (0)
      • Logistic Optimization (0)
      • Machine Learning (37)
        • Linear Regression (2)
        • Logistic Regression (2)
        • Decision Tree (5)
        • Naive Bayes (1)
        • KNN (2)
        • SVM (2)
        • Clustering (4)
        • Dimension Reduction (3)
        • Boosting (6)
        • Abnomaly Detection (2)
        • Recommendation (4)
        • Embedding & NLP (4)
      • Reinforcement Learning (5)
      • Deep Learning (10)
        • Deep learning Bacis Mathema.. (10)
      • Optimization (2)
        • OR Optimization (0)
        • Convex Optimization (0)
        • Integer Optimization (0)
      • SNA 분석 (0)
      • 포트폴리오 최적화 공부 (0)
        • 최적화 기법 (0)
        • 금융 베이스 (0)
      • Finanancial engineering (0)
      • 프로그래머스 데브코스(Boot camp) (15)
        • SQL (9)
        • Python (5)
        • Machine Learning (1)
      • Python (22)
      • Project (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Juson
차원 축소와 군집화
상단으로

티스토리툴바