-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproduct_embeddings.qmd
365 lines (268 loc) · 11.9 KB
/
product_embeddings.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
---
title: "Untitled"
format: html
editor: visual
---
## Notes
- Data sources:
- https://archive.ics.uci.edu/dataset/352/online+retail
- https://archive.ics.uci.edu/dataset/502/online+retail+ii
- Other literature:
- https://anhornsby.github.io/embeddings-retail/#/
- https://www.dunnhumby.com/resources/blog/science-data/en/how-to-solve-the-problem-of-product-similarity-with-data-science/
- https://www.youtube.com/watch?v=0uWCGn-1KRE
```{r message=FALSE}
library(tidyverse)
library(magrittr)
library(ggplot2)
library(tictoc)
library(word2vec)
source("./product_embeddings_fn.r")
options(dplyr.summarise.inform = FALSE)
```
## Load and prepare data
...
```{r}
transactions_df <- readr::read_csv("../dunnhumby_complete/dunnhumby_The-Complete-Journey CSV/transaction_data.csv")
transactions_df %<>% mutate( list_price = (SALES_VALUE-RETAIL_DISC-COUPON_DISC)/QUANTITY )
transactions_df %<>% mutate( month = floor(((DAY-1) %% 365 ) / 31) )
transactions_df %<>% mutate( wday = ((DAY-1) %% 7) )
transactions_df %<>% mutate( hour = stringr::str_sub(TRANS_TIME, 0, 2) )
transactions_df %<>% filter( QUANTITY > 0, list_price > 0 )
transactions_df
```
```{r}
# make sure that there is only one row per transaction id/product id combination
transactions_summary_df <- transactions_df %>%
group_by(month, wday, hour, BASKET_ID, PRODUCT_ID) %>%
summarize( quantity = sum(QUANTITY),
list_price_avg = mean(list_price, na.rm=T)
)
```
```{r}
product_df <- readr::read_csv("../dunnhumby_complete/dunnhumby_The-Complete-Journey CSV/product.csv")
product_df
```
## Filter data and roll up to basekets
```{r}
# plot histogram of product frequencies
product_freq <- transactions_summary_df %>%
group_by(PRODUCT_ID) %>%
summarize(total_quantity = sum(quantity)) %>%
arrange(desc(total_quantity))
```
```{r}
# determine and mark the top 500 products as calibration targets for hyper-parameter tuning
set.seed(1234)
n_test_products <- 200
calibration_products_df <- sample_n(product_freq[1:1500,], n_test_products) %>%
select(PRODUCT_ID) %>%
mutate(is_calibration = T)
calibration_products_df %<>% mutate( PRODUCT_ID_ALT = paste0(PRODUCT_ID, "X") )
calibration_products <- calibration_products_df$PRODUCT_ID %>% as.character()
# mark calibration products
product_df %<>% left_join( calibration_products_df, by = "PRODUCT_ID" )
product_df %<>% mutate( is_calibration = ifelse(!is.na(is_calibration), is_calibration, FALSE) )
```
```{r}
# identify all product ids which have been bought fewer than five times
unpopular_products <- product_freq %>% filter(total_quantity <= 5) %>% select(PRODUCT_ID)
# drop all of those rarely purchased products
transactions_summary_df %<>% anti_join( unpopular_products, by = "PRODUCT_ID" )
```
```{r}
#
product_labels_df <- product_df %>% select(PRODUCT_ID, is_calibration, PRODUCT_ID_ALT)
transactions_summary_df %<>%
left_join(product_labels_df, by = "PRODUCT_ID") %>%
group_by(PRODUCT_ID) %>%
mutate( is_calibration = ifelse(!is.na(is_calibration), is_calibration, FALSE) ) %>%
mutate( ind_use_alternative_label = ifelse(is_calibration, sample_bool_approx_equal_n(n()), F) )
transactions_summary_df %<>%
mutate( PRODUCT_LABEL = ifelse(ind_use_alternative_label, PRODUCT_ID_ALT, as.character(PRODUCT_ID) ))
```
```{r}
# roll up transactions to strings
transaction_baskets_df <-
transactions_summary_df %>%
group_by(BASKET_ID) %>%
summarize( basket_label_lst = list(c(PRODUCT_LABEL, paste0("M",month[1]), paste0("WD",wday[1]), paste0("H",hour[1]))),
basket_id_lst = list(c(PRODUCT_ID, paste0("M",month[1]), paste0("WD",wday[1]), paste0("H",hour[1])))
)
transaction_baskets_df$basket_label <- transaction_baskets_df$basket_label_lst %>% sapply( function(x) paste(sample(x), collapse = " "))
transaction_baskets_df$basket_id <- transaction_baskets_df$basket_id_lst %>% sapply( function(x) paste(sample(x), collapse = " "))
```
## Calibration Products Statistics
```{r}
list_prices_df <- transactions_summary_df %>%
#semi_join( calibration_products_df, by = "PRODUCT_ID" ) %>%
group_by(PRODUCT_LABEL) %>%
filter( quantity > 0, list_price_avg > 0 ) %>%
summarize(list_price_avg = mean(list_price_avg, na.rm=T),
list_price_sd = sd(list_price_avg, na.rm=T) )
list_price <- list_prices_df$list_price_avg %T>% {names(.) <- list_prices_df$PRODUCT_LABEL}
log_list_price <- log(list_price)
```
```{r eval=FALSE}
log_similarity_price_relative <- function(log_price_1, log_prices_2) {
-1 * abs(log_prices_2 - log_price_1)
}
log_similarity_price_absolute <- function(price_1, prices_2) {
-1 * abs(prices_2 - price_1)
}
log_similarity_price <- function(price_1, prices_2, log_price_1, log_prices_2) {
log_similarity_price_absolute(price_1, prices_2) + log_similarity_price_relative(log_price_1, log_prices_2)
}
```
```{r}
# products are considered to not be potential substitutes if the price difference is (i) larger than max_price_delta *and* (ii) the price ratio is larger than log(max_price_ratio)
max_price_delta <- 5
max_price_ratio <- 1.2
mismatch_mat <-
sapply(list_price[calibration_products], \(price_1) {
abs(list_price-price_1) > max_price_delta & abs(log(list_price)-log(price_1)) > log(max_price_ratio)
})
match_mat <-
sapply(calibration_products, \(product_1) {
product_1 == names(list_price) %T>% {names(.) <- names(list_price) }
})
```
```{r eval=FALSE}
log_prior_similarity_mat <-
log( (seasonality_weekly_corr_upper/2 + .5) ) +
log( (seasonality_monthly_corr_upper/2 + .5) ) +
log_similarity_price_mat
```
```{r eval=FALSE}
validation_products <- product_freq$PRODUCT_ID[1:1500]
validation_products_info_df <- product_df %>% filter(PRODUCT_ID %in% validation_products)
validation_products_dept <- validation_products_info_df %>% {names(.$DEPARTMENT) <- .$PRODUCT_ID; .$DEPARTMENT }
validation_products_dept_match_mat <-
sapply(validation_products_dept, \(dept_1) {
sapply(validation_products_dept, \(dept_2) { dept_1 == dept_2 })
})
```
## Hyper-parameter Tuning for Word2Vec
### Effect of Dimensionality, Window Size, and number of Iterations
```{r}
set.seed(12345678)
params <- crossing(dim = c(5, 10, 20, 30, 40, 50, 75, 100, 125, 150),
window = c(10, 20, 30, 40, 50),
n_resampled_baskets = c(1, 2),
iter = c(10, 20, 30)) #c(10, 25, 50)) #, 10, 15))
fit <- params %>% group_by(dim, window, n_resampled_baskets, iter) %>%
summarize( fit = evaluate_model_loglik(baskets = transaction_baskets_df$basket_label_lst,
calibration_products = calibration_products,
dim = dim,
window = window,
n_resampled_baskets = n_resampled_baskets,
iter = iter))
```
```{r}
fit %>%
#filter(dim > 10, dim <= 50) %>% #n_resampled_baskets == 1,
ggplot(aes(dim, fit, color = as.factor(window))) +
geom_point() + geom_line() + theme_bw() + facet_grid(n_resampled_baskets~iter) + theme(legend.position = "top")
```
```{r}
fit %>%
filter(dim > 10, dim <= 50, n_resampled_baskets == 1, window == 30) %>% #,
ggplot(aes(dim, fit, color = as.factor(window))) +
geom_point() + geom_line() + theme_bw() + facet_grid(n_resampled_baskets~iter) + theme(legend.position = "top")
```
## Validate Tuned Hyper-Parameters
```{r eval=FALSE}
params <- crossing(dim = c(2, 10, 20, 50, 100, 150), window = c(10, 15))
val_fit <- params %>% group_by(dim, window) %>%
summarize( fit = evaluate_model_by_dept_match(calibration_products,
validation_products_dept_match_mat,
dim, window) )
params2 <- crossing(dim = c(200, 250, 300, 400, 500, 600), window = c(15, 20))
val_fit2 <- params2 %>% group_by(dim, window) %>%
summarize( fit = evaluate_model_by_dept_match(calibration_products,
validation_products_dept_match_mat,
dim, window) )
params3 <- crossing(dim = c(800, 1000, 1200, 1500), window = c(15, 20, 30))
val_fit3 <- params3 %>% group_by(dim, window) %>%
summarize( fit = evaluate_model_by_dept_match(calibration_products,
validation_products_dept_match_mat,
dim, window) )
params4 <- crossing(dim = c(1750, 2000, 2500, 3000), window = c(30, 40))
val_fit4 <- params4 %>% group_by(dim, window) %>%
summarize( fit = evaluate_model_by_dept_match(calibration_products,
validation_products_dept_match_mat,
dim, window) )
params5 <- crossing(dim = c(3500, 4000), window = c(30, 40, 50))
val_fit5 <- params5 %>% group_by(dim, window) %>%
summarize( fit = evaluate_model_by_dept_match(calibration_products,
validation_products_dept_match_mat,
dim, window) )
val_fit %>% bind_rows(val_fit2) %>% bind_rows(val_fit3) %>%
bind_rows(val_fit4) %>% bind_rows(val_fit5) %>%
filter(dim >= 200) %>%
ggplot(aes(dim, fit, color = as.factor(window) )) + geom_point() + geom_line() + theme_bw()
```
## Inspect Examples
```{r}
n_models = 250
dim_embedding = 30
embeddings <- embeddings_ensemble_word2vec(baskets = transaction_baskets_df$basket_label_lst,
dim = dim_embedding,
window = 30, iter = 30,
n_models = n_models)
```
```{r}
vocabulary <- rownames(embeddings[[1]])
n_vocabulary = length(vocabulary)
embeddings <- lapply(embeddings, \(x) x[vocabulary,])
embeddings_arr <- array(unlist(embeddings), dim = c(n_vocabulary, dim_embedding, n_models))
dim(embeddings_arr)
target_products <- calibration_products %>% intersect(vocabulary)
idx_products <- seq_along(vocabulary) %T>% {names(.) <- vocabulary }
idx_target_products <- idx_products[target_products]
```
```{r}
{
tic()
similarities_df <- compute_similarities(embeddings,
idx_products = idx_products,
idx_target_products = idx_target_products[1:20]
)
toc() # 10.157 sec elapsed
}
```
```{r}
cur_similarities_df <- similarities_df[[10]]
product_df$PRODUCT_ID %<>% as.character()
cur_similarities_df %<>% left_join(product_df, by = c("product_2"="PRODUCT_ID"))
cur_similarities_df$se %<>% round(1)
View(cur_similarities_df %>% filter(lower > .8))
```
```{r}
sim_fn <- function(i) {
word2vec::word2vec_similarity(embeddings[[i]]["1101771",], embeddings[[i]]["1101771X",], type = "cosine")/2+0.5
}
similarities <- sapply(1:250, \(i) sim_fn(i) )
quantile(similarities, c(.025, .975))
```
```{r}
product_similarities <-
purrr::map(calibration_products, function(cur_product) {
compute_ensemble_similarities(embeddings, target = cur_product)
}, .progress = T )
#
#
# word2vec_similarities <- compute_similarities(embeddings_lst, target = cur_product)
# # head(word2vec_similarities)
# # similar_products_df <- word2vec_similarities %>% filter(similarity_est > .85)
#
# # #if (nrow(similar_products_df) > 1)
# # {
# # similar_products_df$product_id %<>% as.integer()
# # similar_products_df %<>% left_join(product_df, by = c("product_id"="PRODUCT_ID"))
# # print(similar_products_df)
# # #break
# # }
# } )
#word2vec_similarities_df
```