Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Machine Learning – Customer Segmentation

Machine Learning - Customer Segmentation

In today's data-driven business world, understanding customers is the key to success.

However, when your customer base reaches tens of thousands or even millions, manually analyzing each customer's characteristics and behavior patterns becomes impractical.

At this point, machine learning techniques, especially the clustering algorithms in Unsupervised learning unsupervised learning, become a powerful tool.

Customer segmentation, also known as customer subdivision, fundamentally aims to divide a huge customer base into several subgroups with similar characteristics. This is like an experienced shopkeeper who no longer views customers as a vague whole, but can clearly identify different groups such as price-conscious housewives, tech enthusiasts keen on new products, and high-end customers who value service experience. By applying targeted marketing, service, and product strategies to different groups, enterprises can significantly improve operational efficiency and customer satisfaction.

This article will guide you step by step through a complete hands-on customer segmentation project. We will use the classic K-Means clustering algorithm to analyze a simulated retail customer dataset, from data understanding to model evaluation, ultimately obtaining segmentation results with business insights.


Understanding Cluster Analysis and the K-Means Algorithm

Before starting the hands-on work, we need to understand the core tools we will use.

What is cluster analysis?

Cluster analysis is an unsupervised learning method. Unlike supervised learning (such as predicting house prices or recognizing cat and dog images), clustering algorithms have no pre-labeled "correct answers" (i.e., labels). Its task is to explore the inherent structure of the data, automatically grouping similar data points into the same group (called a "cluster"), while keeping data points in different groups as dissimilar as possible.

A simple analogy: Imagine you have a basket of mixed fruit containing apples, oranges, and bananas. The task of a clustering algorithm is to automatically pile fruits of similar shape, color, and size into separate groups, without anyone telling you the category names.

How the K-Means Algorithm Works

K-Means is one of the most commonly used and intuitive clustering algorithms. "K" represents the number of clusters we want to divide the data into. Its working principle can be summarized in four steps:

  1. Initialization: Randomly select K data points as the initial "cluster centers" (centroids).
  2. Assignment: Calculate the distance from each data point to each centroid (usually using Euclidean distance), then assign each point to the cluster of its nearest centroid.
  3. update: Recompute the centroid of each cluster (i.e., the average of all points in that cluster).
  4. Iterate: Repeat steps 2 and 3 until the centroid positions no longer change significantly or a preset number of iterations is reached.

The flowchart below clearly illustrates this process:

Key Points of the Algorithm:


Hands-On Practice: Retail Customer Segmentation

Now, let us put theory into practice. We will use Python and its powerful data science ecosystem to complete this project.

Step 1: Environment Setup and Data Loading

First, make sure the necessary libraries are installed in your Python environment:pandas for data processing,numpy for numerical computation,matplotlib and seaborn for visualization,scikit-learn is the core machine learning library.

Example

Import the necessary libraries

import

pandas

as

pd

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

import

seaborn

as

sns

from

sklearn.

cluster

import

KMeans

from

sklearn.

preprocessing

import

StandardScaler

from

sklearn.

metrics

import

silhouette_score

import

warnings

warnings

.

filterwarnings

(

'ignore'

)

Ignore non-critical warnings

Set the visualization style

sns.

set_style

(

"whitegrid"

)

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

We will use a simulated customer dataset customer_data.csv, which typically contains the following features:

has the following content:

CustomerID,Age,Annual_Income_(k$),Spending_Score

1,19,15,39

2,21,15,81

3,20,16,6

4,23,16,77

5,31,17,40

6,22,17,76

7,35,18,6

8,23,18,94

9,64,19,3

10,30,19,72

11,67,20,14

12,35,20,99

13,58,21,15

14,24,21,77

15,37,22,13

16,22,22,79

17,35,23,35

18,20,23,66

19,52,24,29

20,35,24,98

21,46,25,35

22,25,25,73

23,54,26,5

24,28,26,73

25,45,27,28

26,23,28,82

27,40,28,36

28,35,28,61

29,60,29,4

30,21,30,87

31,62,30,17

32,23,30,73

33,18,31,92

34,49,33,14

35,21,33,81

36,42,34,17

37,30,34,73

38,36,37,26

39,20,37,75

40,65,38,35

41,24,38,92

42,48,39,36

43,31,39,61

44,49,40,29

45,24,40,98

46,50,41,15

47,27,42,65

48,29,43,88

49,31,43,19

50,49,44,75

Example

Load data

df

=

pd.

read_csv

(

'customer_data.csv'

)

print

(

"Data shape (rows, columns):"

,

df.

shape

)

print

(

"\nFirst 5 rows of data:"

)

print

(

df.

head

(

)

)

