</>
Skip to content
SciPy lessons (19/25)

SciPy — Clustering

K-means clustering

from scipy.cluster.vq import kmeans, vq
import numpy as np

# Generate data
data = np.random.rand(100, 2)

# Cluster into 3 groups
centroids, distortion = kmeans(data, 3)
print(f"Centroids:\n{centroids}")
print(f"Distortion: {distortion:.4f}")

# Assign points to clusters
labels, _ = vq(data, centroids)
print(f"Labels: {np.unique(labels)}")

Hierarchical clustering

from scipy.cluster.hierarchy import linkage, fcluster
import numpy as np

data = np.random.rand(50, 2)

# Create linkage matrix
Z = linkage(data, method='ward')

# Form clusters
clusters = fcluster(Z, t=3, criterion='maxclust')
print(f"Clusters: {np.unique(clusters)}")

Dendrogram

from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt

dendrogram(Z)
plt.title('Dendrogram')
plt.show()

Distance matrices

from scipy.spatial.distance import pdist, squareform
import numpy as np

data = np.random.rand(10, 2)

# Compute pairwise distances
distances = pdist(data)
dist_matrix = squareform(distances)
print(f"Distance matrix shape: {dist_matrix.shape}")

Silhouette analysis

from sklearn.metrics import silhouette_score
from scipy.cluster.vq import kmeans, vq

data = np.random.rand(100, 2)
centroids, _ = kmeans(data, 3)
labels, _ = vq(data, centroids)

score = silhouette_score(data, labels)
print(f"Silhouette score: {score:.4f}")

Mini Practice

  1. Perform K-means clustering
  2. Create hierarchical clustering
  3. Visualize dendrogram
  4. Evaluate clustering quality

Up Next

Continue with I/O - File operations.

Related Topics

Frequently Asked Questions about Clustering

What is Clustering in SciPy?

Clustering is a fundamental concept in SciPy. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Clustering?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Clustering.

Why is Clustering important in SciPy?

Clustering is essential for SciPy development. Understanding this concept will help you write better code and solve real-world problems more effectively.