Free browser-based ML tool

K-Means CSV Clustering & Elbow Calculator

Cluster numeric CSV data in your browser. Compare inertia and silhouette scores, inspect cluster profiles, and export labeled data and JS or Python code.

Free to useNo upload or sign-inRuns entirely in your browser
Live calculation
Powered by @kanaries/ml

Input features

Numeric CSV or TSV
Use one row per sample. Every column contributes to the distance.
monthly_spendweekly_active_dayssupport_ticketsseats

Cluster settings

Selected k
3
Recommended k
3
Inertia / WCSS
2.126
Silhouette Score
0.771
Davies–Bouldin Index
0.299
Samples (n)
18
Features (p)
4
Scaling Mode
Standardized

Cluster Scatter Plot

-2.1853.236-0.5310.732PC1PC2Row 1, cluster 0Row 2, cluster 0Row 3, cluster 0Row 4, cluster 0Row 5, cluster 0Row 6, cluster 0Row 7, cluster 2Row 8, cluster 2Row 9, cluster 2Row 10, cluster 2Row 11, cluster 2Row 12, cluster 2Row 13, cluster 1Row 14, cluster 1Row 15, cluster 1Row 16, cluster 1Row 17, cluster 1Row 18, cluster 1Cluster 0 centroidCluster 1 centroidCluster 2 centroid

Elbow & Silhouette Plot

WCSS720Cluster count (k)—10.7620.7730.6940.6550.5960.5370.478

The line shows inertia. Numbers above the points show silhouette. Orange marks the selected k.

Cluster profiles

Feature means use original units. Colors match the scatter plot.

Cluster IDSizeShare %monthly_spendweekly_active_dayssupport_ticketsseats
● 0633.3%55.3331.5000.5002.667
● 1633.3%2273.3336.50010.167112.333
● 2633.3%428.3334.3333.16721.167
import { Clusters, Metrics } from '@kanaries/ml';

const X = [[39,1,0,2],[59,2,1,3],[49,1,1,2],[75,2,0,4],[65,2,1,3],[45,1,0,2],[370,4,3,18],[420,4,4,20],[460,5,3,23],[395,4,2,19],[485,5,4,25],[440,4,3,22],[2100,6,9,105],[2350,7,11,118],[1980,6,10,96],[2540,7,12,125],[2250,6,9,110],[2420,7,10,120]];
const means = [919,4.111111111111111,4.611111111111111,45.388888888888886];
const stds = [976.11275532651,2.1052550357218243,4.151825420340751,48.29094565339103];
const XFit = X.map(row => row.map((v, j) => (v - means[j]) / stds[j]));
const model = new Clusters.KMeans({
  n_clusters: 3, random_state: 42, n_init: 10, max_iter: 300, tol: 1e-4,
});
const labels = model.fitPredict(XFit);
console.log({ labels, centers: model.getCentroids(), inertia: model.getInertia() });
if (new Set(labels).size === 3) {
  console.log(Metrics.silhouetteScore(XFit, labels), Metrics.daviesBouldinScore(XFit, labels));
}

What makes two rows similar?

Open the retail locations preset and imagine choosing stores for a merchandising trial. A busy store with small baskets might benefit from faster checkout. A quieter store with large baskets might benefit from personal consultations. Grouping by revenue alone could put both stores in the same segment. Tracking foot traffic and basket value separately gives each location a position on a map. K-Means looks for sets of nearby positions and represents each set with one typical position, its centroid. The same idea works when a position takes four columns to describe and you can no longer draw the map directly.

Start with one observation per row and choose a common measurement window. For accounts, a week of activity and a month of spending can work together if every row uses those same definitions. Mixing annual and monthly invoices in one spend column creates a divide that can look like a customer segment. Exclude numeric identifiers before fitting. Two customers who registered a minute apart can have consecutive account numbers and entirely different purchasing habits. Record the input order so you can restore those identifiers after exporting the assignments.

Read inertia as the cost of representing rows by their centers

Pick a row and subtract its assigned centroid from it, column by column. Square each difference and sum the squares. That row contributes the result to the within-cluster sum of squares, also called WCSS or inertia. Adding the contributions from all rows gives the objective K-Means tries to minimize. For a fixed assignment, the column means minimize this cost. For fixed centers, assigning each row to its nearest center minimizes its contribution. Lloyd’s algorithm alternates these two operations until its stopping rule takes effect.

With one center, every account takes the portfolio average as its representative. Adding a second center can remove a large error if enterprise accounts spend much more than the others. Later centers may distinguish only small variations among accounts on the same plan. The best attainable inertia falls or stays level as centers are added. Individual fits can settle at local optima, so the calculator tries ten initializations for each count and keeps the fit with the lowest inertia. Compare costs on the same rows with the same scaling. Doubling the dataset by duplicating every observation doubles the sum even if every center stays put.

Choose a cluster count with three different questions

The elbow curve answers how much error another center removes. Read from left to right and look for a steep descent followed by smaller gains. In the retail example, compare the step from three to four centers with the step from four to five. Inspect the profiles at both settings. A new center that separates busy stores from quiet ones at a similar basket value may justify a different staffing plan. A fifth center that divides nearly identical stores may add operational overhead for very little reduction in error.

