import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# Sample data: annual income and spending score of customers
X = np.array([
[15, 39], [16, 81], [17, 6], [18, 77], [19, 40],
[20, 76], [21, 6], [22, 94], [23, 3], [24, 72],
[25, 14], [26, 99], [27, 15], [28, 77], [29, 13],
[30, 79], [31, 35], [32, 66], [33, 29], [34, 98]
])
# Try different k values and plot inertia
inertia_values = []
k_values = range(1, 11)
for k in k_values:
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
kmeans.fit(X)
inertia_values.append(kmeans.inertia_)
plt.plot(k_values, inertia_values, 'bo-')
plt.xlabel('Number of clusters (k)')
plt.ylabel('Inertia')
plt.title('Elbow Method for Optimal k')
plt.show()
# Choose k=4 based on elbow method
kmeans = KMeans(n_clusters=4, random_state=42, n_init=10)
kmeans.fit(X)
labels = kmeans.labels_
centers = kmeans.cluster_centers_
print(f'Inertia with k=4: {kmeans.inertia_}')
# Plot clusters
colors = ['red', 'green', 'blue', 'purple']
for i in range(4):
cluster_points = X[labels == i]
plt.scatter(cluster_points[:, 0], cluster_points[:, 1], c=colors[i], label=f'Cluster {i+1}')
plt.scatter(centers[:, 0], centers[:, 1], c='yellow', marker='X', s=200, label='Centers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score')
plt.title('Customer Segments with k=4')
plt.legend()
plt.show()