평균 이동 클러스터링 알고리즘

Beginner

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

소개

이 실습에서는 Python 의 Scikit-learn 라이브러리를 사용하여 평균 이동 군집화 알고리즘을 구현하는 방법을 안내합니다. 샘플 데이터 생성, 평균 이동 군집화 계산 및 결과 플롯 방법을 배울 것입니다.

VM 팁

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

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

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

필요한 라이브러리 가져오기

먼저 필요한 라이브러리를 가져와야 합니다: numpy, sklearn.cluster, sklearn.datasets, 그리고 matplotlib.pyplot.

import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

샘플 데이터 생성

다음으로 sklearn.datasets 모듈의 make_blobs 함수를 사용하여 샘플 데이터를 생성합니다. 10,000 개의 샘플과 중심점이 [[1, 1], [-1, -1], [1, -1]]이고 표준 편차가 0.6 인 세 개의 클러스터를 가진 데이터셋을 생성합니다.

centers = [[1, 1], [-1, -1], [1, -1]]
X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)

MeanShift 알고리즘을 이용한 클러스터링

이제 sklearn.cluster 모듈의 MeanShift 클래스를 사용하여 Mean-Shift 알고리즘으로 클러스터링을 수행합니다. estimate_bandwidth 함수를 사용하여 각 점의 영향력 범위를 나타내는 밴드위스 (bandwidth) 매개변수를 자동으로 감지합니다.

bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=500)
ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_

결과 플롯

마지막으로 matplotlib.pyplot 라이브러리를 사용하여 결과를 플롯합니다. 각 클러스터에 다른 색상과 마커를 사용하고 클러스터 중심점도 플롯합니다.

plt.figure(1)
plt.clf()

colors = ["#dede00", "#377eb8", "#f781bf"]
markers = ["x", "o", "^"]

for k, col in zip(range(n_clusters_), colors):
    my_members = labels == k
    cluster_center = cluster_centers[k]
    plt.plot(X[my_members, 0], X[my_members, 1], markers[k], color=col)
    plt.plot(
        cluster_center[0],
        cluster_center[1],
        markers[k],
        markerfacecolor=col,
        markeredgecolor="k",
        markersize=14,
    )
plt.title("추정된 클러스터 개수: %d" % n_clusters_)
plt.show()

요약

이 실습에서는 파이썬의 Scikit-learn 라이브러리를 사용하여 Mean-Shift 클러스터링 알고리즘을 구현하는 방법을 배웠습니다. 샘플 데이터를 생성하고, MeanShift 를 사용하여 클러스터링을 계산하고, 결과를 플롯했습니다. 이 실습을 마치면 데이터를 클러스터링하기 위해 Mean-Shift 알고리즘을 사용하는 방법에 대한 이해도가 높아질 것입니다.