Black FridayUpgrade your career this Black Friday. Get up to ₹60,000 Scholarship on IIT programsUp to ₹60K Black Friday Scholarship63 seats leftOffer ends Fri, 27 Nov, 11:59 pm IST.

Black Friday Scholarship – IIT Jammu & IIT Roorkee

The best Black Friday deal isn't a gadget. It's your next career move.

Get up to ₹60,000 Black Friday Scholarship on our PG programs with IIT Jammu and iHUB DivyaSampark, IIT Roorkee. IIT certification, 12 live sessions with IIT faculty and 100% placement assistance.

Only 63 seats left. Offer ends Fri, 27 Nov, 11:59 pm IST

3,905 engineers placed since 2019 · 1,276 hiring companies

By submitting you agree to our Terms and Privacy Policy.

Your free demo class is requested

Browse courses

K-means clustering calculator: every step, the elbow and the silhouette

K-means splits points into k groups so that the sum of squared distances from each point to its group's centre (the inertia) is as small as it can find. It repeats two steps: assign every point to its nearest centre, then move each centre to the mean of its points, until nothing changes. Choose k with the elbow and the silhouette together, scale features with different units first, and use k-modes or Gower distance for categorical data.

Paste your points or load an example, then step through every assignment and centroid update with the distances and sums shown, compare starting methods, plot the elbow and silhouette for k = 1 to 10, work out categorical distances, and check the numbers in your report. Free, runs in your browser.

scikit-learn 1.9.1 docs and code · UCI Auto MPG and Car Evaluation (CC BY 4.0) · Satopaa et al. 2011 · Gower 1971 · Huang 1998 · checked against an independent solution (29,992 checks at build, 3,449 scikit-learn cross-checks) · Updated 24 Nov 2026

Dots: points, coloured by their cluster. Crosses: centres. Shading: the region each centre would win.

