Lab 6 of 8about 40 minutes
The penguins' kinds, with the names hidden
It uses what you learned in Clustering with k-means and PCA.
Start here
Run itThe penguins with all four measurements. The species is kept apart in kinds: nothing learns from it, and you only lay the groups against it at the end of a step.
1No ruler
Run itFrom Clustering with k-means and PCA
Run the cell. It prints how far each measurement spreads, then runs k-means and PCA on the measurements as they are. The mass spreads by 802 grams, the bill's depth by 2 millimetres. So the mass decides it all: the groups mix the kinds, and PCA's first direction keeps almost every bit of the spread, since it is the mass alone.
2Three groups on one ruler
Your turnPut the four measurements on one ruler, then ask k-means for three groups, as ml-kmeans did with two: one pipeline, and one call that fits it and gives every penguin a group. Keep the groups in labels.
Hint
The pipeline is StandardScaler() then KMeans(n_clusters=3, random_state=0). fit_predict takes the measurements.
One way to do it
groups = make_pipeline(StandardScaler(), KMeans(n_clusters=3, random_state=0))
labels = groups.fit_predict(X)
pd.crosstab(labels, kinds)3The total for every k
Your turnHow many groups are there? Run k-means for k from 1 to 8 on the scaled penguins, ten starts each, and keep each k's total squared distance, inertia_, in totals.
With four measurements the bend is softer than with the bills alone. The biggest drop is from one group to two, the Gentoos against the rest. Three still saves 187, and after that each group saves less than 80.
Hint
A list comprehension over range(1, 9), as the lesson's code has it: one KMeans(k, n_init=10, random_state=0) fitted on scaled for each k.
One way to do it
scaled = StandardScaler().fit_transform(X)
totals = [KMeans(k, n_init=10, random_state=0).fit(scaled).inertia_ for k in range(1, 9)]
print(np.round(totals))
plt.plot(range(1, 9), totals, marker="o")
plt.xlabel("k")4One start
Run itRun the cell. It runs k-means for three groups twenty times, each with one start only (n_init=1) and a different random_state, and prints each total. Most land on 379. A few get stuck near 486, a worse grouping that one start can't climb out of. Ten starts keep the lowest, which is why you ask for them.
5A flat map
Your turnFrom PCA and Clustering with k-means
Now flatten the four measurements to two numbers with PCA, on one ruler, and keep them in flat. Keep the share of the variance each direction holds in shares. The cell draws every penguin on the flat map, coloured by the group k-means gave it in step 2.
Hint
The lesson's pipeline: a standard scaler, then PCA(n_components=2). The shares are explained_variance_ratio_ of the pipeline's last step, pca[-1].
One way to do it
pca = make_pipeline(StandardScaler(), PCA(n_components=2))
flat = pca.fit_transform(X)
shares = pca[-1].explained_variance_ratio_
plt.scatter(flat[:, 0], flat[:, 1], c=labels, s=10)
print(flat.shape, shares.round(3))6How close to the kinds?
On your ownOn your own. Write agreement(groups, kinds): the share of penguins whose group's most common kind is their own. Then keep it for step 1's groups with no ruler in no_ruler, and for step 2's on one ruler in one_ruler.
Hint
In pd.crosstab(groups, kinds) each row is a group. Its biggest number is how many of its penguins share its most common kind. Add those up, and divide by all the penguins.
One way to do it
def agreement(groups, kinds):
table = pd.crosstab(groups, kinds)
return table.max(axis=1).sum() / len(kinds)
no_ruler = agreement(raw_groups, kinds)
one_ruler = agreement(labels, kinds)
print(round(no_ruler, 3), round(one_ruler, 3))7The digits on a flat map
On your ownFrom PCA
On your own. load_digits() gives 1,797 handwritten digits of 64 pixels, each from 0 to 16, so they are already on one ruler. Flatten them to two numbers with PCA alone, in digit_map, and draw each dot in its digit's colour (c=digits.target, cmap="tab10"). Keep the two shares in digit_shares.
The penguins' two numbers kept 88% of their variance, the digits' only 28%. That is why the lesson drew the digits with t-SNE and UMAP too.
Hint
The same three lines as for the penguins, with PCA(n_components=2) in place of the pipeline and digits.data as what it flattens.
One way to do it
digits = load_digits()
digit_pca = PCA(n_components=2)
digit_map = digit_pca.fit_transform(digits.data)
digit_shares = digit_pca.explained_variance_ratio_
plt.scatter(digit_map[:, 0], digit_map[:, 1], c=digits.target, cmap="tab10", s=5)
plt.colorbar()
print(digit_map.shape, digit_shares.round(3))Run on Pyodide 314, Python 3.14, pandas 3.0, matplotlib 3.10 and scikit-learn 1.8. Checked on .
