DBSCAN
Density-Based Spatial Clustering
A density-based clustering algorithm. Useful for anomaly detection.
Density-Based Spatial Clustering
A density-based clustering algorithm. Useful for anomaly detection.
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is an unsupervised learning algorithm that forms clusters based on the density of data points. Unlike K-Means, it does not require the number of clusters to be specified in advance, and it can discover clusters of arbitrary (non-spherical) shape.
Published in 1996 by Martin Ester et al., this algorithm was developed to solve the problem of clustering data containing noise in spatial databases. As its name suggests, it was originally designed for geographic information systems (GIS) and spatial data analysis.
The core principle is that if there are at least min_samples neighboring points within a radius of eps (epsilon), the point is classified as a "core point," and these core points are connected to expand the cluster. Points that do not belong to any cluster are automatically labeled as noise (-1).
In practice, DBSCAN is widely used for anomaly detection (fraud detection), image segmentation, customer behavior pattern analysis, and hotspot identification in location-based services. In particular, it performs much better than K-Means when the data contains a lot of noise or the cluster shapes are irregular.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
# 반달 모양 데이터 생성 (K-Means가 실패하는 대표적 케이스)
X, y_true = make_moons(n_samples=300, noise=0.05, random_state=42)
# 데이터 스케일링 (DBSCAN 필수 전처리)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# DBSCAN 클러스터링
# eps: 이웃 반경, min_samples: 코어 포인트 최소 이웃 수
dbscan = DBSCAN(eps=0.3, min_samples=5)
labels = dbscan.fit_predict(X_scaled)
# 결과 분석
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = list(labels).count(-1)
print(f"발견된 클러스터 수: {n_clusters}")
print(f"노이즈 포인트 수: {n_noise}")
print(f"코어 포인트 수: {len(dbscan.core_sample_indices_)}")
# 시각화
plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=labels, cmap='viridis')
plt.title(f'DBSCAN Clustering (clusters={n_clusters}, noise={n_noise})')
plt.show()
"DBSCAN is well suited for fraudulent transaction detection. Normal transactions are densely packed, while fraudulent transactions are scattered. Unlike K-Means, it automatically classifies outliers as noise."
"The advantages of DBSCAN are that you do not need to specify the number of clusters in advance and that it can find non-spherical clusters. However, tuning eps and min_samples is important, and for data with varying densities, you should consider HDBSCAN."
"If the data is 2 million records, DBSCAN's O(n²) memory complexity can become a problem. You should consider using the ball_tree or kd_tree algorithm, or an approach that propagates labels after sampling."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
eps is a distance-based parameter. If feature scales differ, a particular feature will dominate the distance calculation. Be sure to preprocess with StandardScaler.
If eps is too large, all points are grouped into a single cluster; if too small, most are classified as noise. Use a k-distance graph (elbow method) to find an appropriate eps.
Set min_samples to at least (number of dimensions + 1), and refer to the elbow point of the k-distance graph for eps. For data with varying densities, use HDBSCAN.