Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import matplotlib.pyplot as plt
- # Generate sample data
- from sklearn.datasets import make_blobs
- X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
- # Number of clusters
- k = 4
- # Initialize centroids randomly from the data points
- def initialize_centroids(X, k):
- indices = np.random.choice(X.shape[0], k, replace=False)
- return X[indices]
- # Assign each point to the nearest centroid
- def assign_clusters(X, centroids):
- distances = np.linalg.norm(X[:, np.newaxis] - centroids, axis=2)
- return np.argmin(distances, axis=1)
- # Recalculate centroids
- def update_centroids(X, labels, k):
- new_centroids = np.array([X[labels == i].mean(axis=0) for i in range(k)])
- return new_centroids
- # K-means main function
- def k_means(X, k, iterations=100):
- centroids = initialize_centroids(X, k)
- for _ in range(iterations):
- labels = assign_clusters(X, centroids)
- new_centroids = update_centroids(X, labels, k)
- # Stop if centroids do not change
- if np.all(centroids == new_centroids):
- break
- centroids = new_centroids
- return centroids, labels
- # Run K-means
- centroids, labels = k_means(X, k)
- # Visualize results
- plt.figure(figsize=(8, 6))
- plt.scatter(X[:, 0], X[:, 1], c=labels, s=30, cmap='viridis')
- plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, alpha=0.6, marker='X')
- plt.title("K-Means Clustering")
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment