Courses / Data Science & ML with AI
Session 8 of 8
K-Means Clustering and PCA in Python: Unsupervised Learning
Notes
K-Means Clustering and PCA in Python: Unsupervised Learning Explained
Course: Data Science & ML with AI
Before you start
You need Python 3 with pandas, scikit-learn and numpy installed
(pip install pandas scikit-learn numpy). Every example uses a dataset that ships inside scikit-learn, or a small table typed
into the code, so there is nothing to download, no account and no API key. You should know what a
feature and a row are, and what supervised learning means (learning from rows that include the
answer). If you have met train_test_split and the idea of a baseline, that helps, but nothing here
depends on it. Run each code block yourself and compare your output with the output shown; if your
installed library versions differ, a last digit may differ too.
Keep one question in mind while you read: if a table has no answer column, how do I find groups in it and know whether the groups mean anything? By the end you will fit a clustering, pick the number of groups with evidence, shrink a 64-column table to a handful of columns, and check an AI assistant’s description of the groups against the numbers.
Summary
Clustering is unsupervised learning: it groups rows by similarity when there is no target column, and k-means is the standard way to do it, placing a chosen number of centre points so that each row sits near the centre of its own group. Because k-means measures straight-line distance, the scale of each column decides how much it counts, and because it starts from random centres, one run can land on a poor answer. Principal component analysis (PCA) is a separate tool that replaces many columns with a few new ones that keep as much of the spread in the data as possible, which makes tables easier to plot and cluster. With no answer column there are no right labels to score against; inertia measures how tight the groups are, not what they mean, so a clustering is also judged by profiling each group, meaning computing the average of every feature per group, and by whether those profiles describe something real. This chapter teaches both tools on the iris and digits datasets and shows how to check an AI assistant’s names for the groups it was given.
Key concepts
| Term | Definition |
|---|---|
| Unsupervised learning | Learning from a table with no target column, to find structure such as groups or a simpler description of the columns. |
| Clustering | Splitting rows into groups so that rows in the same group are more alike than rows in different groups, with no labels given in advance. |
| K-means | A clustering method that picks k centre points and assigns every row to its nearest centre, then moves each centre to the average of its rows, repeating until the centres stop moving. |
| Centroid (cluster centre) | The average of all the rows in a cluster, one value per feature. It is not usually one of the actual rows. |
| Inertia | The sum, over all rows, of the squared distance from a row to its nearest centroid. Lower means tighter clusters. It is not scaled, so it only compares fits of the same data. |
| Elbow method | Fitting k-means for several values of k and plotting inertia against k, then choosing the k after which the improvement becomes small. |
| Local minimum | A fit that is better than every small change to it but worse than the best possible fit. K-means can end in one, depending on where the centres start. |
n_init |
The number of times k-means is run from different starting centres; scikit-learn keeps the run with the lowest inertia. |
| Standardising (scaling) | Rewriting each column as its distance from its own average, counted in standard deviations, so that no column dominates a distance just because of its units or scale. |
| Cluster profile | The average of each feature inside one cluster, shown side by side for all clusters, used to describe what each group is. |
| Principal component analysis (PCA) | A method that builds new columns, called components, as weighted mixes of the old ones, ordered so that the first keeps the most variance. |
| Principal component | One of the new columns PCA builds. Its score for a row is where that row sits along that direction. |
| Explained variance ratio | The share of the table’s total variance that one component keeps. The ratios of all components add up to 1. |
| Adjusted Rand index (ARI) | A score that compares two ways of grouping the same rows: 1.0 means identical groupings, and values near 0 mean no more agreement than chance. It ignores which number each group was given. |
Explanations
The failure, before the explanation
A shop owner has ten customers described by two columns: yearly_spend in dollars and
visits_per_month. The customers really do form two groups. Five visit about twice a month and five
visit nine or ten times a month, and their spending is much the same either way. She asks k-means for
two clusters and gets two groups back with no error message. She writes “one group of heavy
spenders, one of light spenders” in her report. Run the same thing:
import pandas as pd
from sklearn.cluster import KMeans
shop = pd.DataFrame({
"yearly_spend": [1900, 2100, 1950, 2050, 2000, 1920, 2080, 1980, 2060, 1940],
"visits_per_month": [2, 10, 3, 9, 2, 10, 3, 9, 2, 10],
})
raw = KMeans(n_clusters=2, n_init=10, random_state=42).fit(shop)
print(raw.labels_)
print(shop.groupby(raw.labels_).mean().round(1))
It prints:
[0 1 0 1 0 0 1 0 1 0]
yearly_spend visits_per_month
0 1948.3 6.0
1 2072.5 6.0
Look at the second table. Both clusters average exactly 6.0 visits a month. The split is on spend alone, a difference of about 124 dollars, and the real structure, the visit pattern, was ignored. The rest of this chapter explains why this happens (the “scaling” section) and how a profile table like this one is the tool that exposes it. You will fix this table yourself in that section.
What clustering and k-means are
Picture a postal worker with a bag of unsorted letters and four pigeonholes. She puts one marker in each hole’s position on a map of the town, drops each letter into the hole whose marker is nearest to its address, then moves each marker to the middle of the addresses now in its hole, and repeats. After a few rounds the markers stop moving. Nobody told her which letters belong together; the groups came from distances. That is k-means, and the number of holes is the k in the name.
A second picture: a teacher scatters 30 students’ (height, weight) points on graph paper and asks for three groups. She drops three pins at random, ties every student to the nearest pin, slides each pin to the middle of its students, and re-ties. The pins settle where the students bunch up.
Clustering is the general task; k-means is one method for it. The scikit-learn user guide describes k-means as separating samples into groups of equal variance by minimising the criterion called inertia, and it calls each group’s mean a centroid, noting that centroids are not in general points from the data. Here is k-means on the iris dataset, which holds 150 flowers described by four measurements in centimetres:
from sklearn.datasets import load_iris
iris = load_iris(as_frame=True)
X = iris.data
print(X.shape)
print(X.head(3))
km = KMeans(n_clusters=3, n_init=10, random_state=42).fit(X)
print(km.labels_[:5])
print(pd.Series(km.labels_).value_counts().sort_index().to_list())
print(round(km.inertia_, 1))
(150, 4)
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
[1 1 1 1 1]
[62, 50, 38]
78.9
n_clusters=3 is the k. fit learns the centres, and labels_ holds the cluster number given to
each row. The three clusters hold 62, 50 and 38 flowers. The first five flowers all landed in
cluster 1; the number is only a tag. Cluster numbers have no meaning and no order: another
run, another library version or another random_state can hand the same group a different number.
inertia_ is 78.9: the sum of squared distances from each flower to its centre. On its own that number
says little, because inertia is not a normalised metric (the documentation says we only know that lower
is better and zero is optimal). It becomes useful when you compare fits of the same table, as the next
section does.
Note that the iris dataset has 150 flowers and a species label for each, but we did not give the labels to k-means. This is the setting that makes it unsupervised: the model sees only the four columns.
How to choose the number of clusters (the elbow method)
Suppose you sort a bag of mixed coins. With one pile, the coins in it differ a lot. With two piles they differ less in each. With 150 piles, one coin each, they do not differ at all, and the sorting is worthless. More groups look tidier, so you need a rule for when to stop. The k-means answer is the elbow method: fit for k = 1, 2, 3 … and watch inertia.
for k in range(1, 9):
inertia = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X).inertia_
print(k, round(inertia, 1))
1 681.4
2 152.3
3 78.9
4 57.2
5 46.5
6 39.0
7 34.3
8 30.1
Read the gaps, not the values. Going from 1 to 2 clusters removes 529.1 of inertia, from 2 to 3 removes 73.4, from 3 to 4 only 21.7, and from 4 to 5 only 10.7. The curve falls steeply and then flattens; the bend, the “elbow”, is near k = 3, so three clusters is a reasonable choice. A chart of these eight points would show a steep line dropping to k = 3 and a nearly flat line after it. Two cautions. First, the lowest inertia is at k = 8 here, and it would be lower still at k = 150, so picking the lowest value is the mistake the coin analogy warns about. Second, the elbow is a judgement: when the curve bends gradually, two analysts can pick different k, and the right k is often the one whose profiles (below) make business sense.
Why k-means can give a different answer on a different start
Imagine dropping three pins on a map at random and letting them slide to the middle of nearby addresses. If two pins start in the same crowded town, they can split it between them while an entire second town gets one pin for the whole of it. Every pin has stopped moving, yet a better placement exists. The documentation says the same in its own words: K-means will converge, but it may be to a local minimum, which depends highly on the initialisation of the centroids, so the computation is often done several times with different initialisations.
Prove it by starting k-means from one random start at a time, with six different seeds:
for seed in range(6):
one = KMeans(n_clusters=3, init="random", n_init=1, random_state=seed).fit(X)
print(seed, round(one.inertia_, 1))
0 78.9
1 78.9
2 78.9
3 78.9
4 78.9
5 142.8
Five seeds reach 78.9, the value you saw before. Seed 5 stopped at 142.8, an answer nearly twice as
loose, and with nothing in the output to warn you. That is the local-minimum trap. The cure is the
n_init parameter: run the algorithm that many times from different starting centres and keep the best run in terms of inertia, which is what the scikit-learn
reference for KMeans states. The default init="k-means++" also helps, because it chooses starting
centres that are generally far apart. In the runs above, n_init=10 is why the answer was 78.9.
The rule to take away: compare runs by inertia, and do not rely on a single start.
Why you must scale features first
Go back to the shop owner. K-means measures straight-line distance between rows. A spend column that varies by 200 dollars and a visit column that varies by 8 visits are not on equal terms: the dollar differences are around twenty-five times larger, so they dominate the distances and the visit column is nearly ignored. Think of two people deciding how far apart two towns are: one measures in metres and one in kilometres, and then you add their numbers together. The metres person will dominate the sum.
Standardising puts every column on the same footing: subtract the column’s average and divide by
its standard deviation, so each column has an average of 0 and a spread of 1. The scikit-learn
StandardScaler does exactly this. Fix the shop table:
from sklearn.preprocessing import StandardScaler
shop_scaled = StandardScaler().fit_transform(shop)
fixed = KMeans(n_clusters=2, n_init=10, random_state=42).fit(shop_scaled)
print(fixed.labels_)
print(shop.groupby(fixed.labels_).mean().round(1))
[1 0 1 0 1 0 1 0 1 0]
yearly_spend visits_per_month
0 1998.0 9.6
1 1998.0 2.4
Now the groups separate on visits (9.6 against 2.4 a month) and tie exactly on spend (1998.0), the true structure. Notice that we grouped the scaled numbers but profiled with the original table, so the averages are in dollars and visits, readable by a person. Notice also that the labels flipped (the first customer is now in cluster 1): another reminder that the numbers are tags.
Scaling is a decision, not a ritual. The iris columns are all centimetres on similar ranges, so scaling matters less, and it is not guaranteed to help. The adjusted Rand index in the next section shows that, on iris, clustering the raw centimetres agrees more with the known species than clustering the standardised columns. Scale when the columns have unlike units or ranges (dollars with visits, grams with kilometres); when every column is the same kind of measurement, check both.
How to tell whether clusters mean anything: profiles and the adjusted Rand index
Suppose k-means hands you three iris groups labelled 0, 1 and 2. Average the petal length inside each group: if one group’s average is far smaller than the other two, that group is the small-petalled flowers, and you now know what it means. That table of averages is a cluster profile: the per-cluster average of every feature. A clustering has no answer column to be scored against, so describing it this way is how you test it. For iris:
print(X.groupby(km.labels_).mean().round(2))
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.90 2.75 4.39 1.43
1 5.01 3.43 1.46 0.25
2 6.85 3.07 5.74 2.07
Read down each column. Cluster 1 has the shortest and narrowest petals (1.46 cm long, 0.25 cm wide) and the widest sepals. Cluster 2 has the longest and widest petals (5.74 and 2.07). Cluster 0 sits between them. So the profile gives each group a description a person can use: small-petalled flowers with broad sepals, large-petalled flowers, and a middle group. A cluster that has the same average as every other cluster, like the shop owner’s first result, is a warning that the split may mean nothing.
Iris happens to carry species labels, which a real clustering problem usually lacks. Using them after the fit, only to check, shows how well the groups line up. The adjusted Rand index (ARI) compares two groupings of the same rows and, as its documentation says, ignores permutations of the cluster numbers, with 1.0 meaning identical:
from sklearn.metrics import adjusted_rand_score
print(pd.crosstab(km.labels_, iris.target_names[iris.target]))
print(round(adjusted_rand_score(iris.target, km.labels_), 2))
iris_scaled = StandardScaler().fit_transform(X)
km_scaled = KMeans(n_clusters=3, n_init=10, random_state=42).fit(iris_scaled)
print(round(adjusted_rand_score(iris.target, km_scaled.labels_), 2))
col_0 setosa versicolor virginica
row_0
0 0 48 14
1 50 0 0
2 0 2 36
0.73
0.62
The table counts flowers by cluster (rows) and species (columns). Cluster 1 holds all 50 setosa and nothing else, a clean group. Cluster 0 is mostly versicolor with 14 virginica mixed in, and cluster 2 is mostly virginica with 2 versicolor. The two species that overlap are the ones k-means mixes. The ARI is 0.73 for the raw columns and 0.62 for the standardised ones, which is why the previous section told you to check both rather than assume scaling wins.
What PCA is and how to read it
Shine a torch on a pencil held in the air. If you aim it from the side, the shadow on the wall is a long line and shows the pencil’s length. If you aim it from the tip, the shadow is a dot and tells you nothing. PCA is a way to find the best angle to cast the shadow, for a table with many columns. A second picture: a class’s five exam marks per student can be summed into one “overall” number. That loses detail, but the single number still keeps most of what separates strong students from weak ones. PCA does the same job but chooses the weighting so that as much of the spread as possible survives.
Principal component analysis builds new columns, the components, each a weighted mix of the old columns. The first component points along the direction in which the rows vary most, the second along the most variation left over at right angles to the first, and so on. The scikit-learn docs describe PCA as linear dimensionality reduction using singular value decomposition, and note that the input is centered but not scaled for each feature, so when your columns have unlike units you standardise before PCA, as before k-means. The explained variance ratio of a component is the share of the table’s total variance that it keeps.
The digits dataset is a good test. Each of its 1,797 rows is a handwritten digit stored as an 8-by-8 grid of pixel intensities, 64 columns in all, with integer values from 0 to 16:
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
import numpy as np
digits = load_digits()
print(digits.data.shape, digits.data.min(), digits.data.max())
pca2 = PCA(n_components=2, random_state=42).fit(digits.data)
print(pca2.explained_variance_ratio_.round(3))
print(round(pca2.explained_variance_ratio_.sum(), 3))
scores = pca2.transform(digits.data)
print(scores.shape)
(1797, 64) 0.0 16.0
[0.149 0.136]
0.285
(1797, 2)
Sixty-four columns have become two. The first component keeps 14.9% of the variance and the second 13.6%, so together they keep 28.5%. That is a
modest share: a two-column plot loses most of the information. The transform call returned
scores, 1,797 rows by 2 columns, one position per image. To see what those positions mean, average
them per digit (the digit labels are used here only to describe the positions):
means = pd.DataFrame(scores, columns=["pc1", "pc2"]).groupby(digits.target).mean()
print(means.round(1).loc[[0, 1, 4]])
pc1 pc2
0 2.0 -21.1
1 5.4 12.7
4 22.3 0.6
On a scatter plot of these two columns, the 0s would sit low (average second component -21.1), the 1s high (12.7), and the 4s far to the right (average first component 22.3). The images already start to separate, with a lot of overlap left because most of the variance was thrown away.
How many components to keep, and clustering after PCA
If two components keep only 28.5%, how many do you need? Count them:
full = PCA(random_state=42).fit(digits.data)
cumulative = np.cumsum(full.explained_variance_ratio_)
for n in (2, 10, 20, 30):
print(n, round(cumulative[n - 1], 3))
pca90 = PCA(n_components=0.90, random_state=42).fit(digits.data)
print(pca90.n_components_)
2 0.285
10 0.738
20 0.894
30 0.959
21
np.cumsum adds the ratios up one by one, so each line reads “the first n components together keep
this share”. Passing a fraction such as n_components=0.90 tells scikit-learn to keep as many
components as needed to explain more than that share of the variance, and it chose 21 components, a
drop from 64 columns to 21. The cumulative value at 20 (0.894) falls just short of 0.90, which is
consistent with 21.
Does reducing hurt clustering? Cluster the digits into 10 groups three ways and compare each with the true digits using the ARI (labels used only to check):
reduced = pca90.transform(digits.data)
for name, data in (("all 64 pixels", digits.data), ("21 components", reduced),
("2 components", scores)):
labels = KMeans(n_clusters=10, n_init=10, random_state=42).fit_predict(data)
print(name, round(adjusted_rand_score(digits.target, labels), 2))
all 64 pixels 0.67
21 components 0.67
2 components 0.39
Twenty-one components cluster as well as all 64 pixels (0.67 each) while handling about a third of the columns, which is why the scikit-learn guide suggests running a dimensionality reduction such as PCA before k-means. Two components fall to 0.39 because 71.5% of the variance is gone. Remember that a pretty two-dimensional plot is not the same as a good reduction: check the cumulative variance before you trust it.
With AI: check an assistant’s names for the clusters
An AI assistant writes clustering code and describes the output fluently, and it describes the groups it was told about with the same confidence whether the description is right or wrong. Here is an assistant’s answer to “Cluster the iris measurements into three groups and name the groups”:
km = KMeans(n_clusters=3, n_init=10, random_state=42).fit(X)Cluster 0 is setosa: the smallest flowers. Cluster 1 is versicolor: medium flowers. Cluster 2 is virginica: the largest. I chose three clusters because k = 3 gives the lowest inertia (78.9).
The code is fine and the prose reads well. The check is the one this chapter taught: profile the
clusters and compare. Print X.groupby(km.labels_).mean() (you ran it above) and test each sentence
against the numbers:
- The names are in the wrong order. Cluster 0’s petal length is 4.39 cm, the middle value, not the smallest. The smallest flowers (petal length 1.46 cm) are in cluster 1, and the largest (5.74) in cluster 2. The assistant assumed cluster number 0, 1, 2 follows species order and size order; cluster numbers are only tags. Its labels would be right only for cluster 2.
- The reason for k = 3 is wrong. Inertia at k = 3 is not the lowest; the elbow table shows 30.1 at k = 8. The honest reason is the elbow: the drop from k = 2 to 3 is 73.4 and the next drop is only 21.7.
- The names borrow a label k-means never saw. The assistant used species names, but the crosstab shows cluster 0 holds 48 versicolor and 14 virginica, so even a correctly numbered “versicolor” cluster would be mixed. A description such as “medium petals, 4.39 cm long” is safer.
Try it before moving on: change n_clusters to 4 in the code, print the profile table, and write one
sentence describing each cluster from the numbers alone, without using species names.
Three situations you will meet, and what they mean for your work
Before the table, three situations:
- A marketing analyst clusters customers on yearly spend in dollars and number of orders, and every cluster comes back with a different spend but the same average order count.
- You run k-means twice with different
random_statevalues and the cluster sizes differ, so a colleague asks which run to report. - You have a table of 200 sensor columns and cannot plot it, and a plot of its first two PCA components shows one muddy blob.
| What you see | Cause to suspect | What to do |
|---|---|---|
| Clusters split on one big-number column (situation 1) | The columns are on unlike scales and one dominates the distance | Standardise, refit, and compare the profiles of both versions |
| Different runs, different answers (situation 2) | A local minimum from a lucky or unlucky start | Set n_init high enough, compare by inertia, report the lowest |
| One muddy blob in a two-component plot (situation 3) | Two components keep only a small share of the variance | Print the cumulative explained variance, keep enough components for a share you chose, and cluster on those |
Flashcards
Say the answer aloud before revealing it. Speaking it is what exposes the gaps that reading past a written answer hides.
What is clustering, and how does it differ from classification?
Clustering groups rows by similarity when the table has no target column, so no labels are given and none can be scored. Classification learns from rows that carry a known label and predicts that label for new rows.
How does k-means work in one loop?
Pick k centres, assign every row to its nearest centre, move each centre to the average of its rows, and repeat until the centres stop moving. Each centre is the centroid of its cluster.
What does inertia measure, and what can it not tell you?
It is the sum of squared distances from each row to its nearest centroid, so lower means tighter clusters. It is not normalised and keeps falling as clusters are added, so it cannot pick k by itself.
How does the elbow method choose k?
Fit for k = 1, 2, 3 and so on, and look at how much inertia drops at each step. Choose the k after which the drops become small. On iris the drops were 529.1, 73.4, 21.7 and 10.7, so k = 3.
Why can two k-means runs give different answers, and what is the fix?
Starting centres are random and the algorithm can stop in a local minimum. Use n_init so that
several starts are tried and the run with the lowest inertia is kept.
Why standardise columns before k-means?
K-means uses straight-line distance, so a column with big numbers dominates the sum. In the shop table the dollar column hid the visit pattern until the columns were standardised.
Why are cluster numbers like 0, 1 and 2 not a ranking?
They are arbitrary tags handed out by the algorithm and can change between runs or versions. To know what a cluster is, read its profile of per-cluster feature averages.
What does the adjusted Rand index tell you?
How closely two groupings of the same rows agree, ignoring which number each group was given. 1.0 is identical, and values near 0 are no better than chance. On iris, raw columns scored 0.73.
What does PCA do to a table?
It builds a smaller set of new columns, each a weighted mix of the old ones, ordered so the first keeps the most variance. It centres the data but does not scale it.
What does explained variance ratio mean, and how many digits components keep 90%?
It is the share of the table’s total variance that a component keeps. For the digits table 21 components keep more than 90%, and two components keep only 28.5%.
Model answer
The question: “You have a table with many columns and no answer column. How would you find the groups in it and decide whether they mean anything?” A strong answer hits five beats, in this order:
- Scale — put unlike columns on the same footing with standardising.
- Reduce — if there are many columns, use PCA and check the cumulative variance kept.
- Choose k — fit several values and read the elbow in inertia.
- Restart — use
n_initso a poor starting point does not decide the answer. - Profile — average every feature per cluster and describe each group from those numbers.
“First I would standardise the columns, because k-means uses distance and a column with big numbers would otherwise decide the groups. If there are many columns, I would run PCA and keep enough components to explain a share of variance I chose, checking the cumulative ratio rather than trusting a two-dimensional plot. Then I would fit k-means for a range of k and look for the elbow in inertia, not just the lowest value. I would use several restarts through
n_init, because one start can end in a local minimum, and keep the lowest-inertia run. Last, I would profile each cluster with per-cluster feature averages, name the groups from those numbers, and treat cluster numbers as tags that mean nothing.”
Missing a beat is a failure state. Without scale, one big column decides the groups, as in the shop table. Reduce is the beat you may skip when it does not help: on digits, 21 components scored the same 0.67 as all 64 pixels, so it bought a lighter table, not better groups, and you should say so. Without choose k, the group count is a guess. Without restart, a local minimum such as the 142.8 run can pass as the answer. Without profile, the groups have no meaning, and an assistant’s guess at their names goes unchecked.
Why this matters
- Customer and product grouping. Segmenting customers by behaviour gives marketing and support teams groups to act on, and a profile table is what makes a segment something a team can describe.
- Shrinking wide tables. Sensor, text and image features come in hundreds of columns; PCA makes them plottable and cheaper to model, as 64 pixel columns became 21.
- Trusting unsupervised results. With no answer column nobody can tell you the clustering is wrong, so the habit of profiling, restarting and comparing is the only protection.
- Reviewing AI-written analysis. An assistant writes names and reasons for clusters with equal confidence whether or not the numbers agree, so a profile table is how you tell the difference.
After this unit
You now have the full path for unlabelled data: scale, reduce, choose k, restart and profile, and a
way to check anyone’s description of the groups. That completes the course’s tour of the lifecycle:
question, data, cleaning, exploration, features, supervised models, evaluation and now unsupervised
structure. To consolidate, try this on your own. Load scikit-learn’s bundled wine dataset with
load_wine(as_frame=True), set its labels aside, and cluster its 13 columns: standardise them, print
the inertia for k from 2 to 6 with n_init=10, random_state=42, choose k from the elbow, then score
the k = 3 result against the hidden labels with adjusted_rand_score. Repeat the k = 3 run without
standardising.
Check your answer
The inertia falls 1658.8, 1277.9, 1175.4, 1109.5, 1046.0 for k = 2 to 6; the big drop ends at k = 3, which matches the three wine cultivars. Scaled, the k = 3 clustering scores an adjusted Rand index of 0.9; unscaled it scores 0.37, because one large-valued column decides the groups, the same failure as the shop table. If your scaled score is far below 0.9, check that you standardised before clustering.
Quiz
Answers are not marked on this page yet. Work through the questions and check the written ones against the criteria printed with each question. The answer key is kept back for now.
Quiz — K-Means Clustering and PCA in Python: Unsupervised Learning Explained
Instructions: Eight multiple-choice questions. Pick one option per question. Work closed-book, then compare your letters with the answer key, which is held separately and holds the reasons.
1. [recall] What does the inertia value of a fitted k-means model report?
a) The share of all the rows that ended up in the largest cluster the algorithm found b) The number of restarts the algorithm needed before it settled on its final answer c) The sum of squared distances from every row to the centre of its own nearest cluster d) The average of each feature, taken across all the rows of the whole table at once
2. [application] A table holds yearly_spend (values from 1,900 to 2,100) and visits_per_month
(values from 2 to 10). You want k-means to let both columns shape the groups. Which step should come
before the fit?
a) Standardise both columns so each one has an average of 0 and a standard deviation of 1 b) Drop the visits column, because its numbers are small next to the yearly spend figures c) Sort the rows by yearly spend so that customers with similar habits sit next to each other d) Raise the number of clusters until the visits column begins to change the groups formed
3. [scenario] You cluster the iris measurements into three groups. An assistant tells you: “Cluster 0 is the group with the smallest flowers.” What should you do before using that sentence in a report?
a) Refit with other random_state values until cluster 0 happens to match the assistant’s claim
b) Accept it, since the algorithm numbers its groups in order from the smallest flowers upward
c) Check that the inertia is lower than the inertia of a model fitted with a single cluster
d) Print the per-cluster feature averages and see which cluster really has the smallest petals
4. [application] You fit k-means for k = 1 to 5 on a table and record these inertia values, in that order: 900, 300, 120, 105 and 95. Which choice of k does the elbow method support?
a) k = 2, because the single biggest drop in inertia comes when going from one cluster to two b) k = 3, because the drops after it are small compared with the drops that came before it c) k = 5, because it has the lowest inertia value among all the values that were tried here d) k = 1, because one cluster is the simplest grouping that still describes every row there
5. [scenario] You fit KMeans(n_clusters=3, init="random", n_init=1) twice with different
seeds. The first run ends with inertia 78.9 and the second with 142.8. Which action fits best?
a) Average the centres from the two runs so that the final result uses a fairer single set
b) Keep the first run, since a result that was produced earlier is more likely to be sound
c) Keep the second run, because a larger inertia means each cluster holds a greater share of rows
d) Raise n_init so several starts are tried, and keep the run with the lowest inertia
6. [recall] In scikit-learn’s PCA, what does explained_variance_ratio_ hold?
a) The share of the table’s total variance that each component keeps b) The share of the rows that each component assigns to its own group c) The fraction of pixel values that were missing before the fit ran d) The strength of the link between each component and the target column
7. [application] The digits table has 64 pixel columns. You want PCA to keep just enough components to explain more than 90% of the variance, and you want the library to count them. Which call does that?
a) PCA(n_components=90), which asks for ninety components, more than the 64 columns on hand
b) PCA(n_components=0.10), which keeps just enough components to explain ten percent
c) PCA(n_components=0.90), which keeps enough components to explain ninety percent
d) PCA(n_components=2), which keeps two components whatever share of the variance they hold
8. [scenario] An analyst plots the digits on the first two PCA components, sees heavy overlap between the digits, and concludes that digits cannot be told apart from their pixels. Those two components keep 28.5% of the variance. What would you do?
a) Accept the conclusion, since overlap on a plot proves that the pixel columns hold no pattern b) Check the cumulative explained variance and cluster on enough components to keep far more of it c) Remove the scaling step from k-means so that the overlapping groups are able to separate d) Drop the pixel columns that overlap the most and refit PCA on the columns that remain
Want help building this with someone?
Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.
Ask about mentor-led trainingTechEazy Consulting training material — not affiliated with or endorsed by pandas, scikit-learn or any other project or company named in this course.