print

(

"\nBasic data information:"

)

print

(

df.

info

(

)

)

print

(

"\nDescriptive statistics:"

)

print

(

df.

describe

(

)

)

Output:



数据形状(行数,列数): (50, 4)



First 5 rows of data:

   CustomerID  Age  Annual_Income_(k$)  Spending_Score

0           1   19                  15              39

1           2   21                  15              81

2           3   20                  16               6

3           4   23                  16              77

4           5   31                  17              40



Basic data information:



RangeIndex: 50 entries, 0 to 49

Data columns (total 4 columns):

 #   Column              Non-Null Count  Dtype

---  ------              --------------  -----

 0   CustomerID          50 non-null     int64

 1   Age                 50 non-null     int64

 2   Annual_Income_(k$)  50 non-null     int64

 3   Spending_Score      50 non-null     int64

dtypes: int64(4)

memory usage: 1.7 KB

None



Descriptive statistics:

       CustomerID        Age  Annual_Income_(k$)  Spending_Score

count    50.00000  50.000000           50.000000       50.000000

mean     25.50000  35.560000           28.160000       51.680000

std      14.57738  14.283085            8.739682       31.506682

min       1.00000  18.000000           15.000000        3.000000

25%      13.25000  23.000000           21.000000       20.750000

50%      25.50000  31.000000           27.500000       61.000000

75%      37.75000  47.500000           36.250000       77.000000

max      50.00000  67.000000           44.000000       99.000000

Step 2: Data Exploration and Preprocessing

Before applying the algorithm, we must first understand the data and do a good job of "cleaning" it.

1. Exploratory Data Analysis Discover initial patterns through visualization and statistics.

Example

Visualize feature distributions

fig

,

axes

=

plt.

subplots

(

1

,

3

,

figsize

=

(

15

,

4

)

)

sns.

histplot

(

df

[

'Age'

]

,

bins

=

30

,

kde

=

True

,

ax

=

axes

[

0

]

)

axes

[

0

]

.

set_title

(

'Age distribution'

)

sns.

histplot

(

df

[

'Annual_Income_(k$)'

]

,

bins

=

30

,

kde

=

True

,

ax

=

axes

[

1

]

)

axes

[

1

]

.

set_title

(

'Annual income distribution'

)

sns.

histplot

(

df

[

'Spending_Score'

]

,

bins

=

30

,

kde

=

True

,

ax

=

axes

[

2

]

)

axes

[

2

]

.

set_title

(

'Spending score distribution'

)

plt.

tight_layout

(

)

plt.

show

(

)

Examine relationships between features

sns.

pairplot

(

df

[

[

'Age'

,

'Annual_Income_(k$)'

,

'Spending_Score'

]

]

)

plt.

suptitle

(

'Scatter plot matrix of feature relationships'

,

y

=

1.02

)

plt.

show

(

)

2. Data Preprocessing Clustering algorithms are very sensitive to feature scales (units). The value ranges of annual income (tens of thousands) and age (tens) differ greatly, which seriously affects distance calculations and causes the income feature to dominate the clustering result. Therefore, we need to performfeature standardization, scaling each feature to a standard normal distribution with mean 0 and variance 1.

Example

Select features for clustering

features

=

[

'Age'

,

'Annual_Income_(k$)'

,

'Spending_Score'

]

X

=

df

[

features

]

.

copy

(

)

feature standardization

scaler

=

StandardScaler

(

)

X_scaled

=

scaler.

fit_transform

(

X

)

fit computes the mean and variance; transform applies the transformation

X_scaled_df

=

pd.

DataFrame

(

X_scaled

,

columns

=

features

)

print

(

"First 5 rows of standardized data:"

)

print

(

X_scaled_df.

head

(

)

)

Step 3: Determining the Optimal Number of Clusters (K)

K-Means requires us to specify K in advance. How do we choose a reasonable K? We use two classic methods:

1. Elbow Method Plot the within-cluster sum of squares (Inertia) for different K values. Inertia decreases as K grows; we look for the elbow point (like an elbow) in the curve, after which the gain from a larger K (decrease in Inertia) becomes small.

Example

inertia

=

[

]

K_range

=

range

(

1

,

11

)

Test K from 1 to 10

for

k

in

K_range:

    kmeans

=

KMeans

(

n_clusters

=

k

,

random_state

=

42

,

n_init

=

'auto'

)

n_init='auto' is usage in newer versions

    kmeans.

fit

(

X_scaled

)

    inertia.

append

(

kmeans.

inertia_

)

Get the Inertia for that K value

Plot the elbow method chart

plt.

figure

(

figsize

=

(

8

,

5

)

)

