/
customer2vec.qmd
374 lines (284 loc) · 12.5 KB
/
customer2vec.qmd
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
---
jupyter: python3
---
# Customer2Vec
In this notebook, we demonstrate how to learn embeddings for customers from transactional data using Doc2Vec. Each customer is viwed as a document, orders as sentences, and products as words. We also compare Customer2Vec with the baseline representations obtained using k-means on manually designed features.
### Data
We use an external dataset from the Instacart Market Basket Analysis competition (see [datasets](https://github.com/ikatsov/tensor-house/blob/master/resources/datasets.md)). Please download and unzip the dataset to 'data' folder before running this notebook.
### References
1. Arora S., Warrier D. -- Decoding Fashion Contexts Using Word Embeddings, 2016
1. Stiebellehner S., Wang J, Yuan S. -- Learning Continuous User Representations through Hybrid Filtering with doc2vec, 2017
```{python}
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
from tqdm.notebook import tqdm
import numpy as np
import os
from sklearn.manifold import TSNE
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn import preprocessing
pd.options.display.max_rows = 20
#matplotlib inline
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 500)
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import glob
from IPython.display import display, HTML
import multiprocessing as mp
print('Number of CPU cores:', mp.cpu_count())
```
# Step 1: Data Exploration and Preparation
```{python}
DATA_PATH = 'data/instacart'
files_list = glob.glob(f'{DATA_PATH}/*.csv')
data_dict = {}
for file in files_list:
print(f'Reading: {file}')
data = pd.read_csv(file)
print(data.info(show_counts=True))
data_dict[file.split('.')[0].split('/')[-1]] = data
print(f'Loaded data sets: {data_dict.keys()}')
```
# Step 2: Establish the Baselines
We start with designing several basic features and segmenting customers using this basic representation. Note that the dataset is limited and does not allow for advanced ferature engineering (there is no demographic data, etc).
### Step 2.1: Feature Engineering
```{python}
train_orders = data_dict['order_products__train']
prior_orders = data_dict['order_products__prior']
products = data_dict['products'].set_index('product_id')
orders = data_dict['orders']
prior_orders = prior_orders.merge(right=orders[['user_id','order_id','order_number']],on='order_id',how='left')
prior_orders.head()
```
```{python}
# Sample users to keep the problem computationaly tractable
USER_SUBSET = 50000
user_ids_sample = prior_orders['user_id'].sample(n=USER_SUBSET, replace=False)
```
```{python}
prior_orders_details = prior_orders[prior_orders.user_id.isin(user_ids_sample)].copy()
prior_orders_details['product_id'] = prior_orders_details['product_id'].astype(int)
prior_orders_details = prior_orders_details.merge(data_dict['products'], on='product_id', how='left')
prior_orders_details = prior_orders_details.merge(data_dict['aisles'], on='aisle_id', how='left')
prior_orders_details = prior_orders_details.merge(data_dict['departments'], on='department_id', how='left')
prior_orders_details.head()
```
```{python}
# Create basic user features: relative purchase frequences in each depertment/aisle
feature_department = pd.pivot_table(prior_orders_details, index=['user_id'], values=['product_id'], columns=['department'], aggfunc='count', fill_value=0)
feature_department = feature_department.div(feature_department.sum(axis=1), axis=0)
feature_department.columns = feature_department.columns.droplevel(0)
feature_department = feature_department.reset_index()
feature_aisle = pd.pivot_table(prior_orders_details, index=['user_id'], values=['product_id'], columns=['aisle'], aggfunc='count', fill_value=0)
feature_aisle = feature_aisle.div(feature_aisle.sum(axis=1), axis=0)
feature_aisle.columns = feature_aisle.columns.droplevel(0)
feature_aisle = feature_aisle.reset_index()
feature_df = feature_department.merge(feature_aisle, how='left', on='user_id').set_index('user_id')
feature_df.iloc[:5, :10] # show first 10 columns (departments) only
```
```{python}
len(feature_df.columns)
```
### Step 2.2: Visualize the Basic Space Using t-SNE
```{python}
from sklearn.preprocessing import MinMaxScaler
mm_scale = MinMaxScaler()
feature_df_scale = pd.DataFrame(mm_scale.fit_transform(feature_df),
columns=feature_df.columns,
index=feature_df.index.values)
tsne_doc_features = TSNE(n_components=2, verbose=1, perplexity=30, n_iter=500)
tsne_features_doc = tsne_doc_features.fit_transform(feature_df_scale.values)
```
```{python}
tsne_doc_features = pd.DataFrame({'user_id':feature_df.index.values})
tsne_doc_features['tsne-2d-one'] = tsne_features_doc[:,0]
tsne_doc_features['tsne-2d-two'] = tsne_features_doc[:,1]
```
```{python}
plt.figure(figsize=(16, 16))
sns.scatterplot(
x="tsne-2d-one", y="tsne-2d-two",
data=tsne_doc_features,
legend="full",
alpha=0.3
)
plt.show()
```
```{python}
# Computing silhouette scores for different clustering option
silhouette_list = []
for k in tqdm(range(2, 12, 2)):
clusters = KMeans(n_clusters=k, n_init = 10).fit(feature_df_scale).labels_.astype(float)
silhouette_avg = silhouette_score(feature_df_scale, clusters, metric="euclidean")
silhouette_list.append(silhouette_avg)
print(f'Silhouette score for {k} clusters is : {silhouette_avg:.4}')
```
```{python}
plt.figure(figsize=(10, 6))
plt.plot(range(2, 12, 2), silhouette_list)
```
Conclusions: We can see from the t-SNE visualization it is possible to detect 2-3 clusters, but the silhouette score is close to zero and this feature space is not a good choice for customer segmentation.
We should develop more advanced features and incorporate more domain knowledge to obtain better feature space for segmentation.
# Step 3: Customer2Vec Using Doc2Vec
In this and next section, we are learning and exploring the customer semantic space using Doc2Vec.
### Step 3.1: Data Preparation
```{python}
train_orders["product_id"] = train_orders["product_id"].astype(str)
prior_orders["product_id"] = prior_orders["product_id"].astype(str)
# It is important to sort order and products chronologically
prior_orders.sort_values(by=['user_id','order_number','add_to_cart_order'], inplace=True)
```
```{python}
combined_orders_by_user_id = prior_orders.groupby("user_id").apply(lambda order: ' '.join(order['product_id'].tolist()))
combined_orders_by_user_id = pd.DataFrame(combined_orders_by_user_id,columns=['all_orders'])
print(f'Number of orders: {combined_orders_by_user_id.shape[0]}')
combined_orders_by_user_id.reset_index(inplace=True)
combined_orders_by_user_id.user_id = combined_orders_by_user_id.user_id.astype(str)
combined_orders_by_user_id.head()
```
### Step 3.2: Train Doc2Vec model
We use implementation from Gensim adjusting the following parameters:
* documents = users (each user is represented by a chronologically sorted list of products)
* window - Maximum distance between the current and predicted word within a sentence.
* vector_size - Dimensionality of the word vectors.
* min_count - Ignores all words with total frequency lower than this.
Note that model training can take a long time (10+ hours).
```{python}
TRAIN_USER_MODEL = False # True - create a new model, False - load a previosuly created model
MODEL_DIR = 'models'
if not os.path.exists(MODEL_DIR):
os.makedirs(MODEL_DIR)
```
```{python}
from gensim.models.doc2vec import TaggedDocument, Doc2Vec
import timeit
import gensim
embeddings_dim = 200 # dimensionality of user representation
filename = f'models/customer2vec.{embeddings_dim}d.model'
if TRAIN_USER_MODEL:
class TaggedDocumentIterator(object):
def __init__(self, df):
self.df = df
def __iter__(self):
for row in self.df.itertuples():
yield TaggedDocument(words=dict(row._asdict())['all_orders'].split(),tags=[dict(row._asdict())['user_id']])
it = TaggedDocumentIterator(combined_orders_by_user_id)
doc_model = Doc2Vec(vector_size=embeddings_dim,
window=5,
min_count=10,
workers=mp.cpu_count(),
alpha=0.055,
min_alpha=0.055,
epochs=120) # use fixed learning rate
train_corpus = list(it)
doc_model.build_vocab(train_corpus)
for epoch in tqdm(range(10)):
doc_model.alpha -= 0.005 # decrease the learning rate
doc_model.min_alpha = doc_model.alpha # fix the learning rate, no decay
doc_model.train(train_corpus, total_examples=doc_model.corpus_count, epochs=doc_model.epochs)
print('Iteration:', epoch)
doc_model.save(filename)
print(f'Model saved to [{filename}]')
else:
doc_model = Doc2Vec.load(filename)
print(f'Model loaded from [{filename}]')
```
```{python}
vocab_doc = list(doc_model.dv.doctags.keys())
doc_vector_dict = {arg:doc_model.dv[arg] for arg in vocab_doc}
X_doc = pd.DataFrame(doc_vector_dict).T.values
X_doc.shape, len(vocab_doc), prior_orders["user_id"].nunique()
```
### Step 3.3: Visualize the Customer Semantic Space Using t-SNE
```{python}
user_ids_sample_str = set([str(id) for id in user_ids_sample])
idx = []
for i, user_id in enumerate(doc_vector_dict):
if user_id in user_ids_sample_str:
idx.append(i)
X_doc_subset = X_doc[idx] # only sampled user IDs
X_doc_subset.shape
```
```{python}
doc_vec_subset = pd.DataFrame(doc_vector_dict).T.iloc[idx]
doc_vec_subset.shape
```
```{python}
from sklearn.metrics import pairwise_distances
distance_matrix_doc = pairwise_distances(X_doc_subset, X_doc_subset, metric='cosine', n_jobs=-1)
tsne_doc = TSNE(metric="precomputed", n_components=2, verbose=1, perplexity=30, n_iter=500)
tsne_results_doc = tsne_doc.fit_transform(distance_matrix_doc)
```
```{python}
tsne_doc = pd.DataFrame()
tsne_doc['tsne-2d-one'] = tsne_results_doc[:,0]
tsne_doc['tsne-2d-two'] = tsne_results_doc[:,1]
```
```{python}
plt.figure(figsize=(16,16))
sns.scatterplot(
x="tsne-2d-one", y="tsne-2d-two",
data=tsne_doc,
legend="full",
alpha=0.3
)
plt.show()
```
### Step 3.4: Segmentation in the Customer Semantic Space Using t-SNE
```{python}
def cluster_cosine(X, k):
# normalization is equivalent to cosine distance
return KMeans(n_clusters=k).fit(preprocessing.normalize(X_doc_subset)).labels_.astype(float)
silhouette_list = []
for k in tqdm(range(2, 22, 1)):
latent_clusters = cluster_cosine(X_doc_subset, k)
silhouette_avg = silhouette_score(X_doc_subset, latent_clusters, metric="cosine")
silhouette_list.append(silhouette_avg)
print(f'Silhouette score for {k} clusters is : {silhouette_avg:.4}')
```
```{python}
plt.figure(figsize=(10,6))
plt.plot(range(2,22,1), silhouette_list);
```
```{python}
N_CLUSTER = 12
latent_clusters = cluster_cosine(X_doc_subset, N_CLUSTER)
doc_vec_end = doc_vec_subset.copy()
doc_vec_end['label'] = latent_clusters
tsne_doc['cluster'] = latent_clusters
doc_vec_end['label'].value_counts()
```
```{python}
plt.figure(figsize=(16, 16))
sns.scatterplot(
x="tsne-2d-one", y="tsne-2d-two",
hue='cluster',
palette=sns.color_palette("hls", tsne_doc['cluster'].nunique()),
data=tsne_doc,
legend="full",
alpha=0.3
);
plt.show();
```
```{python}
feature_df['latent_cluster'] = latent_clusters
department_names = np.setdiff1d(prior_orders_details['department'].unique(), ['other', 'missing'])
interpetation_department = feature_df.groupby('latent_cluster')[department_names].mean()
interpetation_department.T.div(interpetation_department.sum(axis=1)).round(3)
```
```{python}
interpetation_aisle = feature_df.groupby('latent_cluster')[feature_df.columns.values[16:-1]].mean()
interpetation_aisle.T.div(interpetation_aisle.sum(axis=1)).round(3).head(20)
```
```{python}
prior_orders_details_clustered = prior_orders_details.copy()
prior_orders_details_clustered = prior_orders_details_clustered.merge(feature_df['latent_cluster'], on='user_id', how='left')
for cluster_id in [7.0, 3.0]:
prior_orders_details_clustered[prior_orders_details_clustered['latent_cluster']==cluster_id][['user_id', 'product_name']].groupby("user_id").apply(lambda order: ' > '.join(order['product_name'])).reset_index().head(5)
```
Conclusions: Cluster 7 is clearly characterized by healthy products (vegetables, nonfat dairy, vitamins, etc). Cluster 3 has significant percentage of high-calorie products (sausage, bananas, frozen desserts, ice cream, pasta sause, etc).