숫자 데이터셋에 대한 계층적 군집화

Beginner

This tutorial is from open-source community. Access the source code

소개

이 실습에서는 숫자 데이터셋의 2 차원 임베딩에 대한 응집 계층적 군집화의 다양한 연결 옵션을 보여줍니다. 이 실습의 목표는 서로 다른 연결 전략이 어떻게 작동하는지 보여주는 것이며, 숫자 데이터에 대한 좋은 군집을 찾는 것이 아닙니다. 이것이 예제가 2 차원 임베딩에서 작동하는 이유입니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근할 수 있습니다.

때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중 문제가 발생하면 Labby 에 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.

라이브러리 가져오기

이 실습에서 필요한 라이브러리를 가져오는 것으로 시작합니다. 응집 계층적 군집화를 수행하기 위해 numpy, matplotlib, manifold 및 scikit-learn 의 datasets 를 사용할 것입니다.

import numpy as np
from matplotlib import pyplot as plt
from time import time
from sklearn import manifold, datasets
from sklearn.cluster import AgglomerativeClustering

데이터셋 로드 및 준비

숫자 데이터셋을 로드하고 데이터와 대상 레이블을 추출하여 군집화를 위한 준비를 합니다. 또한 재현성을 보장하기 위해 난수 시드를 0 으로 설정합니다.

digits = datasets.load_digits()
X, y = digits.data, digits.target
n_samples, n_features = X.shape
np.random.seed(0)

데이터셋 시각화

manifold.SpectralEmbedding() 을 사용하여 숫자 데이터셋의 2 차원 임베딩을 계산하고 각 숫자에 대해 다른 마커로 산점도를 플롯하여 데이터셋을 시각화합니다.

def plot_dataset(X_red):
    x_min, x_max = np.min(X_red, axis=0), np.max(X_red, axis=0)
    X_red = (X_red - x_min) / (x_max - x_min)

    plt.figure(figsize=(6, 4))
    for digit in digits.target_names:
        plt.scatter(
            *X_red[y == digit].T,
            marker=f"${digit}$",
            s=50,
            alpha=0.5,
        )

    plt.xticks([])
    plt.yticks([])
    plt.title('숫자 데이터셋 산점도', size=17)
    plt.axis("off")
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])

print("임베딩 계산 중")
X_red = manifold.SpectralEmbedding(n_components=2).fit_transform(X)
print("완료.")
plot_dataset(X_red)

다양한 연결 전략을 사용한 계층적 군집화

다양한 연결 전략 (ward, average, complete, single) 을 사용하여 계층적 군집화를 수행합니다. 모든 전략에 대해 클러스터 수를 10 으로 설정합니다. 그런 다음 각 숫자에 대해 다른 색상을 사용하여 군집화 결과를 플롯합니다.

def plot_clustering(X_red, labels, title=None):
    x_min, x_max = np.min(X_red, axis=0), np.max(X_red, axis=0)
    X_red = (X_red - x_min) / (x_max - x_min)

    plt.figure(figsize=(6, 4))
    for digit in digits.target_names:
        plt.scatter(
            *X_red[y == digit].T,
            marker=f"${digit}$",
            s=50,
            c=plt.cm.nipy_spectral(labels[y == digit] / 10),
            alpha=0.5,
        )

    plt.xticks([])
    plt.yticks([])
    if title is not None:
        plt.title(title, size=17)
    plt.axis("off")
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])

for linkage in ("ward", "average", "complete", "single"):
    clustering = AgglomerativeClustering(linkage=linkage, n_clusters=10)
    t0 = time()
    clustering.fit(X_red)
    print("%s :\t%.2fs" % (linkage, time() - t0))

    plot_clustering(X_red, clustering.labels_, "%s linkage" % linkage)

plt.show()

요약

이 실습에서는 다양한 연결 전략을 사용하여 숫자 데이터셋에 대한 계층적 군집화를 수행하는 방법을 배웠습니다. 또한 각 전략에 대한 데이터셋과 군집화 결과를 시각화했습니다. 결과는 서로 다른 연결 전략이 서로 다른 군집화 결과를 생성한다는 것을 보여주며, 우리의 필요에 가장 적합한 전략을 선택해야 함을 시사합니다.