惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Apple Machine Learning Research
Apple Machine Learning Research
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
G
Google Developers Blog
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Threat Research - Cisco Blogs
A
Arctic Wolf
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
博客园 - 【当耐特】
AWS News Blog
AWS News Blog
U
Unit 42
V
Vulnerabilities – Threatpost
P
Privacy International News Feed
T
Tor Project blog
Microsoft Security Blog
Microsoft Security Blog
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
爱范儿
爱范儿
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Recorded Future
Recorded Future
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
Latest news
Latest news
GbyAI
GbyAI
S
SegmentFault 最新的问题
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
Hacker News: Ask HN
Hacker News: Ask HN
美团技术团队
N
News | PayPal Newsroom
J
Java Code Geeks
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Hacker News
The Hacker News
The GitHub Blog
The GitHub Blog
V
V2EX
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Security Latest
Security Latest
博客园 - 叶小钗
P
Palo Alto Networks Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
67. DBSCAN: Clustering That Handles Messy Data
Akhilesh · 2026-05-11 · via DEV Community

Last post K-Means failed on crescent-shaped data. It cut across the natural curves instead of following them. You also had to tell it K upfront. And one outlier could drag a centroid completely off course.

DBSCAN fixes all three problems.

It finds clusters based on density, not distance to a centroid. It discovers K automatically. It labels outliers explicitly instead of forcing them into a cluster.

Different idea. Different use cases. Worth knowing.


What You'll Learn Here

  • How density-based clustering works
  • What eps and min_samples actually control
  • Core points, border points, and noise points explained
  • How to tune DBSCAN parameters properly
  • When DBSCAN wins and when K-Means is still better
  • Anomaly detection with DBSCAN
  • Full working code

The Core Idea: Density

K-Means asks: what's the nearest centroid?

DBSCAN asks: how many neighbors does this point have within radius epsilon?

If a point has at least min_samples neighbors within distance eps, it's a core point. Core points form the dense heart of a cluster.

Points that are within eps of a core point but don't have enough neighbors themselves are border points. They're on the edge of a cluster.

Points that are not within eps of any core point are noise. DBSCAN labels them -1. They don't belong to any cluster.

Core point:   has >= min_samples neighbors within eps
Border point: within eps of a core point, but < min_samples neighbors itself
Noise:        not within eps of any core point

Enter fullscreen mode Exit fullscreen mode

Two clusters are distinct if there's no chain of core points connecting them.


Visualizing the Three Point Types

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN

# Data that K-Means can't handle
X_moons, _ = make_moons(n_samples=300, noise=0.08, random_state=42)

# Run DBSCAN
db = DBSCAN(eps=0.2, min_samples=5)
labels = db.fit_predict(X_moons)

# Identify point types
core_mask   = np.zeros_like(labels, dtype=bool)
core_mask[db.core_sample_indices_] = True
border_mask = (~core_mask) & (labels != -1)
noise_mask  = labels == -1

print(f"Core points:   {core_mask.sum()}")
print(f"Border points: {border_mask.sum()}")
print(f"Noise points:  {noise_mask.sum()}")
print(f"Clusters found: {len(set(labels)) - (1 if -1 in labels else 0)}")

Enter fullscreen mode Exit fullscreen mode

Output:

Core points:   250
Border points: 45
Noise points:  5
Clusters found: 2

Enter fullscreen mode Exit fullscreen mode

# Plot each type differently
plt.figure(figsize=(8, 5))

# Core points colored by cluster
plt.scatter(X_moons[core_mask, 0],   X_moons[core_mask, 1],
            c=labels[core_mask], cmap='bwr', s=40, alpha=0.8, label='Core')

# Border points same color, smaller
plt.scatter(X_moons[border_mask, 0], X_moons[border_mask, 1],
            c=labels[border_mask], cmap='bwr', s=15, alpha=0.5, label='Border')

# Noise in black
plt.scatter(X_moons[noise_mask, 0],  X_moons[noise_mask, 1],
            c='black', s=60, marker='x', linewidths=2, label='Noise')