Stepstart
Inertia (WCSS)–
Labels changed–

    Distances are Euclidean; inertia adds up their squares. A tie goes to the lower-numbered centre. A centre left with no points stays where it was (scikit-learn moves it to a far point instead). k-means++ here is the greedy version scikit-learn describes, with 2 + ⌊ln k⌋ candidates per centre, drawn from the page's own seeded generator, so the same seed gives the same start here every time but not the same start as scikit-learn's random_state.

    How does k-means work, step by step?

    k-means looks for k centres μ1 … μk that make the inertia as small as it can. scikit-learn's guide: "The K-means algorithm aims to choose centroids that minimise the inertia, or within-cluster sum-of-squares criterion".

    Lloyd's algorithm gets there by repeating two steps. In scikit-learn's words, "The first step assigns each sample to its nearest centroid. The second step creates new centroids by taking the mean value of all of the samples assigned to each previous centroid."

    Worked example: the 12 points of the hand example in tab 1, k = 3, with the first three points (1, 1), (2, 1) and (1, 2) as starting centres. The point (6, 5) is nearest centre 2:

    After the first assignment, centre 2 owns 4 points (points 2, 5, 6, 8), so it moves to their mean:

    The inertia is 374 with the starting centres and 106.93 once they move; reassigning the points brings it to 44.68 (4 points change cluster), the next move to 14.75, and the third assignment changes nothing, so k-means stops at 14.75. That is the lowest inertia ten k-means++ starts find for these points. Each step can only lower the inertia or keep it, which is why the loop always stops; it can stop at a local minimum, though, as the next section shows.

    Why do I get different clusters each run? (k-means++ and n_init)

    Because the answer depends on the start. scikit-learn: "Given enough time, K-means will always converge, however this may be to a local minimum. This is highly dependent on the initialization of the centroids." Take the 20 points of the "four groups" example, four tight groups at the corners of a rectangle. One start from four random points (seed 1) puts two centres in one group: k-means then merges two other groups and stops at an inertia of 63.27. Greedy k-means++ from the same seed reaches 3.14. Over seeds 1 to 100, a single random start ends more than 50 % above the best inertia 53 times; a single k-means++ start 0 times.

    Two fixes, both in scikit-learn. k-means++ spreads the starting centres: each new one is drawn with probability proportional to its squared distance from the centres chosen so far, and scikit-learn's version is "greedy k-means++", which "differs from the vanilla k-means++ by making several trials at each sampling step and choosing the best centroid among them" (2 + log k trials, its kmeans_plusplus page says). And n_init runs k-means several times and keeps the lowest inertia: ten random starts from seed 1 find 3.14 here. Note the default: since scikit-learn 1.4, n_init = "auto" means 1 run with k-means++ and 10 with init = "random". Set random_state too, or every run of your notebook can print a different elbow.

    How do you choose k: elbow or silhouette?

    Inertia always falls as k grows (k = n gives zero), so the elbow method looks for where the fall flattens. To make "where it bends" a rule rather than a guess, we use Kneedle (Satopaa, Albrecht, Irwin and Raghavan, 2011). The paper's knee is the point "at which the curve differs most from the straight line segment connecting the first and last data point". It scales both axes to [0, 1], takes the difference curve yd = yn − xn, and accepts a peak of yd when the curve then drops below a threshold set by the sensitivity S (we use S = 1 and no smoothing). Inertia falls rather than rises, so we flip it first, which the paper allows for curves that are not knees already.

    The silhouette adds what the elbow cannot: how well separated the clusters are. For each point, a is its mean distance to the rest of its own cluster and b its mean distance to the nearest other cluster (scikit-learn: "The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters"). A point alone in its cluster scores 0, as in scikit-learn.

    On the 90-point three-blob example, the knee is at k = 3 and the mean silhouette is highest at k = 3 (0.659). Clean data like this is the easy case. Real elbows are often ambiguous: on Auto MPG below, the scaled curve's knee is at k = 3 while the silhouette is highest at k = 2. When they disagree, check the per-point silhouette (tab 2), and remember that inertia rewards splitting large clusters while the silhouette favours few, well separated ones. A k you can describe and act on often settles it.

    02004006008001e+312345678910knee k = 3inertiak (clusters)inertia (WCSS)
    00.20.40.60.812345678910highest at k = 3silhouettek (clusters)mean silhouette

    Should you scale data before k-means? Auto MPG with and without StandardScaler

    To show what scaling does on real numbers, we clustered UCI Auto MPG (Quinlan, 1993; doi:10.24432/C5859H; CC BY 4.0), a public car dataset with the same kind of columns the challenge reports cluster: horsepower, weight and mpg. Most reports (10 of 44 with text) used a course file, Cars_mileage.csv, with horsepower, weight, mpg, volume and top speed; it has no published licence, so we do not use it here. The UCI file has 398 cars; 6 have "?" for horsepower (ford pinto, ford maverick, renault lecar deluxe, ford mustang cobra, renault 18i, amc concord dl), so we drop them and keep 392. We cluster six columns: mpg, cylinders, displacement, horsepower, weight, acceleration. Model year and origin are left out of the distance: origin is a code (1, 2, 3 are the USA, Europe and Japan, as the names show: all 48 Fords are 1, all 15 Volkswagens 2, all 25 Toyotas 3), and putting it in a Euclidean distance would make Japan "further" from the USA than Europe. We use both afterwards to describe the clusters.

    The columns live on very different scales. Weight has a standard deviation of 848 (range 1,613 to 5,140; the file gives no units, pounds by the look of it) and acceleration 2.76. Unscaled, weight carries 98.3 % of the total variance, so the Euclidean distance is weight and little else.

    With scikit-learn 1.9.1, KMeans(n_init = 10, random_state = 0), on the raw columns and after StandardScaler:

    kInertia, unscaledSilhouette, unscaledSizes, unscaledInertia, scaledSilhouette, scaledSizes, scaledARI unscaled vs scaled
    27,29,16,1320.637236 / 156927.700.545288 / 1040.520
    33,38,44,1840.585180 / 122 / 90596.520.442202 / 93 / 970.647
    41,88,06,2120.579136 / 98 / 89 / 69482.110.38278 / 131 / 86 / 970.370
    51,34,84,2320.550131 / 95 / 65 / 53 / 48416.490.37075 / 48 / 93 / 79 / 970.350
    61,01,35,7320.527119 / 79 / 62 / 56 / 50 / 26360.210.33275 / 48 / 93 / 76 / 62 / 380.326
    776,60,1640.50658 / 81 / 66 / 55 / 56 / 50 / 26327.120.32370 / 29 / 73 / 45 / 75 / 63 / 370.295
    856,10,5340.52157 / 79 / 55 / 47 / 50 / 40 / 48 / 16296.550.29734 / 65 / 77 / 32 / 45 / 41 / 61 / 370.271

    Do not compare the two inertia columns: they are in different units (squared weight units against squared standard deviations). The silhouettes can be compared, and the unscaled ones look better (0.585 against 0.442 at k = 3). That is the trap: the unscaled clusters are cleanly separated along one axis because they are weight bands. At k = 3 they are 1,613 to 2,694, 2,700 to 3,672, 3,693 to 5,140, with no overlap at all, cut wherever the weight gaps fall. The adjusted Rand index between the unscaled and scaled k = 3 labels is 0.647 (1 means the same partition, about 0 means no more agreement than chance).

    05e+71e+82e+82e+83e+83e+812345678910knee k = 3inertiak (clusters)inertia (WCSS)
    05001e+32e+32e+312345678910knee k = 3inertiak (clusters)inertia (WCSS)

    The scaled curve's knee is at k = 3 and the unscaled one's at k = 3; the silhouette is highest at k = 2 scaled and k = 2 unscaled. The page's own code (greedy k-means++ from its seeded generator, 10 starts) run on the same scaled data reaches scikit-learn's inertia at k = 1, 2, 3, 4, a higher one at k = 5, 6 and a lower one at k = 7, 8, 9, 10. Neither is promised the global minimum: with 10 starts each, which code finds the lower inertia for a large k depends on where the starts fall.

    00.20.40.60.82345678unscaledscaledk (clusters)mean silhouette

    Car dataset k-means: the business insight from k = 3

    Scaled, k = 3 splits the 392 cars into three groups you can name. Centroids are in the original units (StandardScaler's inverse transform); the typical car is the one nearest each centroid.

    ClusterCarsmpgCylinders (most common)DisplacementHorsepowerWeightAccelerationOrigin: USA / Europe / JapanMean model yearTypical car
    Economy20229.44.0 (4-cyl: 195 of 202)110782,30316.535 % / 29 % / 36 %1977audi fox
    Mid-size9319.86.0 (6-cyl: 80 of 93)2181023,22616.484 % / 10 % / 6 %1976plymouth valiant custom
    Heavy9714.58.0 (8-cyl: 96 of 97)3481624,14412.6100 % / 0 % / 0 %1974chevrolet impala

    What a reader can lift from this. The economy cluster (202 cars, 195 of them 4-cylinder) averages 29.4 mpg and is the only one with a real share of imports: 29 % European and 36 % Japanese. The heavy cluster (97 cars, 96 with 8 cylinders) averages 14.5 mpg at 4,144 weight, is 100 % American and is the oldest on average (1974 against 1977 for economy), which fits the fuel crises of the 1970s pushing buyers toward small cars. The mid-size cluster is the 6-cylinder American middle. A maker reading this would see that its imports compete in one segment only. Weight ranges overlap here (1,613 to 3,250, 2,472 to 4,060, 3,086 to 5,140): the clusters now use every column, not weight alone.

    Silhouette of each car for scaled k = 3 (mean 0.442): most bars are positive, and the low and negative ones are cars between segments.

    00.51123mean 0.442

    Can k-means use categorical data? Hamming, Jaccard, cosine and Gower

    Not directly. Huang (1998) put it plainly: "the k-means algorithm only works on numeric data", because "it minimises a cost function by changing the means of clusters". The usual alternatives start from simple matching, which Huang defines as "the total mismatches of the corresponding attribute categories of the two objects". Take two cars from the UCI Car Evaluation attributes (buying, maint, doors, persons, lug_boot, safety; values as listed on the UCI page) that differ only in safety:

    One-hot encoding turns the 6 attributes into 21 0/1 columns. One differing attribute flips two of them (low off, med on), so the Hamming distance on the one-hot vector is 2 where simple matching on the raw attributes counts 1. When every record has exactly one 1 per attribute, Jaccard and cosine are fixed by the mismatch count m: J = (p − m)/(p + m) and cos = (p − m)/p, so cosine distance on one-hot data equals simple matching. For 0/1 vectors in general, cosine is the dot product over the norms: [1, 1, 1, 0, 0, 0] against [1, 1, 0, 0, 0, 1] gives 2/(√3 × √3) = 0.6667.

    Label encoding is the slip to avoid. scikit-learn's LabelEncoder numbers categories in sorted order, so buying becomes high = 0, low = 1, med = 2, vhigh = 3: "low" sits between "high" and "med", and the distance from low to vhigh is 2 while high to low is 1. Even codes in the natural order (vhigh = 0, high = 1, med = 2, low = 3) impose equal steps (low to vhigh = 3), which may be fine for a truly ordinal field if you mean it, and is meaningless for a nominal one such as colour or brand. Means of codes (a centre at buying = 1.4) mean nothing either.

    For mixed records, Gower (1971) averages a score per field: "For qualitative characters we set sijk = 1 if the two individuals i and j agree in the kth character and sijk = 0 if they differ"; for quantitative ones, 1 − |xi − xj|/Rk with Rk the range. For a toyota corolla and a ford pinto (mpg, horsepower and weight numeric with the ranges of the 392 cars; origin and cylinders as categories):

    Gower gives distances, not means, so pair it with a method that needs only distances: k-medoids (PAM) or hierarchical clustering. For all-categorical data, k-modes (Huang 1998) keeps the k-means loop but uses simple matching and replaces means with modes (the most frequent category of each attribute). On 8 Car Evaluation records with records 1 and 2 as starting modes, our batch k-modes (Huang updates a mode after each record; this version updates after a full pass) settles in 2 passes at a total mismatch cost of 12:

    ClusterRecordsMode (buying, maint, doors, persons, lug_boot, safety)
    11, 3, 4, 7vhigh, vhigh, 2, 2, small, low
    22, 5, 6, 8low, low, 4, more, big, high

    k-prototypes, in the same paper, handles mixed data by adding the squared Euclidean distance on the numeric fields to γ times the matching distance on the categorical ones.

    What the 47 public k-means challenge reports do (as of 24 Nov 2026)

    We read the 47 public Skill-Lync reports titled "Unsupervised Learning - Kmeans Week 11 Challenge", as of 24 Nov 2026, n = 47. 3 are image-only, which leaves 44 with text; many show code and plots only as screenshots, so every count is a floor. The challenge asks how similarity is calculated for categorical data, and for k-means on a car dataset with business insights. The links are examples.

    • 38 / 44Gave some way to compare categorical records in Q1. A named measure, the 1/0 match rule, or "turn the categories into numbers first". The other reports answer a different question or only Q2. report 1report 2
    • 25 / 44Named at least one similarity measure for categorical data. Hamming, Jaccard, cosine, matching, Gower, Dice, k-modes, overlap, chi-square or entropy based. report 1report 2
    • 20 / 44Named Hamming distance. report 1report 2
    • 19 / 44Named Jaccard similarity. report 1report 2
    • 10 / 44Named cosine similarity. report 1report 2
    • 9 / 44Mentioned one-hot or dummy encoding. report 1report 2
    • 10 / 44Used the Cars_mileage dataset (MPG, HP, SP, VOL, WT). report 1report 2
    • 18 / 44Did not show which dataset in the text. report 1report 2
    • 18 / 44Ran an elbow plot (inertia/WCSS/SSE against k) on the car data. Shown as code that collects inertia_ or as a sentence that the elbow was used. The plots are images. report 1report 2
    • 26 / 44Stated the k used for the final model. report 1report 2
    • 16 / 44Used k = 3. report 1report 2
    • 12 / 44Showed KMeans(...) code in the text. Floor: many reports attach a notebook or show code as images. report 1report 2
    • 8 / 44Showed or stated a scaling step before k-means. Seven show it in code; one states that features were normalised. report 1report 2
    • 13 / 44Wrote an insights section in words. None gives a number for a cluster profile; 2 only describe what a cluster might be. report 1report 2

    What stands out for this calculator. k = 3 is the usual choice (16 of the 26 that state k), and 18 run an elbow plot, but only 1 prints a silhouette value. 8 of 44 show or state a scaling step (5 min-max, 2 StandardScaler), and none of the 10 Cars_mileage reports scales its columns before clustering horsepower against weight, the situation the Auto MPG section shows. 12 show KMeans code in text. 13 write an insights section in words, and none gives a number for a cluster profile: the k = 3 table above is the kind of profile that makes the insight checkable. For Q1, the measures named most are Hamming (20), Jaccard (19) and cosine (10); Gower appears in 4 and k-modes in 2. These are first-party counts, a starting point rather than a measure of anyone's ability.

    One report prints its whole elbow list (Auto MPG, six min-max scaled columns with mpg included, k = 1 to 9): 142.70, 47.05, 25.14, 20.32, 17.40, 15.60, 14.29, 13.11, 12.28. Kneedle on that list gives k = 3, and the point farthest from the chord is k = 3. Paste a list like it into tab 4 to get the same reading for yours.

    Common k-means slips and how to fix them

    • Clustering unscaled columns. The widest column decides the clusters (weight carries 98.3 % of the Auto MPG variance). Fix: StandardScaler (or MinMaxScaler) on the columns you cluster, then interpret centroids after inverse_transform.
    • Silhouette or elbow on different data from the clustering. A silhouette computed on raw columns for clusters found on scaled ones measures something else. Tab 4 tests your silhouette against scaled, min-max and raw versions of the same points.
    • Inertia vs distortion. scikit-learn's inertia_ is the sum of squared distances. Yellowbrick's elbow "distortion" is the "mean sum of squared distances to centers", and some tutorials sum plain distances. Tab 4 says which one your number is.
    • Label-encoding categories and running k-means. The codes invent an order and a spacing (LabelEncoder sorts the names alphabetically). Use one-hot for a few categories, or k-modes or Gower for categorical data.
    • One run, no seed. A single random start can land in a poor local minimum (53 of 100 seeds on the four-group example). Set random_state and n_init = 10; an elbow that rises somewhere is a sign of too few starts.
    • Including ID, name or target columns. A car_ID or a label-encoded car name is not a property of the car, and clustering on the target you want to explain makes the clusters say what you put in.

    How we checked the calculator

    An independent Python script, scripts/verify/kmeans.py, recomputes everything with its own code in plain Python: Lloyd's steps from given centres, the seeded starts, silhouette from pairwise distances, Kneedle, scaling, the adjusted Rand index by counting pairs, the categorical distances, modes and k-modes, parsing and the check tab. This page refuses to build if the browser code differs from it in any of 29,992 numbers, labels, indices or causes (678 cases including 241 Lloyd runs in 1 to 6 dimensions with k = 1 to 8, duplicate points, exact ties and empty clusters; 511 more assertions run inside the script). Run with scikit-learn 1.9.1, it also compared 3,449 values with KMeans (init = the same centres, n_init = 1, algorithm = "lloyd", tol = 0: labels, cluster_centers_, inertia_ and n_iter_ for 168 runs), silhouette_samples, silhouette_score and adjusted_rand_score: 0 mismatches. It skipped 67 runs where a cluster went empty (scikit-learn relocates the centre, we keep it) and 6 where a point was exactly as far from two centres and scikit-learn's arithmetic broke the tie the other way. The Auto MPG inertias, silhouettes, sizes, centroids and adjusted Rand indices are recomputed at build from the stored data and labels. Two deliberate bugs, inertia from un-squared distances and a silhouette whose b is the mean distance to all other points, each make the build fail.

    What this calculator does not cover

    • Other clustering methods: DBSCAN, hierarchical clustering, Gaussian mixtures, k-medoids. k-means assumes round clusters of similar size; scikit-learn notes that inertia "responds poorly to elongated clusters, or manifolds with irregular shapes".
    • Sample weights, mini-batch k-means, the Elkan algorithm and scikit-learn's tol stopping rule (the page stops when no label changes or no centre moves, which is scikit-learn with tol = 0).
    • The gap statistic, Davies-Bouldin and Calinski-Harabasz scores for choosing k.
    • Classification metrics. For accuracy, precision and recall, use the confusion matrix calculator; k-means labels have no fixed meaning, so compare them with classes using the adjusted Rand index, not accuracy.
    Learn machine learning with Python

    Clustering, the elbow curve and k-means are the unsupervised-learning week of Skill-Lync's PG program in data analytics and data science, after the regression and classification weeks.

    Frequently asked questions

    How do you do k-means step by step?

    Pick k starting centres. Assign every point to its nearest centre by squared Euclidean distance. Move each centre to the mean of its points. Repeat until no point changes cluster. In our 12-point example with the first three points as centres, the inertia at the three assignments is 374, 44.68 and 14.75.

    How do I choose k?

    Run k = 1 to 10, plot inertia against k and look for the bend (the elbow); the Kneedle method finds it objectively. Then check the mean silhouette, which is highest for the k that separates clusters best. On our three-blob data both point to k = 3. Prefer a k you can explain and use.

    Elbow vs silhouette: which should I use?

    Use both. Inertia always falls as k grows, so the elbow is a judgement about where the gains flatten, and many real curves have no clear bend. The silhouette compares each point's distance to its own cluster with the next nearest one, and peaks at a k with well separated clusters.

    Should I scale data before k-means?

    Yes, when features have different units. k-means uses Euclidean distance, so the widest column decides everything. In UCI Auto MPG, weight has a standard deviation of 848 against 2.76 for acceleration, and unscaled k = 3 clusters are just weight bands. StandardScaler gives every column an equal say.

    Can k-means use categorical data?

    Not directly. k-means needs means and Euclidean distances, which categories do not have. Label codes such as low = 1, vhigh = 3 invent an order and spacing. Use k-modes (simple matching and modes) for all-categorical data, or Gower distance with a medoid or hierarchical method for mixed data.

    What is inertia or WCSS in k-means?

    Inertia is the sum of squared Euclidean distances from each point to its nearest cluster centre, also called the within-cluster sum of squares. scikit-learn reports it as inertia_. It is zero only if every point sits on a centre, never rises when k grows, and for k = 1 equals the total sum of squares.

    Why do I get different clusters each run?

    The starting centres are random, and k-means stops at the nearest local minimum. On our four-group example a single random start ended in a bad minimum for 53 of 100 seeds, greedy k-means++ for 0. Set random_state for repeatable results and keep n_init at 10 or more.

    k-means vs k-modes vs k-prototypes?

    k-means is for numeric data: centres are means and distance is squared Euclidean. k-modes, from Huang (1998), is for categorical data: centres are modes and distance counts mismatched attributes. k-prototypes combines the two for mixed records, adding the numeric and categorical parts with a weight you choose.

    Related on Skill-Lync

    Sources

    • scikit-learn 1.9.1 documentation: KMeans (init "greedy k-means++", n_init "auto", tol, inertia_, n_iter_, the note on local minima); kmeans_plusplus (n_local_trials = 2 + log k); user guide 2.3.2 K-means and the Silhouette Coefficient; silhouette_samples; adjusted_rand_score. Source code of _kmeans_plusplus, the Lloyd convergence test and silhouette_samples in scikit-learn 1.9.1.
    • Quinlan, R. (1993). Auto MPG [Dataset]. UCI Machine Learning Repository, doi:10.24432/C5859H, CC BY 4.0 (auto-mpg.names: "horsepower has 6 missing values").
    • Bohanec, M. (1988). Car Evaluation [Dataset]. UCI Machine Learning Repository, doi:10.24432/C5JP48, CC BY 4.0.
    • Satopaa, V., Albrecht, J., Irwin, D. and Raghavan, B. (2011). Finding a "Kneedle" in a Haystack: Detecting Knee Points in System Behavior. ICDCS Workshops.
    • Gower, J. C. (1971). A General Coefficient of Similarity and Some of Its Properties. Biometrics 27(4), 857-871.
    • Huang, Z. (1998). Extensions to the k-Means Algorithm for Clustering Large Data Sets with Categorical Values. Data Mining and Knowledge Discovery 2, 283-304.
    • Yellowbrick documentation, KElbowVisualizer: the "distortion" metric.
    • Skill-Lync, the 47 public k-means challenge reports, read 24 Nov 2026.
    Free counselling

    From an elbow plot to clusters you can explain.

    Data roles want people who can say why they chose k, what each segment is, and whether scaling changed the answer. A Skill-Lync counsellor can map the data science or machine learning course that fits your background.

    Talk to a course counsellor

    Free. We call you back, usually the same day.

    By submitting you agree to our Terms and Privacy Policy.

    Talk to a career counsellor

    Talk to a career counsellor

    Free 20-minute call. We'll map the right course to where you want to work.

    By submitting you agree to our Terms and Privacy Policy.