-
Notifications
You must be signed in to change notification settings - Fork 0
/
Customers_Segmentation.Rmd
192 lines (153 loc) · 7.15 KB
/
Customers_Segmentation.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
---
title: ""
output:
html_document:
df_print: paged
code_folding: hide
---
```{r, include = FALSE}
library(readxl)
df <- read_excel(here::here("online_retail_II.xlsx"))
library(dplyr)
library(stringr)
df <- df %>%
filter(str_length(StockCode) == 5 |
str_detect(StockCode, "^\\d{5}[a-zA-Z]{1,2}$") |
str_detect(StockCode, "PADS|DCGS|SP|gift")) %>%
filter(Price != 0) %>%
mutate(CustomerID = as.character(`Customer ID`),
Country = na_if(Country, "Unspecified"), .keep = "unused", .after = Price)
```
In this analysis we will divide our customers into different segments based on their spending behaviors, not considering cancelled invoices and removing as well the missing values in the `CustomerID` column.
```{r}
df <- df %>%
filter(!str_starts(Invoice, "C") &
!is.na(CustomerID))
```
# - *preparations*
We can, for example, model their spending behaviors with these metrics.
```{r}
(clustdf <- df %>%
mutate(Expenses = Quantity * Price) %>%
group_by(CustomerID) %>%
summarise("Number of Invoices" = n_distinct(Invoice),
"Number of Distinct Items Invoiced" = n_distinct(StockCode),
"Total Quantity Purchased" = sum(Quantity),
"Total of Expenses" = round(sum(Expenses), 2)) %>%
left_join(df %>%
mutate(Expenses = Quantity * Price) %>%
group_by(CustomerID, Invoice) %>%
summarise("Total Quantity per Invoice" = sum(Quantity),
"Total Expenses per Invoice" = sum(Expenses), .groups = "drop_last") %>%
summarise("Rounded Median Quantity per Invoice" = round(median(`Total Quantity per Invoice`)),
"Rounded Median Revenues per Invoice" = round(median(`Total Expenses per Invoice`), 2)), by = "CustomerID"))
```
<br>
The algorithm we will use needs to know in advance how many segments (clusters in its jargon) we want.
To determine their number, we can use graphical methods like the following one,
```{r, message = FALSE}
set.seed(123)
#we set seeds as k-means may return different results for each run
clustdf_norm <- scale(clustdf[2:ncol(clustdf)])
#we z-score normalize the data to not have outliers influence the results
library(factoextra)
fviz_nbclust(clustdf_norm, kmeans, method = "wss", linecolor = "black") +
labs(subtitle = "Elbow method")
```
where we pick a value where the curve starts to get flat, meaning that the decrements in value of the measure on the y axis are not anymore significant as we increase the number of clusters.
We want that measure as small as possible, as it quantifies their "compactness" as the "distances" between its members, so with smaller distances we will have clusters that are more "closely-knit", more homogeneous.
With these premises, we choose `6` and we run the algorithm.
```{r}
set.seed(123)
kmclusters <- kmeans(clustdf_norm, centers = 6)
```
# - *analysis of results*
The clusters returned by the algorithm are very different in size, with one (number `1`) that dominates.
```{r}
knitr::kable(table(kmclusters$cluster), col.names = c("Cluster", "Number of Customers"))
```
<br>
We can continue by analyzing their differences according to the metrics designed at the beginning:
```{r}
clustdf$Cluster <- kmclusters$cluster
df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
mutate(Expenses = Quantity * Price) %>%
group_by(Cluster) %>%
summarise("Number of Invoices" = n_distinct(Invoice),
"Number of Distinct Items Invoiced" = n_distinct(StockCode),
"Total Quantity Purchased" = sum(Quantity),
"Total of Expenses" = round(sum(Expenses), 2)) %>%
left_join(df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
mutate(Expenses = Quantity * Price) %>%
group_by(Cluster, Invoice) %>%
summarise("Total Quantity per Invoice" = sum(Quantity),
"Total Expenses per Invoice" = sum(Expenses), .groups = "drop_last") %>%
summarise("Rounded Median Quantity per Invoice" = round(median(`Total Quantity per Invoice`)),
"Rounded Median Revenues per Invoice" = round(median(`Total Expenses per Invoice`), 2)), by = "Cluster")
```
<br>
Cluster number `3` is surely interesting: only `2` customers (`13687` and `13902`), for just `6` invoices, that contain large quantities of stock codes and that yield high revenues.
```{r}
df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
filter(Cluster == 3)
```
<br>
Another topic of investigation can be the geographic heterogeneity,
```{r}
df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
count(Cluster, wt = n_distinct(Country), name = "Number of Distinct Countries")
```
and clusters `2` and `4` seem rather restricted in that regard (besides number `3`, already examined).
```{r}
df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
filter(Cluster %in% c(2, 4)) %>%
distinct(Cluster, Country) %>%
arrange(Cluster)
```
<br>
Let's see now if there are some clusters with few customers from the `UK` (the country where more than `90%` of them reside),
```{r}
df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
distinct(Cluster, CustomerID, Country) %>%
mutate(UK = if_else(Country == "United Kingdom", TRUE, FALSE)) %>%
group_by(Cluster) %>%
summarise("Percentage of UK Customers" = formattable::percent(mean(UK, na.rm = TRUE)))
```
and number `4` seems to be the one (there are only `5` customers in it though).
```{r}
df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
filter(Cluster == 4) %>%
distinct(CustomerID, Country) %>%
arrange(CustomerID)
```
<br>
Likewise, let's see if there are clusters with mostly extra European countries,
```{r}
EU <- c("Austria", "Belgium", "Channel Islands", "Cyprus", "Denmark", "EIRE", "Finland", "France", "Germany", "Greece", "Iceland", "Italy", "Lithuania", "Malta", "Netherlands", "Norway", "Poland", "Portugal", "Spain", "Sweden", "Switzerland", "United Kingdom")
df %>%
left_join(clustdf %>%
select(CustomerID, Cluster), by = "CustomerID") %>%
distinct(Cluster, CustomerID, Country) %>%
mutate(is_EU = if_else(Country %in% EU, TRUE, FALSE)) %>%
group_by(Cluster) %>%
summarise("Percentage of EU Customers" = formattable::percent(mean(is_EU, na.rm = TRUE)))
```
but that is not the case.
<br>
# - *main takeaways and further developments*
In this first iteration of the application of a clustering algorithm we grouped our clients into `6` different ones according to some metrics meant to resume their spending behaviors. Following a brief analysis of the results, we discovered two clients (`13902` and `13687`) with very peculiar ones.
Many more things can be done hereafter; we can change the number of clusters to have either smaller or bigger groups, we can add, remove or modify the metrics we designed, we can change the clustering algorithm using one with different characteristics.