Practical Exercises Chapter 5
Exercise 1: K-Means Clustering
Task: You are given a synthetic dataset containing two features. Use K-Means clustering to group the data into three clusters and visualize the clusters with their centroids.
Solution:
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
X = np.array([[2.5, 3.1], [1.8, 2.3], [3.4, 3.0], [4.1, 4.2], [1.9, 2.8],
[3.6, 3.7], [2.2, 3.5], [4.0, 4.5]])
# Apply K-Means clustering with 3 clusters
kmeans = KMeans(n_clusters=3, random_state=42)
# Get cluster labels and centroids ...