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:
First, segments: clusters people can act on. A hostel scaled two features and clustered its guests:
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
MediumA theatre wants to know its 166 members. The program reads the features to segment on, such as age,ticket_price.
- Scale those columns, cluster into
best_k(X)segments with the starter's helper, and print how many. - Biggest first, print each segment's size and name: its center's feature furthest from 0,
highorlow, 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unsupervised Learning
1Finding Groups
Learning Without LabelsMeasuring SimilarityK-Means by HandK-Means in scikit-learnRecap: Gym Members7PCA in Practice
Seeing 64 DimensionsComponents as PatternsCompress and RebuildPCA Before a ModelRecap: Face Scanner10Project: Digit Explorer
Look at the DigitsShrink with PCACluster the DigitsName the ClustersFind the Odd OnesPractice on your own: Online Python compiler