이분 K-평균과 정규 K-평균 성능 비교

Beginner

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

소개

정규 K-평균 알고리즘과 이분 K-평균 알고리즘의 성능을 비교하는 단계별 튜토리얼입니다. 이 튜토리얼은 증가하는 n_clusters 값에 따른 클러스터링에서 두 알고리즘의 차이를 보여줍니다.

VM 팁

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

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

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

라이브러리 가져오기

이 단계에서는 이 튜토리얼에 필요한 필수 라이브러리를 가져옵니다.

import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import BisectingKMeans, KMeans

샘플 데이터 생성

이 단계에서는 scikit-learn 의 make_blobs() 함수를 사용하여 샘플 데이터를 생성합니다. 2 개의 중심점을 가진 10,000 개의 샘플을 생성합니다.

n_samples = 10000
random_state = 0
X, _ = make_blobs(n_samples=n_samples, centers=2, random_state=random_state)

클러스터 개수 및 알고리즘 정의

이 단계에서는 KMeans 및 BisectingKMeans 에 대한 클러스터 중심의 개수를 정의하고, 비교할 알고리즘을 정의합니다.

n_clusters_list = [4, 8, 16]
clustering_algorithms = {
    "Bisecting K-Means": BisectingKMeans,
    "K-Means": KMeans,
}

결과 시각화

이 단계에서는 서브플롯을 사용하여 알고리즘의 결과를 시각화합니다. 산점도를 사용하여 데이터 포인트와 클러스터 중심점을 표현합니다. 비교할 각 알고리즘과 클러스터 수를 반복하여 결과를 플롯합니다.

fig, axs = plt.subplots(len(clustering_algorithms), len(n_clusters_list), figsize=(12, 5))
axs = axs.T

for i, (algorithm_name, Algorithm) in enumerate(clustering_algorithms.items()):
    for j, n_clusters in enumerate(n_clusters_list):
        algo = Algorithm(n_clusters=n_clusters, random_state=random_state, n_init=3)
        algo.fit(X)
        centers = algo.cluster_centers_

        axs[j, i].scatter(X[:, 0], X[:, 1], s=10, c=algo.labels_)
        axs[j, i].scatter(centers[:, 0], centers[:, 1], c="r", s=20)

        axs[j, i].set_title(f"{algorithm_name} : {n_clusters} clusters")

for ax in axs.flat:
    ax.label_outer()
    ax.set_xticks([])
    ax.set_yticks([])

plt.show()

요약

이 튜토리얼에서는 scikit-learn 에서 생성된 샘플 데이터를 사용하여 정규 K-평균 알고리즘과 이분 K-평균 알고리즘의 성능을 비교했습니다. 산점도를 사용하여 데이터 포인트와 클러스터 중심점을 나타내는 서브플롯을 통해 결과를 시각화했습니다. 이분 K-평균 알고리즘은 일반적으로 더 규칙적인 대규모 구조를 가진 클러스터를 생성하는 경향이 있는 반면, 정규 K-평균 알고리즘은 n_clusters 를 증가시키면 다른 클러스터링을 생성하는 것을 관찰했습니다.