Exercises
Clustering
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
labels_ holds the cluster for each point. Pass n_init=10 and random_state=0.
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
X, _ = load_iris(return_X_y=True)
model = KMeans(n_clusters=3, random_state=0, n_init=10).fit(X)
print(sorted(int((model.labels_ == c).sum()) for c in range(3)))Exercise 2Passed
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
inertia_ is on the fitted model.
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
X, _ = load_iris(return_X_y=True)
for k in range(1, 5):
model = KMeans(n_clusters=k, random_state=0, n_init=10).fit(X)
print(round(model.inertia_, 1))Exercise 3Passed
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
silhouette_score takes the data and the labels.
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X, _ = load_iris(return_X_y=True)
labels = KMeans(n_clusters=3, random_state=0, n_init=10).fit_predict(X)
print(round(silhouette_score(X, labels), 3))