/
association_analysis.ipynb
1813 lines (1813 loc) · 74.7 KB
/
association_analysis.ipynb
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Association Rules Mining Using Python Generators to Handle Large Datasets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Motivation\n",
"I was looking to run association analysis in Python using the apriori algorithm to derive rules of the form {A} -> {B}. However, I quickly discovered that it's not part of the standard Python machine learning libraries. Although there are some implementations that exist, I could not find one capable of handling large datasets. \"Large\" in my case was an orders dataset with 32 million records, containing 3.2 million unique orders and about 50K unique items (file size just over 1 GB). So, I decided to write my own implementation, leveraging the apriori algorithm to generate simple {A} -> {B} association rules. Since I only care about understanding relationships between any given pair of items, using apriori to get to item sets of size 2 is sufficient. I went through various iterations, splitting the data into multiple subsets just so I could get functions like crosstab and combinations to run on my machine with 8 GB of memory. :) But even with this approach, I could only process about 1800 items before my kernel would crash... And that's when I learned about the wonderful world of Python generators.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Python Generators\n",
"\n",
"In a nutshell, a generator is a special type of function that returns an iterable sequence of items. However, unlike regular functions which return all the values at once (eg: returning all the elements of a list), a generator <i>yields</i> one value at a time. To get the next value in the set, we must ask for it - either by explicitly calling the generator's built-in \"next\" method, or implicitly via a for loop. This is a great property of generators because it means that we don't have to store all of the values in memory at once. We can load and process one value at a time, discard when finished and move on to process the next value. This feature makes generators perfect for creating item pairs and counting their frequency of co-occurence. Here's a concrete example of what we're trying to accomplish: \n",
"\n",
"1. Get all possible item pairs for a given order \n",
" eg: order 1: apple, egg, milk --> item pairs: {apple, egg}, {apple, milk}, {egg, milk}\n",
" order 2: egg, milk --> item pairs: {egg, milk}\n",
" \n",
"2. Count the number of times each item pair appears\n",
" eg: {apple, egg}: 1\n",
" {apple, milk}: 1\n",
" {egg, milk}: 2\n",
"\n",
"Here's the generator that implements the above tasks:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Counter({('apple', 'egg'): 1, ('apple', 'milk'): 1, ('egg', 'milk'): 2})"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import numpy as np\n",
"from itertools import combinations, groupby\n",
"from collections import Counter\n",
"\n",
"# Sample data\n",
"orders = np.array([[1,'apple'], [1,'egg'], [1,'milk'], [2,'egg'], [2,'milk']], dtype=object)\n",
"\n",
"# Generator that yields item pairs, one at a time\n",
"def get_item_pairs(order_item):\n",
" \n",
" # For each order, generate a list of items in that order\n",
" for order_id, order_object in groupby(orders, lambda x: x[0]):\n",
" item_list = [item[1] for item in order_object] \n",
" \n",
" # For each item list, generate item pairs, one at a time\n",
" for item_pair in combinations(item_list, 2):\n",
" yield item_pair \n",
"\n",
"\n",
"# Counter iterates through the item pairs returned by our generator and keeps a tally of their occurrence\n",
"Counter(get_item_pairs(orders))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<i>get_item_pairs()</i> generates a list of items for each order and produces item pairs for that order, one pair at a time. The first item pair is passed to Counter which keeps track of the number of times an item pair occurs. The next item pair is taken, and again, passed to Counter. This process continues until there are no more item pairs left. With this approach, we end up not using much memory as item pairs are discarded after the count is updated."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Apriori Algorithm \n",
"Apriori is an algorithm used to identify frequent item sets (in our case, item pairs). It does so using a \"bottom up\" approach, first identifying individual items that satisfy a minimum occurence threshold. It then extends the item set, adding one item at a time and checking if the resulting item set still satisfies the specified threshold. The algorithm stops when there are no more items to add that meet the minimum occurrence requirement. Here's an example of apriori in action, assuming a minimum occurence threshold of 3:\n",
"\n",
"\n",
" order 1: apple, egg, milk \n",
" order 2: carrot, milk \n",
" order 3: apple, egg, carrot\n",
" order 4: apple, egg\n",
" order 5: apple, carrot\n",
"\n",
" \n",
" Iteration 1: Count the number of times each item occurs \n",
" item set occurrence count \n",
" {apple} 4 \n",
" {egg} 3 \n",
" {milk} 2 \n",
" {carrot} 2 \n",
"\n",
" {milk} and {carrot} are eliminated because they do not meet the minimum occurrence threshold.\n",
"\n",
"\n",
" Iteration 2: Build item sets of size 2 using the remaining items from Iteration 1 (ie: apple, egg) \n",
" item set occurence count \n",
" {apple, egg} 3 \n",
"\n",
" Only {apple, egg} remains and the algorithm stops since there are no more items to add.\n",
" \n",
" \n",
"If we had more orders and items, we can continue to iterate, building item sets consisting of more than 2 elements. For the problem we are trying to solve \n",
"(ie: finding relationships between pairs of items), it suffices to implement apriori to get to item sets of size 2."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Association Rules Mining\n",
"Once the item sets have been generated using apriori, we can start mining association rules. Given that we are only looking at item sets of size 2, the association rules we will generate will be of the form {A} -> {B}. One common application of these rules is in the domain of recommender systems, where customers who purchased item A are recommended item B.\n",
"\n",
"Here are 3 key metrics to consider when evaluating association rules:\n",
"\n",
"1. <b>support</b> \n",
" This is the percentage of orders that contains the item set. In the example above, there are 5 orders in total \n",
" and {apple,egg} occurs in 3 of them, so: \n",
" \n",
" support{apple,egg} = 3/5 or 60%\n",
" \n",
" The minimum support threshold required by apriori can be set based on knowledge of your domain. In this \n",
" grocery dataset for example, since there could be thousands of distinct items and an order can contain \n",
" only a small fraction of these items, setting the support threshold to 0.01% may be reasonable.<br><br><br>\n",
" \n",
"2. <b>confidence</b> \n",
" Given two items, A and B, confidence measures the percentage of times that item B is purchased, given that \n",
" item A was purchased. This is expressed as:\n",
" \n",
" confidence{A->B} = support{A,B} / support{A} \n",
" \n",
" Confidence values range from 0 to 1, where 0 indicates that B is never purchased when A is purchased, and 1 \n",
" indicates that B is always purchased whenever A is purchased. Note that the confidence measure is directional. This means that we can also compute the percentage of times that item A is purchased, given that item B was \n",
" purchased:\n",
" \n",
" confidence{B->A} = support{A,B} / support{B} \n",
" \n",
" In our example, the percentage of times that egg is purchased, given that apple was purchased is: \n",
" \n",
" confidence{apple->egg} = support{apple,egg} / support{apple}\n",
" = (3/5) / (4/5)\n",
" = 0.75 or 75%\n",
"\n",
" A confidence value of 0.75 implies that out of all orders that contain apple, 75% of them also contain egg. Now, \n",
" we look at the confidence measure in the opposite direction (ie: egg->apple): \n",
" \n",
" confidence{egg->apple} = support{apple,egg} / support{egg}\n",
" = (3/5) / (3/5)\n",
" = 1 or 100% \n",
" \n",
" Here we see that all of the orders that contain egg also contain apple. But, does this mean that there is a \n",
" relationship between these two items, or are they occurring together in the same orders simply by chance? To \n",
" answer this question, we look at another measure which takes into account the popularity of <i>both</i> items.<br><br><br> \n",
" \n",
"3. <b>lift</b> \n",
" Given two items, A and B, lift indicates whether there is a relationship between A and B, or whether the two items \n",
" are occuring together in the same orders simply by chance (ie: at random). Unlike the confidence metric whose \n",
" value may vary depending on direction (eg: confidence{A->B} may be different from confidence{B->A}), \n",
" lift has no direction. This means that the lift{A,B} is always equal to the lift{B,A}: \n",
" \n",
" lift{A,B} = lift{B,A} = support{A,B} / (support{A} * support{B}) \n",
" \n",
" In our example, we compute lift as follows:\n",
" \n",
" lift{apple,egg} = lift{egg,apple} = support{apple,egg} / (support{apple} * support{egg})\n",
" = (3/5) / (4/5 * 3/5) \n",
" = 1.25 \n",
" \n",
" One way to understand lift is to think of the denominator as the likelihood that A and B will appear in the same \n",
" order if there was <i>no</i> relationship between them. In the example above, if apple occurred in 80% of the\n",
" orders and egg occurred in 60% of the orders, then if there was no relationship between them, we would \n",
" <i>expect</i> both of them to show up together in the same order 48% of the time (ie: 80% * 60%). The numerator, \n",
" on the other hand, represents how often apple and egg <i>actually</i> appear together in the same order. In \n",
" this example, that is 60% of the time. Taking the numerator and dividing it by the denominator, we get to how \n",
" many more times apple and egg actually appear in the same order, compared to if there was no relationship between them (ie: that they are occurring together simply at random). \n",
" \n",
" In summary, lift can take on the following values:\n",
" \n",
" * lift = 1 implies no relationship between A and B. \n",
" (ie: A and B occur together only by chance)\n",
" \n",
" * lift > 1 implies that there is a positive relationship between A and B.\n",
" (ie: A and B occur together more often than random)\n",
" \n",
" * lift < 1 implies that there is a negative relationship between A and B.\n",
" (ie: A and B occur together less often than random)\n",
" \n",
" In our example, apple and egg occur together 1.25 times <i>more</i> than random, so we conclude that there exists \n",
" a positive relationship between them.\n",
" \n",
"Armed with knowledge of apriori and association rules mining, let's dive into the data and code to see what relationships we unravel!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Input Dataset\n",
"Instacart, an online grocer, has graciously made some of their datasets accessible to the public. The order and product datasets that we will be using can be downloaded from the link below, along with the data dictionary:\n",
"\n",
"“The Instacart Online Grocery Shopping Dataset 2017”, Accessed from https://www.instacart.com/datasets/grocery-shopping-2017 on September 1, 2017.<br><br>"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import sys\n",
"from itertools import combinations, groupby\n",
"from collections import Counter"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Function that returns the size of an object in MB\n",
"def size(obj):\n",
" return \"{0:.2f} MB\".format(sys.getsizeof(obj) / (1000 * 1000))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 1: Data Preparation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### A. Load order data"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"orders -- dimensions: (32434489, 4); size: 1037.90 MB\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>order_id</th>\n",
" <th>product_id</th>\n",
" <th>add_to_cart_order</th>\n",
" <th>reordered</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>2</td>\n",
" <td>33120</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>2</td>\n",
" <td>28985</td>\n",
" <td>2</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>2</td>\n",
" <td>9327</td>\n",
" <td>3</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>2</td>\n",
" <td>45918</td>\n",
" <td>4</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>2</td>\n",
" <td>30035</td>\n",
" <td>5</td>\n",
" <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" order_id product_id add_to_cart_order reordered\n",
"0 2 33120 1 1\n",
"1 2 28985 2 1\n",
"2 2 9327 3 0\n",
"3 2 45918 4 1\n",
"4 2 30035 5 0"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"orders = pd.read_csv('order_products__prior.csv')\n",
"print('orders -- dimensions: {0}; size: {1}'.format(orders.shape, size(orders)))\n",
"display(orders.head())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### B. Convert order data into format expected by the association rules function"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"order_id\n",
"2 33120\n",
"2 28985\n",
"2 9327\n",
"2 45918\n",
"2 30035\n",
"2 17794\n",
"2 40141\n",
"2 1819\n",
"2 43668\n",
"3 33754\n",
"Name: item_id, dtype: int64"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"pandas.core.series.Series"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Convert from DataFrame to a Series, with order_id as index and item_id as value\n",
"orders = orders.set_index('order_id')['product_id'].rename('item_id')\n",
"display(orders.head(10))\n",
"type(orders)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### C. Display summary statistics for order data"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"orders -- dimensions: (32434489,); size: 518.95 MB; unique_orders: 3214874; unique_items: 49677\n"
]
}
],
"source": [
"print('orders -- dimensions: {0}; size: {1}; unique_orders: {2}; unique_items: {3}'\n",
" .format(orders.shape, size(orders), len(orders.index.unique()), len(orders.value_counts())))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2: Association Rules Function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### A. Helper functions to the main association rules function"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": [
"# Returns frequency counts for items and item pairs\n",
"def freq(iterable):\n",
" if type(iterable) == pd.core.series.Series:\n",
" return iterable.value_counts().rename(\"freq\")\n",
" else: \n",
" return pd.Series(Counter(iterable)).rename(\"freq\")\n",
"\n",
" \n",
"# Returns number of unique orders\n",
"def order_count(order_item):\n",
" return len(set(order_item.index))\n",
"\n",
"\n",
"# Returns generator that yields item pairs, one at a time\n",
"def get_item_pairs(order_item):\n",
" order_item = order_item.reset_index().as_matrix()\n",
" for order_id, order_object in groupby(order_item, lambda x: x[0]):\n",
" item_list = [item[1] for item in order_object]\n",
" \n",
" for item_pair in combinations(item_list, 2):\n",
" yield item_pair\n",
" \n",
"\n",
"# Returns frequency and support associated with item\n",
"def merge_item_stats(item_pairs, item_stats):\n",
" return (item_pairs\n",
" .merge(item_stats.rename(columns={'freq': 'freqA', 'support': 'supportA'}), left_on='item_A', right_index=True)\n",
" .merge(item_stats.rename(columns={'freq': 'freqB', 'support': 'supportB'}), left_on='item_B', right_index=True))\n",
"\n",
"\n",
"# Returns name associated with item\n",
"def merge_item_name(rules, item_name):\n",
" columns = ['itemA','itemB','freqAB','supportAB','freqA','supportA','freqB','supportB', \n",
" 'confidenceAtoB','confidenceBtoA','lift']\n",
" rules = (rules\n",
" .merge(item_name.rename(columns={'item_name': 'itemA'}), left_on='item_A', right_on='item_id')\n",
" .merge(item_name.rename(columns={'item_name': 'itemB'}), left_on='item_B', right_on='item_id'))\n",
" return rules[columns] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### B. Association rules function"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def association_rules(order_item, min_support):\n",
"\n",
" print(\"Starting order_item: {:22d}\".format(len(order_item)))\n",
"\n",
"\n",
" # Calculate item frequency and support\n",
" item_stats = freq(order_item).to_frame(\"freq\")\n",
" item_stats['support'] = item_stats['freq'] / order_count(order_item) * 100\n",
"\n",
"\n",
" # Filter from order_item items below min support \n",
" qualifying_items = item_stats[item_stats['support'] >= min_support].index\n",
" order_item = order_item[order_item.isin(qualifying_items)]\n",
"\n",
" print(\"Items with support >= {}: {:15d}\".format(min_support, len(qualifying_items)))\n",
" print(\"Remaining order_item: {:21d}\".format(len(order_item)))\n",
"\n",
"\n",
" # Filter from order_item orders with less than 2 items\n",
" order_size = freq(order_item.index)\n",
" qualifying_orders = order_size[order_size >= 2].index\n",
" order_item = order_item[order_item.index.isin(qualifying_orders)]\n",
"\n",
" print(\"Remaining orders with 2+ items: {:11d}\".format(len(qualifying_orders)))\n",
" print(\"Remaining order_item: {:21d}\".format(len(order_item)))\n",
"\n",
"\n",
" # Recalculate item frequency and support\n",
" item_stats = freq(order_item).to_frame(\"freq\")\n",
" item_stats['support'] = item_stats['freq'] / order_count(order_item) * 100\n",
"\n",
"\n",
" # Get item pairs generator\n",
" item_pair_gen = get_item_pairs(order_item)\n",
"\n",
"\n",
" # Calculate item pair frequency and support\n",
" item_pairs = freq(item_pair_gen).to_frame(\"freqAB\")\n",
" item_pairs['supportAB'] = item_pairs['freqAB'] / len(qualifying_orders) * 100\n",
"\n",
" print(\"Item pairs: {:31d}\".format(len(item_pairs)))\n",
"\n",
"\n",
" # Filter from item_pairs those below min support\n",
" item_pairs = item_pairs[item_pairs['supportAB'] >= min_support]\n",
"\n",
" print(\"Item pairs with support >= {}: {:10d}\\n\".format(min_support, len(item_pairs)))\n",
"\n",
"\n",
" # Create table of association rules and compute relevant metrics\n",
" item_pairs = item_pairs.reset_index().rename(columns={'level_0': 'item_A', 'level_1': 'item_B'})\n",
" item_pairs = merge_item_stats(item_pairs, item_stats)\n",
" \n",
" item_pairs['confidenceAtoB'] = item_pairs['supportAB'] / item_pairs['supportA']\n",
" item_pairs['confidenceBtoA'] = item_pairs['supportAB'] / item_pairs['supportB']\n",
" item_pairs['lift'] = item_pairs['supportAB'] / (item_pairs['supportA'] * item_pairs['supportB'])\n",
" \n",
"\n",
" # Return association rules sorted by lift in descending order\n",
" return item_pairs.sort_values('lift', ascending=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 3: Association Rules Mining"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Starting order_item: 32434489\n",
"Items with support >= 0.01: 10906\n",
"Remaining order_item: 29843570\n",
"Remaining orders with 2+ items: 3013325\n",
"Remaining order_item: 29662716\n",
"Item pairs: 30622410\n",
"Item pairs with support >= 0.01: 48751\n",
"\n",
"CPU times: user 10min 22s, sys: 47.6 s, total: 11min 9s\n",
"Wall time: 11min 40s\n"
]
}
],
"source": [
"%%time\n",
"rules = association_rules(orders, 0.01) "
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>itemA</th>\n",
" <th>itemB</th>\n",
" <th>freqAB</th>\n",
" <th>supportAB</th>\n",
" <th>freqA</th>\n",
" <th>supportA</th>\n",
" <th>freqB</th>\n",
" <th>supportB</th>\n",
" <th>confidenceAtoB</th>\n",
" <th>confidenceBtoA</th>\n",
" <th>lift</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>Organic Strawberry Chia Lowfat 2% Cottage Cheese</td>\n",
" <td>Organic Cottage Cheese Blueberry Acai Chia</td>\n",
" <td>306</td>\n",
" <td>0.010155</td>\n",
" <td>1163</td>\n",
" <td>0.038595</td>\n",
" <td>839</td>\n",
" <td>0.027843</td>\n",
" <td>0.263113</td>\n",
" <td>0.364720</td>\n",
" <td>9.449868</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>Grain Free Chicken Formula Cat Food</td>\n",
" <td>Grain Free Turkey Formula Cat Food</td>\n",
" <td>318</td>\n",
" <td>0.010553</td>\n",
" <td>1809</td>\n",
" <td>0.060033</td>\n",
" <td>879</td>\n",
" <td>0.029170</td>\n",
" <td>0.175788</td>\n",
" <td>0.361775</td>\n",
" <td>6.026229</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>Organic Fruit Yogurt Smoothie Mixed Berry</td>\n",
" <td>Apple Blueberry Fruit Yogurt Smoothie</td>\n",
" <td>349</td>\n",
" <td>0.011582</td>\n",
" <td>1518</td>\n",
" <td>0.050376</td>\n",
" <td>1249</td>\n",
" <td>0.041449</td>\n",
" <td>0.229908</td>\n",
" <td>0.279424</td>\n",
" <td>5.546732</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9</th>\n",
" <td>Nonfat Strawberry With Fruit On The Bottom Gre...</td>\n",
" <td>0% Greek, Blueberry on the Bottom Yogurt</td>\n",
" <td>409</td>\n",
" <td>0.013573</td>\n",
" <td>1666</td>\n",
" <td>0.055288</td>\n",
" <td>1391</td>\n",
" <td>0.046162</td>\n",
" <td>0.245498</td>\n",
" <td>0.294033</td>\n",
" <td>5.318230</td>\n",
" </tr>\n",
" <tr>\n",
" <th>10</th>\n",
" <td>Organic Grapefruit Ginger Sparkling Yerba Mate</td>\n",
" <td>Cranberry Pomegranate Sparkling Yerba Mate</td>\n",
" <td>351</td>\n",
" <td>0.011648</td>\n",
" <td>1731</td>\n",
" <td>0.057445</td>\n",
" <td>1149</td>\n",
" <td>0.038131</td>\n",
" <td>0.202773</td>\n",
" <td>0.305483</td>\n",
" <td>5.317849</td>\n",
" </tr>\n",
" <tr>\n",
" <th>11</th>\n",
" <td>Baby Food Pouch - Roasted Carrot Spinach & Beans</td>\n",
" <td>Baby Food Pouch - Butternut Squash, Carrot & C...</td>\n",
" <td>332</td>\n",
" <td>0.011018</td>\n",
" <td>1503</td>\n",
" <td>0.049878</td>\n",
" <td>1290</td>\n",
" <td>0.042810</td>\n",
" <td>0.220892</td>\n",
" <td>0.257364</td>\n",
" <td>5.159830</td>\n",
" </tr>\n",
" <tr>\n",
" <th>12</th>\n",
" <td>Unsweetened Whole Milk Mixed Berry Greek Yogurt</td>\n",
" <td>Unsweetened Whole Milk Blueberry Greek Yogurt</td>\n",
" <td>438</td>\n",
" <td>0.014535</td>\n",
" <td>1622</td>\n",
" <td>0.053828</td>\n",
" <td>1621</td>\n",
" <td>0.053794</td>\n",
" <td>0.270037</td>\n",
" <td>0.270204</td>\n",
" <td>5.019798</td>\n",
" </tr>\n",
" <tr>\n",
" <th>23</th>\n",
" <td>Uncured Cracked Pepper Beef</td>\n",
" <td>Chipotle Beef & Pork Realstick</td>\n",
" <td>410</td>\n",
" <td>0.013606</td>\n",
" <td>1839</td>\n",
" <td>0.061029</td>\n",
" <td>1370</td>\n",
" <td>0.045465</td>\n",
" <td>0.222947</td>\n",
" <td>0.299270</td>\n",
" <td>4.903741</td>\n",
" </tr>\n",
" <tr>\n",
" <th>24</th>\n",
" <td>Organic Mango Yogurt</td>\n",
" <td>Organic Whole Milk Washington Black Cherry Yogurt</td>\n",
" <td>334</td>\n",
" <td>0.011084</td>\n",
" <td>1675</td>\n",
" <td>0.055586</td>\n",
" <td>1390</td>\n",
" <td>0.046128</td>\n",
" <td>0.199403</td>\n",
" <td>0.240288</td>\n",
" <td>4.322777</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>Grain Free Chicken Formula Cat Food</td>\n",
" <td>Grain Free Turkey & Salmon Formula Cat Food</td>\n",
" <td>391</td>\n",
" <td>0.012976</td>\n",
" <td>1809</td>\n",
" <td>0.060033</td>\n",
" <td>1553</td>\n",
" <td>0.051538</td>\n",
" <td>0.216142</td>\n",
" <td>0.251771</td>\n",
" <td>4.193848</td>\n",
" </tr>\n",
" <tr>\n",
" <th>25</th>\n",
" <td>Raspberry Essence Water</td>\n",
" <td>Unsweetened Pomegranate Essence Water</td>\n",
" <td>366</td>\n",
" <td>0.012146</td>\n",
" <td>2025</td>\n",
" <td>0.067202</td>\n",
" <td>1304</td>\n",
" <td>0.043274</td>\n",
" <td>0.180741</td>\n",
" <td>0.280675</td>\n",
" <td>4.176615</td>\n",
" </tr>\n",
" <tr>\n",
" <th>13</th>\n",
" <td>Unsweetened Whole Milk Strawberry Yogurt</td>\n",
" <td>Unsweetened Whole Milk Blueberry Greek Yogurt</td>\n",
" <td>440</td>\n",
" <td>0.014602</td>\n",
" <td>1965</td>\n",
" <td>0.065210</td>\n",
" <td>1621</td>\n",
" <td>0.053794</td>\n",
" <td>0.223919</td>\n",
" <td>0.271437</td>\n",
" <td>4.162489</td>\n",
" </tr>\n",
" <tr>\n",
" <th>14</th>\n",
" <td>Unsweetened Whole Milk Peach Greek Yogurt</td>\n",
" <td>Unsweetened Whole Milk Blueberry Greek Yogurt</td>\n",
" <td>421</td>\n",
" <td>0.013971</td>\n",
" <td>1922</td>\n",
" <td>0.063783</td>\n",
" <td>1621</td>\n",
" <td>0.053794</td>\n",
" <td>0.219043</td>\n",
" <td>0.259716</td>\n",
" <td>4.071849</td>\n",
" </tr>\n",
" <tr>\n",
" <th>44</th>\n",
" <td>Oh My Yog! Pacific Coast Strawberry Trilayer Y...</td>\n",
" <td>Oh My Yog! Organic Wild Quebec Blueberry Cream...</td>\n",
" <td>860</td>\n",
" <td>0.028540</td>\n",
" <td>2857</td>\n",
" <td>0.094812</td>\n",
" <td>2271</td>\n",
" <td>0.075365</td>\n",
" <td>0.301015</td>\n",
" <td>0.378688</td>\n",
" <td>3.994083</td>\n",
" </tr>\n",
" <tr>\n",
" <th>55</th>\n",
" <td>Mighty 4 Kale, Strawberry, Amaranth & Greek Yo...</td>\n",
" <td>Mighty 4 Essential Tots Spinach, Kiwi, Barley ...</td>\n",
" <td>390</td>\n",
" <td>0.012943</td>\n",
" <td>2206</td>\n",
" <td>0.073208</td>\n",
" <td>1337</td>\n",
" <td>0.044370</td>\n",
" <td>0.176791</td>\n",
" <td>0.291698</td>\n",
" <td>3.984498</td>\n",
" </tr>\n",
" <tr>\n",
" <th>20</th>\n",
" <td>Unsweetened Whole Milk Peach Greek Yogurt</td>\n",
" <td>Unsweetened Whole Milk Strawberry Yogurt</td>\n",
" <td>499</td>\n",
" <td>0.016560</td>\n",
" <td>1922</td>\n",
" <td>0.063783</td>\n",
" <td>1965</td>\n",
" <td>0.065210</td>\n",
" <td>0.259625</td>\n",
" <td>0.253944</td>\n",
" <td>3.981352</td>\n",
" </tr>\n",
" <tr>\n",
" <th>65</th>\n",
" <td>0% Greek, Blueberry on the Bottom Yogurt</td>\n",
" <td>Nonfat Strawberry With Fruit On The Bottom Gre...</td>\n",
" <td>305</td>\n",
" <td>0.010122</td>\n",
" <td>1391</td>\n",
" <td>0.046162</td>\n",
" <td>1666</td>\n",
" <td>0.055288</td>\n",
" <td>0.219267</td>\n",
" <td>0.183073</td>\n",
" <td>3.965918</td>\n",
" </tr>\n",
" <tr>\n",
" <th>15</th>\n",
" <td>Unsweetened Whole Milk Mixed Berry Greek Yogurt</td>\n",
" <td>Unsweetened Whole Milk Peach Greek Yogurt</td>\n",
" <td>410</td>\n",
" <td>0.013606</td>\n",
" <td>1622</td>\n",
" <td>0.053828</td>\n",
" <td>1922</td>\n",
" <td>0.063783</td>\n",
" <td>0.252774</td>\n",
" <td>0.213319</td>\n",
" <td>3.963014</td>\n",
" </tr>\n",
" <tr>\n",
" <th>43</th>\n",
" <td>Unsweetened Whole Milk Peach Greek Yogurt</td>\n",
" <td>Unsweetened Whole Milk Mixed Berry Greek Yogurt</td>\n",
" <td>407</td>\n",
" <td>0.013507</td>\n",
" <td>1922</td>\n",
" <td>0.063783</td>\n",
" <td>1622</td>\n",
" <td>0.053828</td>\n",
" <td>0.211759</td>\n",
" <td>0.250925</td>\n",
" <td>3.934016</td>\n",
" </tr>\n",
" <tr>\n",
" <th>26</th>\n",
" <td>Unsweetened Blackberry Water</td>\n",
" <td>Unsweetened Pomegranate Essence Water</td>\n",
" <td>494</td>\n",
" <td>0.016394</td>\n",
" <td>3114</td>\n",
" <td>0.103341</td>\n",
" <td>1304</td>\n",
" <td>0.043274</td>\n",
" <td>0.158638</td>\n",
" <td>0.378834</td>\n",
" <td>3.665867</td>\n",
" </tr>\n",
" <tr>\n",
" <th>19</th>\n",
" <td>Unsweetened Whole Milk Mixed Berry Greek Yogurt</td>\n",
" <td>Unsweetened Whole Milk Strawberry Yogurt</td>\n",
" <td>383</td>\n",
" <td>0.012710</td>\n",
" <td>1622</td>\n",
" <td>0.053828</td>\n",
" <td>1965</td>\n",
" <td>0.065210</td>\n",
" <td>0.236128</td>\n",
" <td>0.194911</td>\n",
" <td>3.621024</td>\n",
" </tr>\n",
" <tr>\n",
" <th>16</th>\n",
" <td>Unsweetened Whole Milk Strawberry Yogurt</td>\n",
" <td>Unsweetened Whole Milk Peach Greek Yogurt</td>\n",
" <td>444</td>\n",
" <td>0.014735</td>\n",
" <td>1965</td>\n",
" <td>0.065210</td>\n",
" <td>1922</td>\n",
" <td>0.063783</td>\n",
" <td>0.225954</td>\n",
" <td>0.231009</td>\n",
" <td>3.542526</td>\n",
" </tr>\n",
" <tr>\n",
" <th>56</th>\n",
" <td>Mighty 4 Sweet Potato, Blueberry, Millet & Gre...</td>\n",
" <td>Mighty 4 Essential Tots Spinach, Kiwi, Barley ...</td>\n",
" <td>398</td>\n",
" <td>0.013208</td>\n",
" <td>2534</td>\n",
" <td>0.084093</td>\n",
" <td>1337</td>\n",
" <td>0.044370</td>\n",
" <td>0.157064</td>\n",
" <td>0.297681</td>\n",
" <td>3.539900</td>\n",
" </tr>\n",
" <tr>\n",
" <th>74</th>\n",
" <td>Sweet Potatoes Stage 2</td>\n",
" <td>Organic Stage 2 Winter Squash Baby Food Puree</td>\n",
" <td>322</td>\n",
" <td>0.010686</td>\n",
" <td>2077</td>\n",
" <td>0.068927</td>\n",
" <td>1322</td>\n",
" <td>0.043872</td>\n",
" <td>0.155031</td>\n",
" <td>0.243570</td>\n",
" <td>3.533734</td>\n",
" </tr>\n",
" <tr>\n",
" <th>79</th>\n",
" <td>Compostable Forks</td>\n",
" <td>Plastic Spoons</td>\n",
" <td>321</td>\n",
" <td>0.010653</td>\n",
" <td>1528</td>\n",
" <td>0.050708</td>\n",
" <td>1838</td>\n",
" <td>0.060996</td>\n",
" <td>0.210079</td>\n",
" <td>0.174646</td>\n",
" <td>3.444151</td>\n",
" </tr>\n",
" <tr>\n",