Machine Learning Academy · 강의

K 선택하기: 엘보 방법과 실루엣 점수

학습자는 관성 대 k를 그려 엘보를 찾고 실루엣 계수를 계산하여, 서로 잘 분리되고 조밀한 그룹을 만드는 클러스터 수를 선택합니다.

레슨 2/413개 단계

K 선택하기: 엘보 방법과 실루엣 점수은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Choosing k Matters

K-Means requires you to specify k — the number of clusters — before training. Too few clusters and you lump distinct groups together; too many and you split natural groups artificially. There is no universally correct k, but two diagnostic tools — the elbow method and the silhouette score — give principled guidance.

Inertia Decreases as k Grows

As you increase k, inertia always decreases because points are assigned to closer centroids. At k=n (one cluster per point), inertia is zero. This means you cannot simply minimise inertia — you need to find where additional clusters stop providing meaningful reductions. That point of diminishing returns is the elbow.

from sklearn.cluster import KMeans
import numpy as np

X = np.random.randn(200, 2)
inertias = []

for k in range(1, 11):
    km = KMeans(n_clusters=k, random_state=42, n_init=10)
    km.fit(X)
    inertias.append(km.inertia_)

print('Inertia per k:')
for k, inr in enumerate(inertias, start=1):
    print(f'  k={k}: {inr:.1f}')

The Elbow Method Explained

Plot inertia on the y-axis against k on the x-axis. The curve typically drops steeply for the first few k values then flattens. The elbow — the kink where the rate of decrease sharply slows — is your estimate of the true cluster count. If the true k is 3, the drop from k=1 to k=3 is large, but from k=3 to k=4 is much smaller.

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

X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.7, random_state=0)

inertias = []
for k in range(1, 11):
    km = KMeans(n_clusters=k, random_state=0, n_init=10)
    km.fit(X)
    inertias.append(km.inertia_)

plt.plot(range(1, 11), inertias, marker='o')
plt.xlabel('Number of clusters k')
plt.ylabel('Inertia')
plt.title('Elbow Method')
plt.axvline(x=4, color='red', linestyle='--', label='True k=4')
plt.legend()
plt.show()

Limitations of the Elbow Method

The elbow method works well when clusters are clearly separated, but real-world data often produces a smooth curve with no obvious kink. In such cases the elbow is ambiguous and different people may pick different k. That is where the silhouette score provides a more objective, mathematically grounded alternative.

Silhouette Score: The Formula

For each point i, compute two values: a(i) = mean distance to other points in the same cluster (cohesion), and b(i) = mean distance to the nearest different cluster (separation). The silhouette for point i is s(i) = (b(i) - a(i)) / max(a(i), b(i)). Values range from −1 (wrong cluster) through 0 (on border) to +1 (tight, well-separated cluster).

Computing Silhouette Score in sklearn

sklearn.metrics.silhouette_score returns the mean silhouette over all points. A score above 0.5 typically indicates reasonable clustering; above 0.7 is strong. Because you cannot compute the silhouette for k=1 (no second cluster), sweep k from 2 to some maximum and pick the k with the highest mean score.

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.datasets import make_blobs

X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.7, random_state=0)

scores = {}
for k in range(2, 9):
    km = KMeans(n_clusters=k, random_state=0, n_init=10)
    labels = km.fit_predict(X)
    scores[k] = silhouette_score(X, labels)
    print(f'k={k}  silhouette={scores[k]:.3f}')

best_k = max(scores, key=scores.get)
print(f'Best k: {best_k}')

Silhouette Plots for Per-Point Analysis

A silhouette plot shows the silhouette coefficient of every individual point, sorted by cluster and width. Wide, uniform bars indicate all points are well-placed. Thin bars or points with negative scores reveal misassigned outliers. scikit-learn's silhouette_samples returns per-point scores that you can visualise this way.

from sklearn.metrics import silhouette_samples
import numpy as np

from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

X, _ = make_blobs(n_samples=100, centers=3, cluster_std=0.6, random_state=0)
km = KMeans(n_clusters=3, random_state=0, n_init=10)
labels = km.fit_predict(X)

samples = silhouette_samples(X, labels)
print('Per-cluster mean silhouettes:')
for c in range(3):
    print(f'  Cluster {c}: {samples[labels == c].mean():.3f}')

Combining Elbow and Silhouette

In practice, use both methods together. If the elbow suggests k=4 and the silhouette score is also highest at k=4, you have strong convergent evidence. When they disagree — e.g., elbow at k=3 but silhouette peaks at k=5 — examine the silhouette plot for each candidate k and apply domain knowledge to make the final call.

Gap Statistic: A Statistical Test for k

The gap statistic compares the observed inertia against the expected inertia under a null reference distribution (data sampled uniformly in the feature space). Choose the smallest k where gap(k) >= gap(k+1) - stddev. It is more statistically rigorous than the elbow method but computationally expensive because it requires generating many random reference datasets.

Practical Guidelines for k Selection

Start with domain knowledge — if you know there are 5 product categories, start with k=5. Use the elbow as a quick visual sanity check. Confirm with silhouette for objectivity. Evaluate downstream — for business use cases, test whether the segments are actionable and interpretable. The numerically optimal k is not always the most useful business segmentation.

Elbow and Silhouette Together: Full Example

Here is a compact pipeline that runs both diagnostics side by side, giving you a summary table to help pick k efficiently.

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler

X, _ = make_blobs(n_samples=400, centers=5, cluster_std=0.8, random_state=7)
X = StandardScaler().fit_transform(X)

print(f'{'k':>3}  {'Inertia':>10}  {'Silhouette':>10}')
for k in range(2, 10):
    km = KMeans(n_clusters=k, n_init=10, random_state=0)
    labels = km.fit_predict(X)
    sil = silhouette_score(X, labels)
    print(f'{k:>3}  {km.inertia_:>10.1f}  {sil:>10.3f}')

Quick Check

Test your understanding of k selection methods from this lesson.

Lesson Recap

In this lesson you learned: the elbow method plots inertia vs k and looks for the kink where improvement slows, silhouette score ranges from -1 to +1 and measures both cohesion and separation, and combining both methods with domain knowledge gives the most reliable k selection. Next up we explore DBSCAN — a density-based algorithm that discovers clusters of arbitrary shape and handles noise.

무료로 시작

AI 튜터와 함께 Python을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
30
레슨
120

자주 묻는 질문

“K 선택하기: 엘보 방법과 실루엣 점수” 강의는 무료인가요?

네 — “K 선택하기: 엘보 방법과 실루엣 점수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“K 선택하기: 엘보 방법과 실루엣 점수”에서 뭘 배우나요?

학습자는 관성 대 k를 그려 엘보를 찾고 실루엣 계수를 계산하여, 서로 잘 분리되고 조밀한 그룹을 만드는 클러스터 수를 선택합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“K 선택하기: 엘보 방법과 실루엣 점수” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. K-Means: 중심점, 할당 및 갱신 단계
  2. K 선택하기: 엘보 방법과 실루엣 점수
  3. DBSCAN: 핵심 점, 경계 점 및 잡음
  4. 고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기
← Machine Learning Academy(으)로 돌아가기