응집적 군집화 거리 측정 지표

Beginner

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

소개

계층적 군집화 방법 중 하나인 응집적 군집화는 유사한 객체를 그룹으로 묶는 데 사용됩니다. 각 객체를 개별 클러스터로 시작하여 반복적으로 가장 유사한 클러스터를 병합하여 중지 기준을 충족할 때까지 계속됩니다. 이 실습에서는 응집적 군집화 알고리즘을 사용하여 다양한 메트릭이 계층적 군집화에 미치는 영향을 보여줄 것입니다.

VM 팁

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

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

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

라이브러리 가져오기 및 파형 데이터 생성

먼저, 이 실습에서 사용할 필요한 라이브러리를 가져오고 파형 데이터를 생성합니다.

import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import pairwise_distances

np.random.seed(0)

## 파형 데이터 생성
n_features = 2000
t = np.pi * np.linspace(0, 1, n_features)

def sqr(x):
    return np.sign(np.cos(x))

X = list()
y = list()
for i, (phi, a) in enumerate([(0.5, 0.15), (0.5, 0.6), (0.3, 0.2)]):
    for _ in range(30):
        phase_noise = 0.01 * np.random.normal()
        amplitude_noise = 0.04 * np.random.normal()
        additional_noise = 1 - 2 * np.random.rand(n_features)
        ## 노이즈를 희소하게 만듭니다.
        additional_noise[np.abs(additional_noise) < 0.997] = 0

        X.append(
            12
            * (
                (a + amplitude_noise) * (sqr(6 * (t + phi + phase_noise)))
                + additional_noise
            )
        )
        y.append(i)

X = np.array(X)
y = np.array(y)

기준 라벨링 시각화

파형 데이터의 기준 라벨링을 시각화합니다.

n_clusters = 3

labels = ("Waveform 1", "Waveform 2", "Waveform 3")

colors = ["#f7bd01", "#377eb8", "#f781bf"]

## 기준 라벨링 시각화
plt.figure()
plt.axes([0, 0, 1, 1])
for l, color, n in zip(range(n_clusters), colors, labels):
    lines = plt.plot(X[y == l].T, c=color, alpha=0.5)
    lines[0].set_label(n)

plt.legend(loc="best")

plt.axis("tight")
plt.axis("off")
plt.suptitle("Ground truth", size=20, y=1)

거리 시각화

다양한 지표에 대한 클래스 간 거리를 시각화합니다.

for index, metric in enumerate(["cosine", "euclidean", "cityblock"]):
    avg_dist = np.zeros((n_clusters, n_clusters))
    plt.figure(figsize=(5, 4.5))
    for i in range(n_clusters):
        for j in range(n_clusters):
            avg_dist[i, j] = pairwise_distances(
                X[y == i], X[y == j], metric=metric
            ).mean()
    avg_dist /= avg_dist.max()
    for i in range(n_clusters):
        for j in range(n_clusters):
            t = plt.text(
                i,
                j,
                "%5.3f" % avg_dist[i, j],
                verticalalignment="center",
                horizontalalignment="center",
            )
            t.set_path_effects(
                [PathEffects.withStroke(linewidth=5, foreground="w", alpha=0.5)]
            )

    plt.imshow(avg_dist, interpolation="nearest", cmap="cividis", vmin=0)
    plt.xticks(range(n_clusters), labels, rotation=45)
    plt.yticks(range(n_clusters), labels)
    plt.colorbar()
    plt.suptitle("Interclass %s distances" % metric, size=18, y=1)
    plt.tight_layout()

클러스터링 결과 시각화

다양한 지표에 대한 클러스터링 결과를 시각화합니다.

for index, metric in enumerate(["cosine", "euclidean", "cityblock"]):
    model = AgglomerativeClustering(
        n_clusters=n_clusters, linkage="average", metric=metric
    )
    model.fit(X)
    plt.figure()
    plt.axes([0, 0, 1, 1])
    for l, color in zip(np.arange(model.n_clusters), colors):
        plt.plot(X[model.labels_ == l].T, c=color, alpha=0.5)
    plt.axis("tight")
    plt.axis("off")
    plt.suptitle("AgglomerativeClustering(metric=%s)" % metric, size=20, y=1)

요약

이 실험에서는 계층적 군집화 알고리즘인 응집적 군집화 (agglomerative clustering) 에서 다양한 거리 측정 지표가 결과에 미치는 영향을 보여주었습니다. 파형 데이터를 생성하고, 다양한 거리 측정 지표에 대해 실제 레이블링, 클래스 간 거리, 그리고 군집화 결과를 시각화했습니다. 군집화 결과는 거리 측정 지표의 선택에 따라 달라졌으며, 시티블록 거리가 파형을 가장 잘 구분하는 것으로 나타났습니다.