Surya_from_1627

USML1

Aug 17th, 2026
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. # Generate sample data
  5. from sklearn.datasets import make_blobs
  6. X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
  7.  
  8. # Number of clusters
  9. k = 4
  10.  
  11. # Initialize centroids randomly from the data points
  12. def initialize_centroids(X, k):
  13.     indices = np.random.choice(X.shape[0], k, replace=False)
  14.     return X[indices]
  15.  
  16. # Assign each point to the nearest centroid
  17. def assign_clusters(X, centroids):
  18.     distances = np.linalg.norm(X[:, np.newaxis] - centroids, axis=2)
  19.     return np.argmin(distances, axis=1)
  20.  
  21. # Recalculate centroids
  22. def update_centroids(X, labels, k):
  23.     new_centroids = np.array([X[labels == i].mean(axis=0) for i in range(k)])
  24.     return new_centroids
  25.  
  26. # K-means main function
  27. def k_means(X, k, iterations=100):
  28.     centroids = initialize_centroids(X, k)
  29.  
  30.     for _ in range(iterations):
  31.         labels = assign_clusters(X, centroids)
  32.         new_centroids = update_centroids(X, labels, k)
  33.  
  34.         # Stop if centroids do not change
  35.         if np.all(centroids == new_centroids):
  36.             break
  37.         centroids = new_centroids
  38.  
  39.     return centroids, labels
  40.  
  41. # Run K-means
  42. centroids, labels = k_means(X, k)
  43.  
  44. # Visualize results
  45. plt.figure(figsize=(8, 6))
  46. plt.scatter(X[:, 0], X[:, 1], c=labels, s=30, cmap='viridis')
  47. plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, alpha=0.6, marker='X')
  48. plt.title("K-Means Clustering")
  49. plt.show()
  50.  
Advertisement
Add Comment
Please, Sign In to add comment