Menu
CoddyTech

Centers in Real Units

Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 12 of 51.

A cluster's center is its typical member. K-means found the park's centers in scaled data, so they read as z-scores. The same centers, before and after:

Two charts of the theme park visitors with the 3 cluster centers marked by crosses. Left, scaled axes: the centers sit at numbers like 0.8, 1.3. Right, real units: the same centers at 6.8 hours and 13.9 rides, 6.0 and 6.2, 2.4 and 3.0

Keep the scaler: it remembers each feature's mean and spread, and inverse_transform undoes the scaling:

scaler = StandardScaler()
km.fit(scaler.fit_transform(park))
centers = scaler.inverse_transform(km.cluster_centers_)
print(centers.round(1))

This prints hours, rides and age, one row per cluster:

[[ 6.   6.2 38.4]
 [ 2.4  3.  45.8]
 [ 6.8 13.9 20.7]]

Cluster 2's center was 0.8 and 1.3. Now it reads 6.8 hours and 13.9 rides: the same point, in units a person can use.

challenge icon

Challenge

Medium

A glove maker turns hand clusters into 4 glove sizes. The starter scales 150 hands, clusters them, and reads a customer's hand into new_hand.

  1. Find the cluster the new hand joins: scale it first.
  2. Turn the centers back into cm.
  3. Print that cluster's center, 1 decimal, as below.

For another glove maker:

Your glove size: hand 20.3 cm, palm 8.9 cm, finger 8.6 cm

Try it yourself

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

# 150 hands a glove maker measured, in cm: hand length, palm width, middle finger
hands = pd.read_csv("hands.csv")
scaler = StandardScaler()
scaled = scaler.fit_transform(hands)
# One cluster per glove size
km = KMeans(n_clusters=4, n_init=10, random_state=0)
km.fit(scaled)

# A new customer's hand, as a one-row table with the same columns
new_hand = pd.DataFrame({
    "hand_cm": [float(input())],
    "palm_cm": [float(input())],
    "finger_cm": [float(input())],
})

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unsupervised Learning

Practice on your own: Online Python compiler