plt.

plot

(

K_range

,

inertia

,

'bo-'

)

plt.

xlabel

(

'Number of clusters (K)'

)

plt.

ylabel

(

'Within-cluster sum of squares (Inertia)'

)

plt.

title

(

'Elbow method: choosing the best K value'

)

plt.

xticks

(

K_range

)

plt.

show

(

)

2. Silhouette Score Method The silhouette coefficient measures how similar a data point is to its own cluster (cohesion) and how separate it is from other clusters. Its value ranges from -1 to 1,the higher the better, indicating better clustering.

Example

silhouette_scores

=

[

]

K_range

=

range

(

2

,

11

)

The silhouette coefficient requires at least 2 clusters

for

k

in

K_range:

    kmeans

=

KMeans

(

n_clusters

=

k

,

random_state

=

42

,

n_init

=

'auto'

)

    cluster_labels

=

kmeans.

fit_predict

(

X_scaled

)

    score

=

silhouette_score

(

X_scaled

,

cluster_labels

)

    silhouette_scores.

append

(

score

)

Plot the silhouette coefficient chart

plt.

figure

(

figsize

=

(

8

,

5

)

)

plt.

plot

(

K_range

,

silhouette_scores

,

'go-'

)

plt.

xlabel

(

'Number of clusters (K)'

)

plt.

ylabel

(

'Silhouette coefficient'

)

plt.

title

(

'Silhouette method: choosing the best K value'

)

plt.

xticks

(

K_range

)

plt.

show

(

)

Combining the elbow method chart (elbow point) and the silhouette chart (peak), we assume that determining K=5 is a good choice.

Step 4: Applying K-Means for Clustering

Train the model with the chosen K value and assign a cluster label to each customer.

Example

Train the final model with K=5

final_k

=

5

kmeans_final

=

KMeans

(

n_clusters

=

final_k

,

random_state

=

42

,

n_init

=

'auto'

)

df

[

'Cluster'

]

=

kmeans_final.

fit_predict

(

X_scaled

)

Add cluster labels to the original DataFrame

View the number of customers in each cluster

cluster_counts

=

df

[

'Cluster'

]

.

value_counts

(

)

.

sort_index

(

)

print

(

"Distribution of customer counts per cluster:"

)

print

(

cluster_counts

)

View the feature means of each cluster (original scale)

cluster_profile

=

df.

groupby

(

'Cluster'

)

[

features

]

.

mean

(

)

.

round

(

2

)

print

(

"\nAverage feature values per cluster:"

)

print

(

cluster_profile

)

Step 5: Result Analysis and Visualization

Turn abstract cluster labels into intuitive insights.

1. Visualize the clustering result Since we have three features, we can select the two most important ones for visualization on a 2D plane (for example, income and spending score).

Example

Select two features for 2D visualization

plt.

figure

(

figsize

=

(

10

,

6

)

)

scatter

=

plt.

scatter

(

df

[

'Annual_Income_(k$)'

]

,

df

[

'Spending_Score'

]

,

                     c

=

df

[

'Cluster'

]

,

cmap

=

'viridis'

,

s

=

50

,

alpha

=

0.7

)

plt.

colorbar

(

scatter

,

label

=

'Cluster label'

)

plt.

xlabel

(

'Annual income (k$)'

)

plt.

ylabel

(

'Spending score'

)

plt.

title

(

'Customer segmentation result (based on annual income and spending score)'

)

plt.

show

(

)

2. Characterize customer profiles based on cluster_profile From this table, we can assign business meaning to each cluster:

Cluster label Age Annual income Spending score Possible customer profile
0 Medium High Low High-income cautious type: High income but conservative spending; likely savers or price-sensitive high-net-worth individuals.
1 Medium Low Low Low-income, low-spending type: Limited income and spending power; needs cost-effective products.
2 Medium Low High Value-seeking type: Not high income but loves to spend, focused on trends and experiences; a target for promotional campaigns.
3 Medium High High Ideal VIP type: High income and high spending; the core profit source for the enterprise, deserving top-tier service and exclusive benefits.
4 Young Medium Medium Young potential type: Young customers whose income and spending are still growing; key to cultivating brand loyalty.

Step 6: Model Evaluation and Application Recommendations

Evaluation: Besides the silhouette coefficient, you can check whether the sample distribution within clusters is balanced, and combine business logic to judge whether the segmentation is reasonable.

Application Recommendations:


Summary and Extension

Through this hands-on case, you have fully experienced the process of customer segmentation using the K-Means algorithm:Data Preparation -> Exploratory Analysis -> Preprocessing -> Determine K Value -> Train Model -> Analyze Results。

Review of Key Points: