K-Means
K-Means Clustering
An unsupervised learning algorithm that partitions data into K clusters.
K-Means Clustering
An unsupervised learning algorithm that partitions data into K clusters.
K-Means is a representative unsupervised learning algorithm that partitions data into K clusters. It automatically finds groups with similar characteristics in unlabeled data and is widely used for customer segmentation, image compression, anomaly detection, and more.
Proposed by Stuart Lloyd in 1957 and named by James MacQueen in 1967, K-Means is a classic algorithm that has been in use for more than 60 years. It is simple to implement, fast, and efficient even on large datasets, so it remains the most widely used clustering technique.
The algorithm works in these steps: 1) select K initial centroids, 2) assign each data point to the nearest centroid, 3) update each centroid to the mean of its cluster, 4) repeat steps 2-3 until convergence.
In practice, the optimal value of K is determined using the Elbow Method (the bend point in the inertia graph) or the Silhouette Score. sklearn's KMeans can process a million data points within a few seconds, and MiniBatchKMeans is suitable for even larger datasets.
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
import numpy as np
# 샘플 데이터 생성 (고객 데이터 시뮬레이션)
np.random.seed(42)
X = np.vstack([
np.random.randn(100, 2) + [0, 0], # 그룹 1
np.random.randn(100, 2) + [5, 5], # 그룹 2
np.random.randn(100, 2) + [10, 0] # 그룹 3
])
# 데이터 표준화 (중요!)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Elbow Method로 최적 K 찾기
inertias = []
silhouettes = []
K_range = range(2, 11)
for k in K_range:
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
kmeans.fit(X_scaled)
inertias.append(kmeans.inertia_)
silhouettes.append(silhouette_score(X_scaled, kmeans.labels_))
# 최적 K로 클러스터링 (silhouette 최대값 기준)
best_k = K_range[np.argmax(silhouettes)]
print(f"최적 K: {best_k}")
kmeans_final = KMeans(n_clusters=best_k, random_state=42, n_init=10)
labels = kmeans_final.fit_predict(X_scaled)
print(f"Silhouette Score: {silhouette_score(X_scaled, labels):.3f}")
print(f"각 군집 크기: {np.bincount(labels)}")
"We performed customer segmentation with K-Means. Checking with the Elbow Method, K=5 was optimal, and the clusters were well separated with a Silhouette Score of 0.62. We can build a marketing strategy around five groups such as VIP, regular, and churn-risk."
"K-Means is a distance-based algorithm, so it is sensitive to scale. Normalization with StandardScaler is essential, and since results vary with the choice of initial centroids, we improve stability with k-means++ or multiple runs (n_init)."
"For non-spherical clusters or clusters of different densities, DBSCAN is more suitable than K-Means. But because it is easy to interpret and fast, it's good to start with K-Means in the early stages of exploratory analysis."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If features have different scales, distance calculations are distorted. Be sure to normalize with StandardScaler or MinMaxScaler.
Don't rely on intuition; determine K objectively using the Elbow Method and Silhouette Score.
To reduce dependence on initial values, set n_init=10 or higher to run multiple times and select the best result.