DBSCAN: จุดแกนกลาง จุดขอบ และสัญญาณรบกวน
ผู้เรียนจะกำหนดค่า eps และ min_samples ระบุจุดแกนกลาง จุดขอบ และจุดสัญญาณรบกวนในชุดข้อมูลรูปพระจันทร์เสี้ยว และดู DBSCAN ค้นพบกลุ่มที่ไม่เป็นนูนซึ่ง K-Means มองไม่เห็น
DBSCAN: จุดแกนกลาง จุดขอบ และสัญญาณรบกวน เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why K-Means Fails on Arbitrary Shapes
K-Means assumes clusters are convex and roughly spherical. It fails on crescent, ring, or elongated shapes because it partitions by distance to centroids. DBSCAN (Density-Based Spatial Clustering of Applications with Noise) overcomes this by defining clusters as dense regions separated by low-density areas, discovering clusters of any shape.
Two Key Hyperparameters: eps and min_samples
DBSCAN is controlled by two parameters: eps (epsilon) defines the radius of a neighbourhood around a point, and min_samples sets the minimum number of points (including the point itself) required within that radius to be considered a dense region. Together they determine which points are cores, borders, or noise.
Core Points: The Anchors of Dense Regions
A point is a core point if at least min_samples points (including itself) lie within distance eps. Core points are the seeds from which clusters grow. Every point within the core's neighbourhood is directly reachable from it — the foundation for expanding the cluster.
from sklearn.neighbors import BallTree
import numpy as np
X = np.array([[0, 0], [0.3, 0], [0.6, 0],
[5, 5], [10, 10]])
eps = 1.0
min_samples = 3
tree = BallTree(X)
counts = tree.query_radius(X, r=eps, count_only=True)
core_mask = counts >= min_samples
print('Core points:', np.where(core_mask)[0]) # indices 0, 1, 2Border Points and Density-Reachability
A border point has fewer than min_samples neighbours within eps but lies within the eps-neighbourhood of a core point. It belongs to the cluster of its core point but does not expand the cluster further. A point is density-connected to another if there is a chain of directly-reachable steps linking them through core points.
Noise Points: Outlier Detection for Free
Points that are neither core nor border — isolated points with too few neighbours — are labelled noise (label = -1 in scikit-learn). This makes DBSCAN a natural outlier detector: anomalies that do not belong to any dense cluster are automatically flagged as noise without any extra configuration.
Running DBSCAN in scikit-learn
Use sklearn.cluster.DBSCAN. After fitting, db.labels_ contains integer cluster IDs starting at 0, with -1 for noise. db.core_sample_indices_ lists which samples are core points. The number of clusters is determined automatically — no k needed upfront.
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
import numpy as np
X, _ = make_moons(n_samples=200, noise=0.05, random_state=0)
db = DBSCAN(eps=0.3, min_samples=5)
db.fit(X)
n_clusters = len(set(db.labels_)) - (1 if -1 in db.labels_ else 0)
n_noise = (db.labels_ == -1).sum()
print('Clusters found:', n_clusters)
print('Noise points:', n_noise)
print('Labels (first 10):', db.labels_[:10])DBSCAN on Non-Convex Shapes
DBSCAN excels on datasets like two interlocking moons or concentric rings — shapes where K-Means completely fails. Because DBSCAN expands clusters along density chains, it naturally follows the curved manifold of the data. This is a fundamental algorithmic advantage for geospatial data, biological cell clusters, and anomaly-embedded datasets.
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN, KMeans
from sklearn.datasets import make_moons
X, _ = make_moons(n_samples=300, noise=0.05, random_state=0)
db_labels = DBSCAN(eps=0.25, min_samples=5).fit_predict(X)
km_labels = KMeans(n_clusters=2, random_state=0, n_init=10).fit_predict(X)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.scatter(X[:, 0], X[:, 1], c=db_labels, cmap='tab10')
ax1.set_title('DBSCAN')
ax2.scatter(X[:, 0], X[:, 1], c=km_labels, cmap='tab10')
ax2.set_title('K-Means')
plt.show()Choosing eps: The K-Distance Plot
A practical way to choose eps is to plot the k-distance graph: compute the distance of each point to its kth nearest neighbour (where k = min_samples), sort these distances, and look for the knee. The distance at the knee is a good eps candidate. Points above the knee are in sparse regions (noise); below the knee are in dense regions.
from sklearn.neighbors import NearestNeighbors
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
X, _ = make_moons(n_samples=200, noise=0.05, random_state=0)
min_samples = 5
nn = NearestNeighbors(n_neighbors=min_samples)
nn.fit(X)
distances, _ = nn.kneighbors(X)
k_distances = np.sort(distances[:, -1])[::-1]
plt.plot(k_distances)
plt.xlabel('Points sorted by distance')
plt.ylabel(f'{min_samples}-th nearest neighbour distance')
plt.title('K-Distance Plot for eps selection')
plt.show()Effect of eps and min_samples on Results
Increasing eps merges clusters (eventually everything becomes one cluster). Decreasing eps creates more clusters and more noise. Increasing min_samples requires denser cores, making it harder to form clusters and generating more noise points. Tuning both parameters together is needed — the k-distance plot guides eps while min_samples is typically set to the dimensionality of the data plus one as a starting point.
DBSCAN vs K-Means: When to Use Each
Use DBSCAN when: clusters have irregular shapes, you do not know k in advance, outlier detection is important, or data has varying density. Use K-Means when: clusters are roughly spherical, the dataset is very large (DBSCAN scales as O(n log n) with a spatial index), or you need a specific number of clusters for business reasons like market segmentation into exactly 5 regions.
DBSCAN for Geospatial Clustering
DBSCAN is particularly popular for geospatial clustering (finding hotspots in GPS data) because it naturally identifies dense urban areas while marking sparse rural points as noise. Use metric='haversine' and convert coordinates to radians to cluster by great-circle distance on Earth's surface. The result is geographically meaningful clusters without needing to specify their number.
import numpy as np
from sklearn.cluster import DBSCAN
# Sample GPS coords: (lat, lon) in radians
coords = np.radians([
[40.7128, -74.0060], # NYC
[40.6892, -74.0445], # nearby
[40.7282, -73.7949], # Queens
[51.5074, -0.1278], # London
])
# eps in radians: 1km / earth radius
eps_rad = 1.0 / 6371.0
db = DBSCAN(eps=eps_rad, min_samples=2, metric='haversine')
db.fit(coords)
print('Cluster labels:', db.labels_)Quick Check
Test your understanding of DBSCAN concepts from this lesson.
Lesson Recap
In this lesson you learned: DBSCAN classifies points as core, border, or noise based on the eps radius and min_samples threshold, it discovers clusters of arbitrary shape by chaining density-reachable core points, and noise points (label -1) are automatic outliers — a feature K-Means does not provide. Next up we apply clustering end-to-end in a customer segmentation project.
คำถามที่พบบ่อย
บทเรียน “DBSCAN: จุดแกนกลาง จุดขอบ และสัญญาณรบกวน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “DBSCAN: จุดแกนกลาง จุดขอบ และสัญญาณรบกวน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “DBSCAN: จุดแกนกลาง จุดขอบ และสัญญาณรบกวน”
ผู้เรียนจะกำหนดค่า eps และ min_samples ระบุจุดแกนกลาง จุดขอบ และจุดสัญญาณรบกวนในชุดข้อมูลรูปพระจันทร์เสี้ยว และดู DBSCAN ค้นพบกลุ่มที่ไม่เป็นนูนซึ่ง K-Means มองไม่เห็น คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “DBSCAN: จุดแกนกลาง จุดขอบ และสัญญาณรบกวน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม
ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- K-Means: จุดศูนย์กลาง การกำหนดกลุ่ม และขั้นตอนการปรับปรุง
- การเลือกค่า K: วิธีข้อศอกและคะแนนซิลูเอตต์
- DBSCAN: จุดแกนกลาง จุดขอบ และสัญญาณรบกวน
- การจัดกลุ่มเพื่อแบ่งส่วนลูกค้า: ตัวอย่างตั้งแต่ต้นจนจบ