Editor

Run Your First K-Means

Advanced · Write the code · from K-Means Clustering: Find Patterns in Data Without Labels

From the lesson: K-Means Clustering: Find Patterns in Data Without Labels

A streaming service groups users into "action fans," "comedy lovers," and "documentary watchers" - without anyone filling out a survey. A retailer segments customers into "big spenders," "bargain hunters," and "window shoppers" based on purchase behavior. Nobody labeled these groups. The algorithm discovered them.

Read the lesson

Fit a KMeans model with n_clusters=3, random_state=42, and n_init=10 on the data. Print the number of points in each cluster (0, 1, 2) in the format "Cluster X: N points" on separate lines.

from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import numpy as np
X, _ = make_blobs(n_samples=150, centers=3,
cluster_std=1.0, random_state=42)
# Fit KMeans and print cluster sizes

More K-Means Clustering exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz