1. Understand the Goal: The user wants a program that implements clustering algorithms.
-
Identify the Requirements:
- Language: Python is the standard for data science and machine learning, so I should use that.
- Scope: "Clustering algorithms" implies more than just one. I should provide a few distinct and popular ones to demonstrate variety.
- Functionality:
- Data generation (to have something to cluster).
- Implementation of the algorithms (or usage of a library, or both).
- Visualization (to see the results).
-
Choose the Algorithms:
- K-Means: The most popular centroid-based algorithm. Essential.
- Hierarchical (Agglomerative): A common connectivity-based algorithm. Good contrast to K-Means.
- DBSCAN: A density-based algorithm. Great for arbitrary shapes and noise.
-
Determine the Approach:
- From Scratch vs. Library: Implementing complex algorithms from scratch (like DBSCAN) can be verbose and error-prone for a general request. Using
scikit-learn is the industry standard. However, to show "implementation," maybe implementing K-Means from scratch is a nice touch to demonstrate understanding, while using scikit-learn for the others to show practical usage.
- Decision: I will provide a hybrid approach.
- Part 1: K-Means from scratch (educational, concise logic).
- Part 2: Comparison of K-Means, Hierarchical, and DBSCAN using
scikit-learn (practical, powerful visualization).
-
Drafting the Code (Mental or Scratchpad):
-
Setup: Imports (numpy, matplotlib, sklearn).
-
Part 1: K-Means From Scratch
- Init centroids randomly.
- Loop:
- Assign points to nearest centroid.
- Update centroids to be the mean of assigned points.
- Repeat until convergence.
-
Part 2: Scikit-Learn Implementation
- Generate data:
make_blobs (for clusters) and make_circles (to show K-Means failing vs DBSCAN succeeding).
- Run K-Means.
- Run Agglomerative Clustering.
- Run DBSCAN.
- Plot results side-by-side.
-
Refining the Code Structure:
- I need a clear class structure or function structure. A
KMeansCustom class is good.
- For the comparison, I'll create a function
compare_algorithms that takes data and runs the three methods.
-
Writing the Python Code (Iterative refinement):
-
Imports: numpy, matplotlib.pyplot, sklearn.datasets, sklearn.cluster, sklearn.preprocessing.
-
Custom K-Means:
__init__(k=3, max_iters=100)
fit(X): Calculate centroids.
predict(X): Assign clusters.
- Need Euclidean distance helper.
-
Demonstration Data:
- Dataset A: Blobs (Spherical clusters). K-Means works well.
- Dataset B: Moons/Circles (Non-linear). DBSCAN works well, K-Means fails. Self-correction: Keep it simple for a basic request. Just use one dataset or maybe two to highlight strengths. Let's stick to
make_blobs for the general demo, but mention that DBSCAN handles noise better.
- Actually, showing K-Means fail on circles and DBSCAN succeed is a powerful demonstration of why different algorithms exist. I will include a section for "Scenario: Non-Linear Data".
-
Adding Explanations:
- Code comments are crucial.
- A text explanation of how each works (briefly).
- Instructions on how to run it (requirements.txt).
-
Final Code Assembly:
- Create a complete script.
- Include the "From Scratch" class.
- Include the "Library" comparison.
-
Review against User Prompt:
- "Write a program that implements clustering algorithms." -> Done. It implements K-Means logic manually and applies others via library.
-
Output Generation: (This matches the provided good response).
- Structure:
- Prerequisites.
- Implementation of K-Means from scratch (Conceptual understanding).
- Comparative implementation using Scikit-Learn (Practical application).
- Visualization.
-
Self-Correction during drafting:
- Initial thought: Just use
sklearn.
- Correction: That's just calling functions, not "implementing" in the CS sense. I must write the algorithm logic for at least one.
- Complexity check: Don't make the "from scratch" code too complex (no C++ extensions, pure NumPy).
-
Final Polish: Ensure plots are labeled and distinct. (e.g., Centroids marked with red 'x').
(Self-Correction on the KMeans scratch code):
- Ensure centroid initialization is random from the dataset to avoid starting in empty space.
- Handle empty clusters? (Advanced, skip for a basic demo, but maybe re-initialize if a cluster dies). I'll stick to simple re-initialization if a cluster gets no points to keep code readable.
Let's write the response based on this plan.
- Language: Python.
- Libraries: NumPy, Matplotlib, Scikit-learn.
- Algorithms: K-Means (Manual & Lib), DBSCAN (Lib), Agglomerative (Lib).
(Drafting the response...) -> See final output.
Here is a complete Python program that demonstrates clustering algorithms.
To make this robust and educational, I have split the code into two parts:
- From Scratch: A manual implementation of the K-Means algorithm using only
numpy so you can understand the math behind it.
- Using Scikit-Learn: A comparison of three popular algorithms (K-Means, DBSCAN, and Agglomerative Clustering) using the industry-standard library.
Prerequisites
You will need to install the following libraries:
pip install numpy matplotlib scikit-learn
The Python Program
Save this code into a file named clustering_demo.py and run it.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs, make_moons
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.preprocessing import StandardScaler
# ==========================================
# Part 1: K-Means Implementation from Scratch
# ==========================================
class KMeansCustom:
def __init__(self, k=3, max_iters=100, tol=1e-4):
self.k = k
self.max_iters = max_iters
self.tol = tol # Tolerance for convergence
self.centroids = None
self.labels = None
def fit(self, X):
# Step 1: Initialize centroids randomly from the data points
indices = np.random.choice(X.shape[0], self.k, replace=False)
self.centroids = X[indices]
for i in range(self.max_iters):
# Step 2: Assign clusters based on closest centroid
# Calculate distance from every point to every centroid
distances = self._calc_distances(X)
self.labels = np.argmin(distances, axis=1)
# Step 3: Update centroids
new_centroids = np.array([X[self.labels == j].mean(axis=0) for j in range(self.k)])
# Check for convergence (if centroids barely moved)
if np.all(np.abs(new_centroids - self.centroids) < self.tol):
print(f"Converged at iteration {i}")
break
self.centroids = new_centroids
def _calc_distances(self, X):
# Computes Euclidean distance between all points and all centroids
# Returns matrix of shape (n_samples, k)
distances = np.zeros((X.shape[0], self.k))
for i in range(self.k):
# Euclidean distance: sqrt(sum((x - centroid)^2))
distances[:, i] = np.linalg.norm(X - self.centroids[i], axis=1)
return distances
def predict(self, X):
distances = self._calc_distances(X)
return np.argmin(distances, axis=1)
# ==========================================
# Part 2: Comparison of Algorithms
# ==========================================
def plot_comparison():
# Generate synthetic data
# We use 'moons' data because K-Means struggles with non-spherical shapes
X_moons, _ = make_moons(n_samples=300, noise=0.05, random_state=42)
X_moons = StandardScaler().fit_transform(X_moons)
# Also generate standard blobs for context
X_blobs, _ = make_blobs(n_samples=300, centers=3, cluster_std=0.6, random_state=0)
X_blobs = StandardScaler().fit_transform(X_blobs)
# Define algorithms
# 1. K-Means (Good for spherical clusters)
kmeans = KMeans(n_clusters=2, random_state=42)
# 2. Agglomerative Hierarchical (Good for structured clusters)
agglomerative = AgglomerativeClustering(n_clusters=2)
# 3. DBSCAN (Density-Based - Good for arbitrary shapes and noise)
dbscan = DBSCAN(eps=0.3, min_samples=5)
datasets = [(X_blobs, "Blobs Data"), (X_moons, "Moons Data")]
algorithms = [
(kmeans, "K-Means"),
(agglomerative, "Agglomerative"),
(dbscan, "DBSCAN")
]
fig, axes = plt.subplots(2, 4, figsize=(18, 9))
# Loop through data and algorithms to plot
for row_idx, (X, data_name) in enumerate(datasets):
# Plot raw data first
axes[row_idx, 0].scatter(X[:, 0], X[:, 1], c='gray', s=30, edgecolor='k')
axes[row_idx, 0].set_title(f"Raw {data_name}")
axes[row_idx, 0].set_xticks([])
axes[row_idx, 0].set_yticks([])
for col_idx, (algo, algo_name) in enumerate(algorithms):
# Fit model
clusters = algo.fit_predict(X)
# Plot results
ax = axes[row_idx, col_idx + 1]
# DBSCAN marks noise as -1, so we handle coloring differently
if algo_name == "DBSCAN":
unique_labels = set(clusters)
colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]
for k, col in zip(unique_labels, colors):
if k == -1:
# Black used for noise.
col = [0, 0, 0, 1]
class_member_mask = (clusters == k)
xy = X[class_member_mask]
ax.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), markersize=6)
else:
ax.scatter(X[:, 0], X[:, 1], c=clusters, cmap='viridis', s=30, edgecolor='k')
ax.set_title(f"{algo_name}")
ax.set_xticks([])
ax.set_yticks([])
plt.suptitle("Clustering Algorithm Comparison\n(Top: Spherical Data | Bottom: Complex Data)", fontsize=16)
plt.tight_layout()
plt.show()
# ==========================================
# Main Execution
# ==========================================
if __name__ == "__main__":
print("--- Demo 1: Custom K-Means Implementation ---")
# Generate simple data to test custom class
X_simple, _ = make_blobs(n_samples=150, centers=3, random_state=42)
custom_kmeans = KMeansCustom(k=3)
custom_kmeans.fit(X_simple)
plt.figure(figsize=(6, 5))
plt.scatter(X_simple[:, 0], X_simple[:, 1], c=custom_kmeans.labels, cmap='viridis', s=30)
plt.scatter(custom_kmeans.centroids[:, 0], custom_kmeans.centroids[:, 1], c='red', marker='x', s=200, linewidths=3, label='Centroids')
plt.title("Custom K-Means Implementation (From Scratch)")
plt.legend()
plt.show()
print("\n--- Demo 2: Scikit-Learn Comparison ---")
print("Displaying comparison of K-Means, Hierarchical, and DBSCAN.")
plot_comparison()
How it works
-
KMeansCustom Class:
- Initialization: Picks k random points from the data as starting "centroids".
- Distance Calculation: Uses Euclidean distance ((x1−x) to measure how close every point is to every centroid.