plt.title('DBSCAN: Core, Border, and Noise Points')
plt.legend()
plt.savefig('dbscan_point_types.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode


Comparing DBSCAN to K-Means on Shapes K-Means Can't Handle

from sklearn.cluster import KMeans
from sklearn.datasets import make_circles

fig, axes = plt.subplots(2, 3, figsize=(15, 9))
datasets = [
    ('Moons',   make_moons(n_samples=300,   noise=0.08, random_state=42)),
    ('Circles', make_circles(n_samples=300, noise=0.05, factor=0.4, random_state=42)),
]

# Add a blob dataset with outliers
np.random.seed(42)
from sklearn.datasets import make_blobs
X_blob, _ = make_blobs(n_samples=280, centers=3, random_state=42)
X_outliers = np.random.uniform(-10, 10, (20, 2))
X_noise_data = np.vstack([X_blob, X_outliers])
datasets.append(('Blobs + Outliers', (X_noise_data, None)))

dbscan_params = [
    {'eps': 0.2,  'min_samples': 5},
    {'eps': 0.3,  'min_samples': 5},
    {'eps': 1.5,  'min_samples': 5},
]

for col, ((name, (X_d, _)), params) in enumerate(zip(datasets, dbscan_params)):

    # K-Means
    km = KMeans(n_clusters=2 if col < 2 else 3, random_state=42, n_init=10)
    km_labels = km.fit_predict(X_d)
    axes[0, col].scatter(X_d[:, 0], X_d[:, 1], c=km_labels, cmap='tab10', s=20, alpha=0.7)
    axes[0, col].set_title(f'K-Means on {name}')

    # DBSCAN
    db_d = DBSCAN(**params)
    db_labels = db_d.fit_predict(X_d)
    n_clusters = len(set(db_labels)) - (1 if -1 in db_labels else 0)
    axes[1, col].scatter(X_d[:, 0], X_d[:, 1], c=db_labels, cmap='tab10', s=20, alpha=0.7)
    axes[1, col].set_title(f'DBSCAN on {name} ({n_clusters} clusters)')

plt.tight_layout()
plt.savefig('dbscan_vs_kmeans.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

DBSCAN correctly follows the crescent and circle shapes. K-Means cuts them up with straight boundaries.


The Two Parameters: eps and min_samples

These are the only two knobs in DBSCAN. Getting them right is the main challenge.

eps (epsilon): the radius of the neighborhood around each point. If you can reach another point within eps distance, they're neighbors.

  • Too small: most points become noise. Clusters fragment.
  • Too large: everything merges into one big cluster.

min_samples: minimum number of neighbors within eps to be a core point.

  • Too small (like 2): noisy points accidentally become core points.
  • Too large: real cluster members get labeled as noise.
from sklearn.preprocessing import StandardScaler

# Always scale before DBSCAN
X_s = StandardScaler().fit_transform(X_moons)

print(f"{'eps':<8} {'min_s':<8} {'Clusters':<12} {'Noise %'}")
print("-" * 42)

for eps in [0.1, 0.2, 0.3, 0.5, 1.0]:
    for min_s in [3, 5, 10]:
        db_test = DBSCAN(eps=eps, min_samples=min_s)
        lbl = db_test.fit_predict(X_s)
        n_clusters = len(set(lbl)) - (1 if -1 in lbl else 0)
        noise_pct  = (lbl == -1).mean() * 100
        print(f"{eps:<8} {min_s:<8} {n_clusters:<12} {noise_pct:.1f}%")
    print()

Enter fullscreen mode Exit fullscreen mode

Output:

eps      min_s    Clusters     Noise %
------------------------------------------
0.1      3        8            7.7%
0.1      5        5            19.0%
0.1      10       2            42.3%

0.2      3        2            0.3%
0.2      5        2            1.7%    <- good
0.2      10       2            11.3%

0.3      3        2            0.0%
0.3      5        2            0.0%
0.3      10       2            0.0%

0.5      3        1            0.0%
0.5      5        1            0.0%    <- everything merged
...

Enter fullscreen mode Exit fullscreen mode

At eps=0.2, min_samples=5 the algorithm finds 2 clusters with minimal noise. That's the sweet spot for this data.


The K-Distance Graph: Finding eps Systematically

You shouldn't guess eps. There's a principled way to find a good starting value.

For each point, calculate the distance to its K-th nearest neighbor (where K = min_samples). Sort those distances and plot them. Look for the "knee" in the curve.

from sklearn.neighbors import NearestNeighbors

min_samples = 5

# Fit nearest neighbors
nbrs = NearestNeighbors(n_neighbors=min_samples)
nbrs.fit(X_s)

# Get distances to min_samples-th nearest neighbor
distances, _ = nbrs.kneighbors(X_s)
kth_distances = distances[:, -1]  # distance to k-th neighbor
kth_distances_sorted = np.sort(kth_distances)[::-1]

plt.figure(figsize=(8, 5))
plt.plot(kth_distances_sorted, color='blue', linewidth=2)
plt.xlabel('Points (sorted by distance)')
plt.ylabel(f'Distance to {min_samples}-th nearest neighbor')
plt.title('K-Distance Graph: Look for the Knee')
plt.grid(True, alpha=0.3)
plt.savefig('k_distance_graph.png', dpi=100)
plt.show()

# The knee is where the curve bends sharply
# Points above the knee → noise
# Points below the knee → cluster members
print("Look for the knee in the plot to choose eps")
print(f"Suggested eps range: {kth_distances_sorted[int(len(kth_distances_sorted)*0.1):.3f}"
      f" to {kth_distances_sorted[int(len(kth_distances_sorted)*0.05):.3f}")

Enter fullscreen mode Exit fullscreen mode

The knee in the K-distance graph is your suggested eps. Above that value, you start labeling too many points as noise. Below it, everything merges.


Anomaly Detection With DBSCAN

DBSCAN's noise label (-1) is naturally useful for anomaly detection. Points that don't belong to any cluster are outliers.

import pandas as pd

# Simulate transaction data with some fraudulent transactions
np.random.seed(42)
n_normal  = 500
n_fraud   = 20

normal_transactions = pd.DataFrame({
    'amount':   np.random.normal(50, 15, n_normal),
    'hour':     np.random.randint(8, 20, n_normal),     # normal business hours
    'items':    np.random.randint(1, 10, n_normal),
})

fraud_transactions = pd.DataFrame({
    'amount':  np.random.normal(800, 100, n_fraud),     # unusually large amounts
    'hour':    np.random.randint(0, 5, n_fraud),         # odd hours
    'items':   np.random.randint(20, 50, n_fraud),       # many items
})

all_data = pd.concat([normal_transactions, fraud_transactions], ignore_index=True)
true_fraud = np.array([0]*n_normal + [1]*n_fraud)

# Scale and cluster
from sklearn.preprocessing import StandardScaler
X_trans = StandardScaler().fit_transform(all_data)

db_fraud = DBSCAN(eps=0.5, min_samples=10)
labels_fraud = db_fraud.fit_predict(X_trans)

# Points labeled -1 are anomalies
predicted_fraud = (labels_fraud == -1).astype(int)

from sklearn.metrics import classification_report
print("Anomaly Detection Results:")
print(classification_report(true_fraud, predicted_fraud,
                              target_names=['normal', 'fraud']))

Enter fullscreen mode Exit fullscreen mode

The fraud transactions cluster away from normal ones. DBSCAN labels them as noise. That noise label becomes your fraud flag.


DBSCAN on Real Data: Iris

from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import adjusted_rand_score, silhouette_score

iris = load_iris()
X_iris = StandardScaler().fit_transform(iris.data)
y_iris = iris.target

# Try different parameters
print(f"{'eps':<8} {'min_s':<8} {'K':<6} {'Noise':<8} {'ARI':<8} {'Sil'}")
print("-" * 50)

for eps in [0.5, 0.8, 1.0, 1.2, 1.5]:
    for min_s in [3, 5, 8]:
        db_iris = DBSCAN(eps=eps, min_samples=min_s)
        lbl = db_iris.fit_predict(X_iris)
        n_k    = len(set(lbl)) - (1 if -1 in lbl else 0)
        n_noise = (lbl == -1).sum()

        if n_k >= 2:  # silhouette needs at least 2 clusters
            sil = silhouette_score(X_iris, lbl) if n_k >= 2 else 0
            ari = adjusted_rand_score(y_iris, lbl)
            print(f"{eps:<8} {min_s:<8} {n_k:<6} {n_noise:<8} {ari:.3f}    {sil:.3f}")

Enter fullscreen mode Exit fullscreen mode


DBSCAN vs K-Means: When to Use Which

Use DBSCAN when:
- You don't know K upfront
- Clusters have irregular shapes (crescents, rings, blobs of any form)
- You want outlier detection built in
- Clusters have very different sizes or densities (though DBSCAN struggles with varying density)
- Data has meaningful noise that shouldn't be forced into a cluster

Use K-Means when:
- Clusters are roughly spherical/convex
- You know approximately how many clusters you want
- Dataset is very large (DBSCAN is slower on millions of points)
- You need fast, predictable results
- All data should be assigned to a cluster (no noise points)

Enter fullscreen mode Exit fullscreen mode

# Quick runtime comparison on larger data
import time
from sklearn.datasets import make_blobs

X_large, _ = make_blobs(n_samples=50000, centers=5, random_state=42)
X_large_s  = StandardScaler().fit_transform(X_large)

# K-Means
start = time.time()
KMeans(n_clusters=5, random_state=42, n_init=3).fit(X_large_s)
print(f"K-Means (50k points): {time.time()-start:.2f}s")

# DBSCAN
start = time.time()
DBSCAN(eps=0.3, min_samples=10).fit(X_large_s)
print(f"DBSCAN  (50k points): {time.time()-start:.2f}s")

Enter fullscreen mode Exit fullscreen mode

Output:

K-Means (50k points): 0.38s
DBSCAN  (50k points): 2.14s

Enter fullscreen mode Exit fullscreen mode

K-Means is significantly faster on large datasets. For very large data, consider HDBSCAN or Approximate Nearest Neighbor versions of DBSCAN.


Complete Workflow With Best Practices

from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import silhouette_score
import numpy as np
import matplotlib.pyplot as plt

def run_dbscan(X, min_samples=5, plot=True):

    # Step 1: Scale
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)

    # Step 2: Find eps using k-distance graph
    nbrs = NearestNeighbors(n_neighbors=min_samples).fit(X_scaled)
    distances, _ = nbrs.kneighbors(X_scaled)
    kth_dist = np.sort(distances[:, -1])[::-1]

    # Step 3: Fit DBSCAN with suggested eps
    # Using the 95th percentile of the k-distance as eps
    suggested_eps = np.percentile(distances[:, -1], 5)
    print(f"Suggested eps: {suggested_eps:.3f}")

    db = DBSCAN(eps=suggested_eps, min_samples=min_samples)
    labels = db.fit_predict(X_scaled)

    n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
    n_noise    = (labels == -1).sum()

    print(f"Clusters found: {n_clusters}")
    print(f"Noise points:   {n_noise} ({n_noise/len(X)*100:.1f}%)")

    if n_clusters >= 2:
        sil = silhouette_score(X_scaled, labels)
        print(f"Silhouette score: {sil:.3f}")

    if plot and X.shape[1] == 2:
        plt.figure(figsize=(7, 5))
        unique_labels = set(labels)
        colors = plt.cm.tab10(np.linspace(0, 1, len(unique_labels)))

        for label, color in zip(sorted(unique_labels), colors):
            if label == -1:
                plt.scatter(X[labels == label, 0], X[labels == label, 1],
                            c='black', s=60, marker='x', label='Noise')
            else:
                plt.scatter(X[labels == label, 0], X[labels == label, 1],
                            color=color, s=30, alpha=0.7, label=f'Cluster {label}')

        plt.title(f'DBSCAN Result: {n_clusters} clusters')
        plt.legend()
        plt.savefig('dbscan_result.png', dpi=100)
        plt.show()

    return labels

X_demo, _ = make_moons(n_samples=300, noise=0.08, random_state=42)
labels_demo = run_dbscan(X_demo, min_samples=5)

Enter fullscreen mode Exit fullscreen mode


Quick Cheat Sheet

Task Code
Basic DBSCAN DBSCAN(eps=0.5, min_samples=5).fit_predict(X)
Always scale first StandardScaler().fit_transform(X)
Find eps K-distance graph: plot sorted distances to k-th neighbor
Get noise points labels == -1
Get core points db.core_sample_indices_
Count clusters len(set(labels)) - (1 if -1 in labels else 0)
Evaluate quality silhouette_score(X, labels)
Compare to truth adjusted_rand_score(true_labels, labels)

Practice Challenges

Level 1:
Run DBSCAN on make_circles(noise=0.05) with K-Means also on the same data. Plot both results side by side. Which one correctly identifies the two circles?

Level 2:
On the iris dataset, use the k-distance graph to find a good eps. Then tune min_samples between 3 and 15. Report the ARI and silhouette score for each combination. Which parameters give the closest match to the true species?

Level 3:
Generate a dataset with 3 clusters of very different sizes (100, 500, 1000 points) plus 50 outliers. Run both K-Means and DBSCAN. Compare how many outliers each one correctly identifies. Does DBSCAN handle the size difference well?


References


Next up, Post 68: PCA: Shrinking Data Without Losing Information. Too many features slow everything down and cause the curse of dimensionality. PCA finds the directions of maximum variance and lets you keep 95% of the information in far fewer dimensions.