🤖 AI/ML

K-means

K-Means Clustering

An unsupervised learning clustering algorithm. Partitions data into K groups.

📖 Detailed Explanation

K-means clustering is a representative unsupervised learning algorithm that automatically classifies unlabeled data into K groups. Each data point is assigned to the nearest centroid, and the algorithm is optimized to minimize the sum of within-cluster distances (inertia).

It was developed in 1957 by Stuart Lloyd of Bell Labs for pulse-code modulation technology, and the name "K-means" was later given to it in 1967 by James MacQueen. It is a proven algorithm that has been in use for over 60 years.

The algorithm's complexity is O(n * K * d * i), where n is the number of data points, K is the number of clusters, d is the number of dimensions, and i is the number of iterations. For large-scale data, MiniBatchKMeans is more efficient and also uses less memory.

Practical use cases include customer segmentation (RFM analysis), image color quantization (compression), anomaly detection (identifying data outside clusters), and document clustering. Because it is simple and easy to interpret, it is often used as the first step of exploratory data analysis.

💻 Code Example

from sklearn.cluster import KMeans, MiniBatchKMeans
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import numpy as np

# 테스트 데이터 생성
X, y_true = make_blobs(n_samples=1000, centers=4, cluster_std=0.6, random_state=42)

# 데이터 정규화
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Elbow Method로 최적 K 찾기
def find_optimal_k(X, max_k=10):
    inertias = []
    for k in range(1, max_k + 1):
        kmeans = KMeans(n_clusters=k, random_state=42, n_init='auto')
        kmeans.fit(X)
        inertias.append(kmeans.inertia_)

    # 기울기 변화가 가장 큰 지점 찾기
    diffs = np.diff(inertias)
    second_diffs = np.diff(diffs)
    optimal_k = np.argmax(np.abs(second_diffs)) + 2
    return optimal_k, inertias

optimal_k, inertias = find_optimal_k(X_scaled)
print(f"추천 K: {optimal_k}")

# 대용량 데이터용 MiniBatchKMeans
kmeans = MiniBatchKMeans(
    n_clusters=optimal_k,
    batch_size=256,     # 미니배치 크기
    random_state=42,
    n_init='auto'
)
labels = kmeans.fit_predict(X_scaled)

# 결과 시각화
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.plot(range(1, 11), inertias, 'bo-')
plt.axvline(x=optimal_k, color='r', linestyle='--', label=f'K={optimal_k}')
plt.xlabel('K'); plt.ylabel('Inertia'); plt.title('Elbow Method')
plt.subplot(1, 2, 2)
plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=labels, cmap='viridis', alpha=0.6)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],
            c='red', marker='X', s=200, label='Centroids')
plt.title('K-means Clustering'); plt.legend()
plt.tight_layout(); plt.show()

🗣️ Say It Like This in Practice

💬 In a Meeting
"We analyzed customer purchase patterns with K-means, and they split into 4 segments. If we apply a different marketing strategy to each group — VIP, regular purchasers, price-sensitive, and churn-risk — we can raise the conversion rate."
💬 In an Interview
"K-means is based on Euclidean distance, so it suits spherical clusters. For non-spherical clusters or clusters with different densities, you should consider DBSCAN or GMM. The dependence on initial values can be improved with k-means++."
💬 In a Technical Discussion
"If the data is over 1 million records, MiniBatchKMeans is much faster. If you set the batch size to around 256–1024, accuracy is almost maintained while speed improves by more than 10x."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Applying K-means to categorical data

K-means is designed for continuous numerical data. For categorical data, use K-modes or K-prototypes.

❌
Clustering without outlier handling

Outliers distort the centroids. Remove outliers using IQR or Z-score, or use a robust algorithm.

✅
Use k-means++ initialization

sklearn's default (init='k-means++') selects better initial centroids, improving convergence speed and result quality.

🔗 Related Terms

📚 Learn More