If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here's an example of how you can implement the K-Means clustering algorithm using Python and the scikit-learn
library:
pythonCopy code
import numpy as np from sklearn.datasets import make_blobs from sklearn.cluster import KMeans import matplotlib.pyplot as plt # Generate synthetic data data, _ = make_blobs(n_samples=300, centers=4, random_state=42) # Create K-Means model k = 4 # Number of clusters model = KMeans(n_clusters=k, random_state=42) # Fit the model to the data model.fit(data) # Get cluster assignments and centroids cluster_assignments = model.labels_ centroids = model.cluster_centers_ # Plot the data and centroids plt.scatter(data[:, 0], data[:, 1], c=cluster_assignments, cmap='rainbow') plt.scatter(centroids[:, 0], centroids[:, 1], marker='X', s=200, c='black') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('K-Means Clustering') plt.show()
This code snippet demonstrates the following steps:
make_blobs
.You can replace the dataset generation step with your own data if you have a different dataset to cluster. Additionally, you can adjust the number of clusters (k
) and other hyperparameters of the K-Means algorithm to suit your specific needs.
Remember that K-Means is a versatile algorithm, but its performance can be sensitive to the initial placement of centroids. Running K-Means multiple times with different initializations can help mitigate this issue.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform