Menu
CoddyTech

Customer Segments

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

This chapter puts clusters to work, up to a playlist mapped by mood:

80 songs as dots, valence across and energy up, in four groups k-means found and named: tense at the top left, happy at the top right, sad at the bottom left, calm at the bottom right

First, segments: clusters people can act on. A hostel scaled two features and clustered its guests:

150 hostel guests, nights per stay across and days booked ahead up, in three segments: school trips booked months ahead, weekenders with short stays, backpackers with long stays booked late

Real units say what a segment is like. Its scaled center shows what sets it apart: every feature in std from the average guest.

X = StandardScaler().fit_transform(guests[["nights", "days_ahead"]])
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
print(km.cluster_centers_.round(1))

This prints:

[[ 1.3 -0.7]
 [-0.7 -0.7]
 [-0.7  1.4]]

Each row's number furthest from 0 names its segment. Row 0 stays 1.3 std longer: backpackers. Row 2 books 1.4 std earlier: school trips.

challenge icon

Challenge

Medium

A theatre wants to know its 166 members. The program reads the features to segment on, such as age,ticket_price.

  1. Scale those columns, cluster into best_k(X) segments with the starter's helper, and print how many.
  2. Biggest first, print each segment's size and name: its center's feature furthest from 0, high or low, and how far.

For another theatre and age,shows_per_year:

4 segments
57 members: high shows_per_year (1.2 std from average)
52 members: low shows_per_year (1.0 std from average)
40 members: low age (1.4 std from average)
32 members: high age (1.5 std from average)

Try it yourself

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# One row per theatre member
members = pd.read_csv("theatre.csv")
# The features to segment on, such as age,ticket_price
features = input().split(",")


# From Silhouette Scores: the k from 2 to 6 with the best silhouette for X
def best_k(X):
    best, best_score = 2, -1
    for k in range(2, 7):
        labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X)
        score = silhouette_score(X, labels)
        if score > best_score:
            best, best_score = k, score
    return best


# 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