Chapters
Python114 chapters

Exercises

Clustering

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Group the flowers into three clusters without using the labels, and print the three cluster sizes.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans

X, _ = load_iris(return_X_y=True)
# cluster into 3 and print the sizes, sorted
Exercise 2

Print the inertia for k from 1 to 4, so the elbow is visible.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans

X, _ = load_iris(return_X_y=True)
# print one inertia per k, rounded to one place
Exercise 3

Print the silhouette score for three clusters, rounded to three places.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans

X, _ = load_iris(return_X_y=True)
# print the silhouette score for k=3