Silhouette measures the experience of individual samples. For each sample, compare its average distance to other members of its cluster with its lowest average distance to members of any other cluster. Subtract the within-group distance from the neighboring-group distance and divide by the larger of the two. The resulting score ranges from minus one to one. A value near zero places a row near a boundary under this measure. The chart annotates each fit with the mean score. A large, well-separated group can dominate that mean, so also inspect the sizes and characteristics of smaller groups before adopting the recommendation.

The Davies–Bouldin index gives each occupied cluster a turn. For a pair of groups, it compares their combined internal scatter with the distance between their centers. Each group contributes its worst such ratio to the final average. Lower values indicate compact groups with relatively distant centers. If the silhouette score looks favorable while Davies–Bouldin worsens after a split, inspect the two resulting profiles. A small pair of close groups can have little influence on a sample-weighted average while each still contributes a whole term to the cluster-weighted index.

Choose the units before interpreting the distances

In the SaaS preset, a difference of one hundred dollars contributes ten thousand squared dollars to raw inertia. A difference of three active days contributes nine squared days. Even changing dollars to cents would dramatically alter the relative influence of those two features. Standardization subtracts each column mean and divides by its population standard deviation. Now a move of one standard deviation makes the same contribution on either axis. A constant column becomes zero for every row and contributes nothing to the fitted distances.

Scaling deserves a domain decision. If two columns already measure distances in meters along perpendicular axes, the original geometry can have a physical interpretation worth retaining. Conversely, standardizing every column does little to fix duplication. Monthly spend and monthly spend including a fixed sales tax encode the same behavior twice. Including both doubles that behavior’s influence even after scaling. Try removing one and check which accounts change groups. The profile table always reports original units, which lets you describe a change in terms such as seats per account or weekly active days.

Interpret the scatter alongside the full feature profiles

For two columns, each point sits at the original pair of measurements. A cross marks its group’s center. With one column, the horizontal axis carries the measurement and all points share a baseline. Three or more columns require a projection. The calculator fits principal component analysis to the matrix used for clustering and projects both samples and fitted centers through those same two component directions. The first direction captures the greatest variance and the second captures the greatest remaining variance along a perpendicular direction.

Two accounts can appear almost on top of each other while differing substantially along a discarded direction. Their colors can therefore differ even when they appear closer to the same cross on screen. Check the original column means to find the measurements behind that separation. Conversely, a visibly isolated point may have pulled a centroid toward itself because squaring a large residual amplifies its cost. Review the source row for unit errors and decide whether it represents a repeatable group or one exceptional observation. Both the assignments and separation scores use all fitted features.

Recognize when a different cluster model fits the problem

Nearest-center assignment splits space with straight boundaries. A ring around a compact core has a meaningful separation in density, yet several centers placed around the ring can slice it into wedges. DBSCAN can follow chains of dense neighbors and mark isolated observations as noise when a useful neighborhood radius exists. HDBSCAN explores density structure across neighborhood scales and can help when a single radius merges one pair of groups while breaking another into fragments. Inspect the noise assignments when using either approach, especially if unusual observations are central to your question.

For overlapping elliptical populations, a Gaussian mixture model can estimate covariance within each group and return membership probabilities. Those probabilities can support review of ambiguous cases. For large collections of dense vectors where a fixed number of nearest centers still meets the objective, E-Means offers moving-average center updates during a pass. Compare reconstruction error on held-out vectors and measure runtime on your own workload. Changing the update algorithm addresses computational cost while keeping the decision about a meaningful distance measure in your hands.

Reproduce the result in JavaScript or Python

The code tabs carry the current rows, selected count, random seed, restart count, iteration limit, and tolerance into a standalone fit. The JavaScript example uses the browser’s scaling parameters with @kanaries/ml. The Python example computes population scaling with scikit-learn when the toggle is enabled. Compare the resulting inertia first, then match centers by their coordinates. Label zero simply identifies a position in a particular fit’s center array. Another run can call the same segment cluster two and still give identical assignments after relabeling.

Different implementations can draw different initial centers from the same integer seed and apply different convergence tests. If the solutions differ, check the input order, feature order, and scaling before comparing individual labels. For a repeatable report, keep the clustered CSV together with the selected code and record the package version you ran. A scatter image preserves the view that informed your decision, while the CSV preserves each row’s membership for downstream analysis.

Frequently asked questions

Questions about k-means csv clustering & elbow calculator

Which columns should I paste?

Include the numeric measurements you want to compare. Remove account IDs, row numbers, class labels, and text. A header row supplies feature names. Use at least three complete data rows.

How does Use Recommended k choose a fit?

It selects the highest available silhouette score among the tested counts starting at two. If all scores are unavailable, it uses the inertia point farthest from the line joining the ends of the elbow curve. Ties favor the smaller eligible count.

What does a dash in the silhouette plot mean?

A single cluster has no neighboring cluster for comparison. The calculator also skips separation scores when fewer groups receive samples than the requested count. Repeated identical records can produce this outcome.

Are the means in the profile table standardized?

Each mean averages the original CSV values of the rows assigned to that cluster. You can read spend in currency units and usage in days even when the fit uses standardized features.

How do I reproduce a result for a colleague?

Copy the JavaScript tab to capture the rows, fitted scaling parameters, seed, and model options. For small tables the address also stores the input and settings in its fragment. Anyone receiving that address can read the included data.

Can I join cluster assignments back to my records?

Download Clustered CSV to keep the input order and append a zero-based cluster column. Preserve an ordered copy of your source records so you can attach their identifiers after fitting.

Powered by @kanaries/ml — the scikit-learn-style ML library for JavaScriptnpmGitHub