Certainly! Below is a didactic implementation of the DBSCAN algorithm following the structure of your existing kmedoids.py. Additionally, the clustering.py file has been updated to include the DBSCAN clustering process along with corresponding plots.
File: dbscan.py
import numpy as np
from sklearn.metrics.pairwise import euclidean_distances
class DBSCAN:
def __init__(self, eps=0.5, min_samples=5, distance=euclidean_distances):
"""
Initialize the DBSCAN clustering algorithm.
Parameters:
- eps: float, the maximum distance between two samples for one to be considered
as in the neighborhood of the other.
- min_samples: int, the number of samples in a neighborhood for a point to be
considered as a core point.
- distance: callable, the distance function to use (default is Euclidean distance).
"""
self.eps = eps
self.min_samples = min_samples
self.distance = distance
self.labels_ = None
self.core_sample_indices_ = None
def fit(self, X):
"""
Perform DBSCAN clustering from scratch.
Parameters:
- X: array-like of shape (n_samples, n_features)
"""
n_samples = X.shape[0]
self.labels_ = np.full(n_samples, -1) # Initialize all labels as -1 (noise)
distance_matrix = self.distance(X, X)
visited = np.zeros(n_samples, dtype=bool)
cluster_id = 0
for point_idx in range(n_samples):
if visited[point_idx]:
continue
visited[point_idx] = True
neighbors = self._region_query(distance_matrix, point_idx)
if len(neighbors) < self.min_samples:
self.labels_[point_idx] = -1 # Mark as noise
else:
# Start a new cluster
self._expand_cluster(X, distance_matrix, self.labels_, point_idx, neighbors, cluster_id, visited)
cluster_id += 1
def _region_query(self, distance_matrix, point_idx):
"""
Find all points within `eps` distance of the point with index `point_idx`.
Parameters:
- distance_matrix: precomputed distance matrix
- point_idx: index of the query point
Returns:
- neighbors: list of indices within the `eps` neighborhood
"""
neighbors = np.where(distance_matrix[point_idx] <= self.eps)[0]
return neighbors.tolist()
def _expand_cluster(self, X, distance_matrix, labels, point_idx, neighbors, cluster_id, visited):
"""
Expand the cluster with id `cluster_id` by recursively adding density-reachable points.
Parameters:
- X: array-like, the dataset
- distance_matrix: precomputed distance matrix
- labels: array, current label assignments
- point_idx: index of the starting point
- neighbors: list of neighbor indices
- cluster_id: current cluster id
- visited: array, visited flags for each point
"""
labels[point_idx] = cluster_id
i = 0
while i < len(neighbors):
neighbor_idx = neighbors[i]
if not visited[neighbor_idx]:
visited[neighbor_idx] = True
neighbor_neighbors = self._region_query(distance_matrix, neighbor_idx)
if len(neighbor_neighbors) >= self.min_samples:
neighbors += neighbor_neighbors # Add new neighbors to the list
if labels[neighbor_idx] == -1:
labels[neighbor_idx] = cluster_id # Change label from noise to cluster_id
i += 1
def predict(self, X):
"""
Assign cluster labels to each point in X based on the fitted model.
Parameters:
- X: array-like of shape (n_samples, n_features)
Returns:
- labels: array of cluster labels
"""
if self.labels_ is None:
raise ValueError("DBSCAN has not been fitted yet.")
# For simplicity, predict assigns the same labels as the fitted model
# More advanced implementations might handle new points differently
return self.labels_
File: clustering.py
import numpy as np
from sklearn import datasets
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
from kmeans import KMeans
from kmedoids import KMedoids
from dbscan import DBSCAN # Import the newly created DBSCAN class
def main():
# Generate synthetic data using make_blobs
proc_data, y_true = datasets.make_blobs(n_samples=500,
n_features=2,
centers=4,
cluster_std=1,
center_box=(-10.0, 10.0),
shuffle=True,
random_state=88) # For reproducibility
# Normalize the data
mean = np.mean(proc_data, axis=0)
std = np.std(proc_data, axis=0)
proc_data = (proc_data - mean) / std
# Number of clusters for K-Means and K-Medoids
k_s = 4
#################################################################################################
# K-Means from scratch
kmeans_obj = KMeans(n_clusters=k_s, random_state=42)
kmeans_obj.fit(proc_data)
y_pred_kmeans = kmeans_obj.predict(proc_data)
km_silhouette = silhouette_score(proc_data, y_pred_kmeans)
print(f"Silhouette Coefficient - K-Means: {km_silhouette:.4f}")
plt.figure(figsize=(8, 6))
plt.scatter(proc_data[:, 0], proc_data[:, 1], c=y_pred_kmeans, s=30, cmap='viridis')
plt.title("K-Means Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()
#################################################################################################
# K-Medoids from scratch
kmedoids_obj = KMedoids(n_clusters=k_s, random_state=46)
kmedoids_obj.fit(proc_data)
y_pred_kmedoids = kmedoids_obj.predict(proc_data)
kmedoids_silhouette = silhouette_score(proc_data, y_pred_kmedoids)
print(f"Silhouette Coefficient - K-Medoids: {kmedoids_silhouette:.4f}")
plt.figure(figsize=(8, 6))
plt.scatter(proc_data[:, 0], proc_data[:, 1], c=y_pred_kmedoids, s=30, cmap='viridis')
plt.title("K-Medoids Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()
#################################################################################################
# DBSCAN from scratch
# Choosing DBSCAN parameters: eps and min_samples
# These parameters might need tuning based on the data
dbscan_eps = 0.5
dbscan_min_samples = 5
dbscan_obj = DBSCAN(eps=dbscan_eps, min_samples=dbscan_min_samples)
dbscan_obj.fit(proc_data)
y_pred_dbscan = dbscan_obj.predict(proc_data)
# Handle cases where all points are noise or only one cluster is found
if len(set(y_pred_dbscan)) > 1 and (np.abs(y_pred_dbscan) != -1).sum() > 0:
db_silhouette = silhouette_score(proc_data, y_pred_dbscan)
print(f"Silhouette Coefficient - DBSCAN: {db_silhouette:.4f}")
else:
db_silhouette = -1
print("Silhouette Coefficient - DBSCAN: Not defined (only one cluster or all noise)")
plt.figure(figsize=(8, 6))
# Map noise points to a specific color
unique_labels = set(y_pred_dbscan)
colors = plt.cm.viridis(np.linspace(0, 1, len(unique_labels)))
for label, color in zip(unique_labels, colors):
if label == -1:
# Noise is plotted in black
color = [0, 0, 0, 1]
class_member_mask = (y_pred_dbscan == label)
plt.scatter(proc_data[class_member_mask, 0],
proc_data[class_member_mask, 1],
c=[color],
s=30,
label=f'Cluster {label}' if label != -1 else 'Noise')
plt.title("DBSCAN Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.show()
if __name__ == "__main__":
main()
Explanation of the Implementation
1. dbscan.py
-
Initialization (__init__):
eps: The maximum distance between two samples for them to be considered as neighbors.
min_samples: The number of samples in a neighborhood for a point to be considered a core point.
distance: The distance metric used; by default, Euclidean distance is used.
-
Fitting (fit method):
- Initializes all points as noise (
-1).
- Computes the distance matrix once to optimize neighborhood queries.
- Iterates through each point, expanding clusters when core points are found.
- Assigns cluster labels incrementally.
-
Region Query (_region_query method):
- Finds all points within
eps distance from a given point.
-
Expanding Cluster (_expand_cluster method):
- Recursively adds density-reachable points to the current cluster.
- Updates labels accordingly.
-
Prediction (predict method):
- For simplicity, this implementation assigns the same labels as the fitted model.
- Note: A more advanced implementation might handle unseen points differently.
2. clustering.py
-
Data Preparation:
- Generates synthetic data using
make_blobs.
- Normalizes the data for better clustering performance.
-
K-Means Clustering:
- Fits the K-Means algorithm.
- Computes the silhouette score.
- Plots the clustered data.
-
K-Medoids Clustering:
- Fits the K-Medoids algorithm.
- Computes the silhouette score.
- Plots the clustered data.
-
DBSCAN Clustering:
- Initializes DBSCAN with chosen
eps and min_samples.
- Fits the DBSCAN algorithm.
- Computes the silhouette score only if there is more than one cluster and not all points are noise.
- Plots the clustered data, distinguishing noise points in black.
3. Plotting Considerations
-
Cluster Visualization:
- Each clustering method plots the data points colored by their cluster assignments.
- DBSCAN additionally marks noise points distinctly.
-
Silhouette Score:
- Provides a measure of how similar an object is to its own cluster compared to other clusters.
- A higher score indicates better-defined clusters.
- For DBSCAN, if only one cluster is found or all points are labeled as noise, the silhouette score is not defined.
4. Running the Clustering
To execute the clustering processes and visualize the results:
-
Ensure Directory Structure:
- Place
kmeans.py, kmedoids.py, and dbscan.py in the same directory as clustering.py.
-
Execute the Script:
python clustering.py
This will display plots for K-Means, K-Medoids, and DBSCAN clustering results sequentially, along with their respective silhouette scores.
Notes and Recommendations
Feel free to integrate and modify this implementation based on your specific requirements and data characteristics!