Skip to content
Machine Learning

Clustering

Cluster with KMeans and DBSCAN.

By EZ4Code Team
clusteringunsupervised

Code

import numpy as np
from sklearn.cluster import KMeans, DBSCAN
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score
from sklearn.datasets import make_blobs

X, _ = make_blobs(n_samples=400, centers=4, cluster_std=0.6, random_state=42)

# KMeans
km = KMeans(n_clusters=4, random_state=42, n_init=10)
labels = km.fit_predict(X)
print("kmeans silhouette:", silhouette_score(X, labels))

# DBSCAN finds clusters of arbitrary shape and noise
db = DBSCAN(eps=0.5, min_samples=5).fit(X)
n_clusters = len(set(db.labels_)) - (1 if -1 in db.labels_ else 0)
print("dbscan clusters:", n_clusters)

# Gaussian mixture
gmm = GaussianMixture(n_components=4, random_state=42).fit(X)
gmm_labels = gmm.predict(X)

# Elbow method to pick k
inertias = [KMeans(k, n_init=10, random_state=42).fit(X).inertia_ for k in range(2, 8)]

Explanation

KMeans partitions data into k spherical clusters and reports inertia for the elbow method. DBSCAN finds dense regions of arbitrary shape and labels sparse points as noise, removing the need to set k. silhouette_score measures cluster separation and is a handy metric when ground-truth labels are unavailable.

More Machine Learning Snippets