K-means clustering
K-means clustering is an algorithm that partitions data into a specified number of clusters by iteratively assigning observations to the nearest centroid and updating each centroid to the mean of its assigned observations.
Data Without Labels
K-means clustering is an iterative clustering algorithm that partitions observations into a specified number of groups by minimizing within-group squared distance to cluster centroids.
- How it is used
- Uses k-means to group vehicle features and develop actionable customer segments without a target variable.
- How deep it goes
- Works through centroid reassignment and a Python workflow; defers detailed outlier treatment.
- Examples
- Uses vehicle features for a Python fit and customer transactions for business segmentation; suggests an iris comparison exercise.
- What you can do after
- Apply it via scikit-learn KMeans to standardized features, examine an elbow plot, and inspect centroids and cluster labels.
Advanced Algorithms and Data Structures
K-means is an iterative clustering algorithm that partitions observations into a specified number of clusters by minimizing within-cluster squared distances to cluster centroids.
- How it is used
- Partitions unlabeled points into a specified number of clusters, including for customer segmentation and constrained SS+-tree splits.
- How deep it goes
- Develops initialization, assignment, recentering, stopping, failure modes, pseudocode, complexity, and a distributed implementation.
- Examples
- Uses a three-centroid point diagram, an unlucky initialization, a constrained tree split, and customer segmentation.
- What you can do after
- Build it from scratch using assignment and recentering loops, then evaluate when its shape and dimensionality constraints make it suitable.
Read how Advanced Algorithms and Data Structures explains K-means clustering →
Statistics Slam Dunk
K-means is a clustering algorithm that partitions observations into a prespecified number of groups by minimizing within-group squared distances to cluster centroids.
- How it is used
- Segments observations into data-defined groups when analysis has input variables but no target variable.
- How deep it goes
- Explains iterative centroid assignment, convergence, K selection, R output, visualization, and distribution caveats without formal proofs.
- Examples
- Uses customer segmentation and NBA team payrolls with regular-season wins, visualized across candidate K values and a four-cluster solution.
- What you can do after
- Apply it via R’s kmeans function and factoextra visualizations to select K, segment observations, and inspect cluster results.
Classic Computer Science Problems in Swift: Essential techniques for practicing programmers
K-means clustering is an iterative unsupervised learning algorithm that partitions data points into a predefined number of clusters by repeatedly assigning points to their nearest centroid and recomputing the centroids.
- How it is used
- Uses clustering to reveal structure in data when little is known about its groupings.
- How deep it goes
- Works through normalization, random initialization, assignment, centroid updates, and stopping, then notes extensions without detailing them.
- Examples
- Demonstrates three-dimensional points and clusters state governors by longitude and age.
- What you can do after
- Build it from scratch in Swift by defining multidimensional points and iterating nearest-centroid assignments and mean updates.
Build AI Drug Discovery Pipelines
K-means clustering partitions data into a specified number of groups by iteratively assigning points to nearby centroids and recomputing the centroids.
- How it is used
- Uses clustering to select diverse compounds from ultra-large molecular libraries under processing and memory constraints.
- How deep it goes
- Explains centroid-distance computation and asymptotic cost, but does not provide a worked fitting or sampling implementation.
- Examples
- Uses an ultra-large compound library represented in a 1K-plus-dimensional space as its motivating dataset.
- What you can do after
- Evaluate clustering methods by comparing their time and memory scaling for large compound datasets.
Read how Build AI Drug Discovery Pipelines explains K-means clustering →
The Well-Grounded Data Analyst
K-means is a clustering algorithm that partitions observations into a specified number of groups by minimizing distances from observations to their assigned cluster centers.
- How it is used
- Applies clustering to segment mobile users into actionable behavioral groups.
- How deep it goes
- Explains scaling, cluster-count selection, assignments, inertia, and center interpretation without mathematical derivation.
- Examples
- Uses mobile-user records, inertia plots, cluster counts, transformed features, cluster centers, and behavioral personas.
- What you can do after
- Apply it via scikit-learn to assign observations to clusters and interpret their behavioral profiles.
Read how The Well-Grounded Data Analyst explains K-means clustering →
Human-in-the-Loop Machine Learning: Active learning and annotation for human-centered AI
K-means clustering partitions data into a specified number of clusters by iteratively assigning points to their nearest cluster centroid and updating the centroids.
- How it is used
- Uses clusters to select diverse items for human annotation rather than as downstream model inputs.
- How deep it goes
- Explains cluster-count selection, random initialization, reassignment, stopping conditions, and sampling, with a concrete implementation.
- Examples
- Illustrates sampling with sports and rarer headlines, plus a 100-item annotation budget with five items per cluster.
- What you can do after
- Apply it via a PyTorch implementation to create cosine-based clusters for annotation sampling.
Build AI-Enhanced Web Apps
K-means clustering is an unsupervised clustering algorithm that assigns data points to a chosen number of groups according to their distances from cluster centers.
- How it is used
- Improves long-document summarization by grouping semantically similar chunks before merging and summarizing them.
- How deep it goes
- Explains the full chunking, embedding, clustering, distance comparison, and merging pipeline, with a JavaScript implementation.
- Examples
- Uses document chunks, Hugging Face feature embeddings, ml-kmeans, similarity thresholds, and semantically coherent merged sections.
- What you can do after
- Build it from scratch as a JavaScript preprocessing stage for document summarization.
Read how Build AI-Enhanced Web Apps explains K-means clustering →
AI-Powered Search
K-means is an unsupervised clustering algorithm that partitions items into a specified number of groups by iteratively assigning items to and updating cluster centroids.
- How it is used
- Supports personalized search by converting product and query embeddings into dynamic categories for personalization guardrails.
- How deep it goes
- Provides Python fitting, labeling, visualization, and prediction, then recommends related top-N cosine clusters over a single assignment.
- Examples
- Uses product embeddings, cluster descriptions, visualized centroids, and the “microwave” query with five related predicted categories.
- What you can do after
- Apply it via Python and scikit-learn to generate categories and map queries to clusters for search personalization.
Grokking Machine Learning, Second Edition
K-means clustering is an iterative algorithm that assigns data points to clusters around movable centers of mass.
- How it is used
- Groups unlabeled data points into similar clusters for marketing, genetics, medical imaging, and video recommendations.
- How deep it goes
- Defines iterative movement of random centers toward points, but defers detailed treatment of unsupervised-learning algorithms.
- Examples
- Uses an email dataset plotted by message size and recipient count, producing three visible categories.
- What you can do after
- Understand K-means as an iterative method for grouping points around movable centers.
Read how Grokking Machine Learning, Second Edition explains K-means clustering →
Retrieval Augmented Generation, The Foundational Ideas
K-means is a clustering algorithm that partitions data points into a fixed number of clusters by assigning each point to one cluster.
- How it is used
- Accelerates approximate nearest-neighbor search by organizing similar vectors into searchable clusters.
- How deep it goes
- Explains initialization, assignment, averaging, convergence, and query routing, but defers implementation details and compression.
- Examples
- Uses FAISS to illustrate centroid routing and restricted vector search for million-vector collections.
- What you can do after
- Apply it via FAISS to build clustered approximate nearest-neighbor indexes and reduce query-time comparisons.
Read how Retrieval Augmented Generation, The Foundational Ideas explains K-means clustering →
Timeless Algorithms, The Foundational Ideas
K-means clustering partitions observations into a specified number of groups by assigning them to the nearest centroid and iteratively updating the centroids.
- How it is used
- Finds groupings in unlabeled data when no known outcome is provided for prediction.
- How deep it goes
- Explains nearest-centroid assignment, iterative centroid updates, and the geometric goal of within-cluster similarity and between-cluster distinction.
- Examples
- Illustrates clustering with customer purchasing behavior, patient characteristics, and social-network communities.
- What you can do after
- Understand how nearest-centroid assignments and iterative updates produce geometric clusters from unlabeled data.
Read how Timeless Algorithms, The Foundational Ideas explains K-means clustering →
Also covered in
- Privacy-Preserving Machine Learning
- Investing for Programmers
- Outlier Detection in Python
- AI Agents in Action
- Financial AI in Practice
- The Art of AI Product Development
- Time Series Forecasting Using Foundation Models
- Data-Driven Cybersecurity
- Data Analysis with LLMs
- Machine Learning Algorithms in Depth
What to know first
- clusteringClustering is the process of grouping data items so that items within a group are more similar to one another than to items in other groups.
- supervised learningSupervised learning is a machine-learning approach that learns predictive relationships from examples paired with known target outputs or labels.
- centroidA point representing the center of a set of points or a region, commonly calculated as the coordinate-wise mean or, for weighted points, the weighted mean.
- distanceA distance function assigns a numerical measure of separation or dissimilarity to pairs of points or objects in a defined space.
Related concepts
- centroiduses · A point representing the center of a set of points or a region, commonly calculated as the coordinate-wise mean or, for weighted points, the weighted mean.
- Euclidean distanceuses · Euclidean distance is the straight-line distance between two points, calculated as the square root of the sum of squared differences between corresponding coordinates.
- clusteringproduces · Clustering is the process of grouping data items so that items within a group are more similar to one another than to items in other groups.
- hard clusteringkind of · Hard clustering assigns each observation to at most one cluster, with all clusters represented at the same hierarchy level.
- hierarchical clusteringcontrasts with · Hierarchical clustering is a clustering method that organizes observations into nested groups by successively merging or splitting clusters.
- unsupervised learningkind of · Unsupervised learning is a machine-learning approach that discovers patterns, structure, or representations in data without labeled target outputs.
Questions about K-means clustering
What is K-means clustering?
K-means clustering is an algorithm that partitions data into a specified number of clusters by iteratively assigning observations to the nearest centroid and updating each centroid to the mean of its assigned observations.
Which Manning books explain K-means clustering?
Data Without Labels, Advanced Algorithms and Data Structures, Statistics Slam Dunk, Classic Computer Science Problems in Swift: Essential techniques for practicing programmers, Build AI Drug Discovery Pipelines, The Well-Grounded Data Analyst, Human-in-the-Loop Machine Learning: Active learning and annotation for human-centered AI, Build AI-Enhanced Web Apps and 4 more.
What should I know before learning K-means clustering?
Manning books that teach K-means clustering usually introduce clustering, supervised learning, centroid and distance first.
What is the difference between K-means clustering and hierarchical clustering?
K-means clustering is an algorithm that partitions data into a specified number of clusters by iteratively assigning observations to the nearest centroid and updating each centroid to the mean of its assigned observations. Hierarchical clustering is a clustering method that organizes observations into nested groups by successively merging or splitting clusters.
What is K-means clustering a kind of?
K-means clustering is a kind of hard clustering. Hard clustering assigns each observation to at most one cluster, with all clusters represented at the same hierarchy level.
What is K-means clustering also called?
K-means clustering is also called k-means algorithm.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.











