Clustering in Machine Learning: K-Means, DBSCAN and How to Run Clustering Online
Clustering in machine learning groups similar data points together without any labels, so you can discover segments, patterns or unusual records you did not know to look for. K-means is the most widely used method and works well for compact, similarly sized groups, while DBSCAN, hierarchical clustering and Gaussian mixture models handle irregular shapes, unknown cluster counts and overlapping groups. You choose the number of clusters with tools such as the silhouette score and then judge whether the groups make business sense. TensorTurn can run k-means clustering online: upload a dataset, describe the segmentation you want, and it generates and runs the notebook.
What is clustering?
Clustering is unsupervised learning. There is no target column and no right answer to check against. The algorithm measures how similar rows are, usually by distance in feature space, and assigns rows that are close to each other to the same group. The result is a cluster label for every row, which you then interpret: these customers buy often but in small amounts, these sensors behave unlike all the others.
Typical uses include customer segmentation, grouping products or documents by similarity, compressing large datasets into representative prototypes, finding structure before building a supervised model, and spotting outliers that belong to no group. Because there is no ground truth, clustering is as much an exploration tool as a modeling one.
Clustering algorithms compared: k-means, DBSCAN, hierarchical and GMM
| Algorithm | How it groups data | Need to set k? | Best for | Limitations |
|---|---|---|---|---|
| K-means | Assigns each point to the nearest of k centroids, then moves centroids to the mean of their points | Yes | Large datasets with roughly round, similarly sized clusters | Sensitive to scaling and outliers; assumes convex clusters; results depend on initialization |
| DBSCAN (and HDBSCAN) | Grows clusters from dense regions; sparse points are labeled noise | No, but needs a density radius (eps) and minimum points | Irregular shapes, data with noise, finding outliers | Struggles when clusters have very different densities (HDBSCAN helps); eps is hard to choose in high dimensions |
| Hierarchical (agglomerative) | Starts with every point alone and repeatedly merges the closest pair, producing a tree (dendrogram) | No, you cut the tree at the level you want | Small to medium data, when you want to see nested structure | Memory and time grow quickly with row count |
| Gaussian mixture model (GMM) | Models data as a mix of overlapping Gaussian distributions | Yes, choose with BIC or AIC | Elliptical or overlapping clusters, soft membership probabilities | Can be unstable with many dimensions; assumes Gaussian-shaped groups |
If you are unsure, start with k-means for its speed and simplicity, check the result with a silhouette plot, and try DBSCAN or a GMM if the clusters look forced or a lot of points seem to sit between groups.
Preparing data for clustering
- Scale numeric features. Distance-based methods treat a column measured in thousands as far more important than one measured in fractions unless you standardize.
- Encode categories carefully. One-hot encoding works for a few categories; with many, consider k-prototypes or a different representation.
- Drop redundant features. Two highly correlated columns effectively double-count one idea and pull clusters toward it.
- Handle outliers first for k-means, since a single extreme row can drag a centroid away from where the real group is.
- Reduce dimensions with PCA when you have many features, because distances become less meaningful as dimensions grow.
How to choose k in k-means
K-means needs you to say how many clusters to find. No method gives a guaranteed answer, so use several signals and then apply judgment.
- Elbow method: plot the within-cluster sum of squares (inertia) against k and look for the point where adding clusters stops reducing it much.
- Silhouette score: for each point, compares how close it is to its own cluster versus the nearest other cluster. It ranges from -1 to 1; higher is better, values near 0 mean overlapping clusters, and negative values suggest points are in the wrong cluster.
- Davies-Bouldin and Calinski-Harabasz indexes: alternative internal scores that reward compact, well-separated clusters.
- Stability: rerun with different random seeds or on subsamples; real clusters reappear, artifacts do not.
- Usefulness: three clear, actionable segments often beat eight statistically optimal but indistinguishable ones.
How to interpret and validate clusters
Once you have labels, profile each cluster: its size and the average or most common value of each feature. Give each cluster a name a colleague would understand. If two clusters have nearly identical profiles, merge them; if one cluster holds 90 percent of the data, the features probably are not separating anything meaningful. A good next check is whether the clusters differ on an outcome you did not use for clustering, such as revenue or churn.
Common clustering mistakes
- Forgetting to scale features, so one large-valued column decides every cluster.
- Treating the silhouette score as the final word instead of one input to a judgment call.
- Feeding ID columns, timestamps or free-text codes into the distance calculation.
- Assuming clusters are permanent; customer behavior shifts, so segments need to be refreshed.
How to run k-means clustering online with TensorTurn
- Upload your data in CSV, Excel, Parquet or JSON format, or import from a URL, Hugging Face or Kaggle.
- Use the column profile and the association matrix (Pearson, Cramer's V and correlation ratio over every pair of columns) to spot redundant features, and the outlier analysis to find rows that could distort centroids.
- Clean up with the AI data editor: drop ID columns, fill or drop missing values, normalize text categories.
- Describe the task in chat, for example: segment customers with k-means, scale the numeric columns, try k from 2 to 10 and show the elbow and silhouette scores. Clustering is one of the tasks the planner recognizes, and it generates and runs the scikit-learn notebook.
- Ask follow-up questions in plain English, such as profiling each cluster or comparing k-means with DBSCAN, then deploy the fitted model as a /predict endpoint to assign new rows to segments.
For a worked example, see the customer segmentation use case.
Frequently asked questions
What is the difference between clustering and classification?
Classification is supervised: you train on rows that already have labels and predict those labels for new rows. Clustering is unsupervised: there are no labels, and the algorithm discovers groups based on similarity alone.
How do I choose the number of clusters?
Combine the elbow method, the silhouette score and a stability check across random seeds, then pick the smallest k that gives distinct, useful groups. The statistically best k is not always the most actionable one.
What is a good silhouette score?
Silhouette ranges from -1 to 1. As a rough guide, above 0.5 indicates well-separated clusters, 0.25 to 0.5 indicates weak but possibly useful structure, and below 0.25 suggests the data has little natural cluster structure.
When should I use DBSCAN instead of k-means?
Use DBSCAN when clusters have irregular shapes, when you do not know how many clusters to expect, or when you want noise points labeled separately. Stick with k-means for large datasets with roughly round, similarly sized groups.
Do I need to scale data before k-means?
Yes. K-means uses distances, so features with larger numeric ranges dominate unless you standardize them. Scaling is one of the most common fixes for clusters that look wrong.