Skip main navigation

Hurry, only 9 days left to get one year of Unlimited learning for £249.99 £174.99. New subscribers only. T&Cs apply

Find out more

A k-means example in Python

A k-means example in Python

Run and modify the following code and share your experiences. You can try different k and see their difference.

from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt

# Sample data for clustering
# Set the seed for reproducibility
np.random.seed(0)

# Generate 100 random points as a 2D NumPy array
data = np.random.uniform(0, 20, size=(100, 2))

# Number of clusters (k)
k = 2

# Creating a KMeans instance with k clusters
kmeans = KMeans(n_clusters=k)

# Fitting the data to the KMeans algorithm
kmeans.fit(data)

# Getting the centroids and labels for the clusters
centroids = kmeans.cluster_centers_
labels = kmeans.labels_

# Visualizing the clustered data
colors = ["g.", "r.", "c.", "y."]

for i in range(len(data)):
plt.plot(data[i][0], data[i][1], colors[labels[i]], markersize=10)

plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=150, linewidths=5, zorder=10)
plt.show()
This article is from the free online

Recommender Systems in Python

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now