-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecsys.html
1087 lines (989 loc) · 44.7 KB
/
recsys.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Recommender Systems</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/flatly.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<script src="site_libs/navigation-1.1/codefolding.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-5.1.0/css/all.css" rel="stylesheet" />
<link href="site_libs/font-awesome-5.1.0/css/v4-shims.css" rel="stylesheet" />
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 60px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 65px;
margin-top: -65px;
}
.section h2 {
padding-top: 65px;
margin-top: -65px;
}
.section h3 {
padding-top: 65px;
margin-top: -65px;
}
.section h4 {
padding-top: 65px;
margin-top: -65px;
}
.section h5 {
padding-top: 65px;
margin-top: -65px;
}
.section h6 {
padding-top: 65px;
margin-top: -65px;
}
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #ffffff;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
.code-folding-btn { margin-bottom: 4px; }
</style>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Real Statistics</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Case Studies
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="Rmarkdown.html">R and Rmarkdown</a>
</li>
<li>
<a href="recsys.html">Recommender Systems</a>
</li>
<li>
<a href="compositeIndex.html">Indicators</a>
</li>
<li>
<a href="stressTest.html">Stress Test</a>
</li>
<li>
<a href="clustering.html">Clustering</a>
</li>
<li>
<a href="webScraping.html">Web Scraping</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="aboutWeb.html">About</a>
</li>
<li>
<a href="https://github.com/aefdz/RealStatisticsAnalytics">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<div class="btn-group pull-right">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span>Code</span> <span class="caret"></span></button>
<ul class="dropdown-menu" style="min-width: 50px;">
<li><a id="rmd-show-all-code" href="#">Show All Code</a></li>
<li><a id="rmd-hide-all-code" href="#">Hide All Code</a></li>
</ul>
</div>
<h1 class="title toc-ignore">Recommender Systems</h1>
</div>
<div id="introduction" class="section level2">
<h2>Introduction</h2>
<p>Almost every people has received a recommendation from some Recommender System even if he/she has never heard about it. Selling websites like Amazon or simple browsers as Google’s are training models from data in order to provide the best product or website to their customers given some information such as sociodemographic characteristics, historical purchased products or likes in websites. Obviously, Recommender Systems (RecSys) are on the spot of many companies and institutions who are trying to provide the most adequate item for a given person.</p>
<p>In this session, we start by reviewing the different typologies of RecSys. Next, we formalize the problem and introduce the data sets of the case study. The first one is related to transactions in a grocery store and the second one contains users and its listened band music. Finally, we build from the scratch different RecSys methods and apply them for providing merchandasing strategies and product/groups recommendations. The code for applying Collaborative Filtering is not efficient since it is implemented by nested loop, however, in this way we can follow easily each step. The RData file that contains all the results can be dowload <a href="recsys/resultsCase2.RData">here</a>.</p>
<p><img src="recsys/recSys_example.png" /></p>
</div>
<div id="the-problem" class="section level2">
<h2>The problem</h2>
<p>Lets denote by <span class="math inline">\(U=\{u_1, u_2,...\}\)</span> the set of total users in the sample and <span class="math inline">\(I=\{i_1,i_2,...\}\)</span> the list of all items (goods or services) that a given user could consume. Our data set will consist in a binary matrix <span class="math inline">\(R\)</span> of dimension <span class="math inline">\(|U| \times |I|\)</span>, being <span class="math inline">\(|A|\)</span> the number of elements in the set <span class="math inline">\(A\)</span>.</p>
<p>The following table represents a data set of <span class="math inline">\(5\)</span> users and <span class="math inline">\(6\)</span> items.</p>
<pre class="r"><code>set.seed(01071991)
R=matrix(rbinom(30,1,0.5), nrow=5, ncol=6)
colnames(R)<-c('Item 1', 'Item 2','Item 3','Item 4','Item 5','Item 6')
rownames(R)<-c('User 1', 'User 2','User 3','User 4','User 5')
kable(R)</code></pre>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">Item 1</th>
<th align="right">Item 2</th>
<th align="right">Item 3</th>
<th align="right">Item 4</th>
<th align="right">Item 5</th>
<th align="right">Item 6</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>User 1</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">1</td>
</tr>
<tr class="even">
<td>User 2</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">1</td>
</tr>
<tr class="odd">
<td>User 3</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">1</td>
</tr>
<tr class="even">
<td>User 4</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="odd">
<td>User 5</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">1</td>
</tr>
</tbody>
</table>
<p>each cell <span class="math inline">\(R(u_i,i_j)=1\)</span> if the user <span class="math inline">\(u_i\)</span> has bought the product <span class="math inline">\(i_j\)</span> and <span class="math inline">\(0\)</span> otherwise. For instance, the User 1, <span class="math inline">\(u_1\)</span>, consumed <span class="math inline">\(I_{u_1}=\{i_3, i_4, i_6\}\)</span> while the User 3, <span class="math inline">\(u_3\)</span>, bought everything unless the item 4 <span class="math inline">\(I_{u_1}=\{i_1, i_2, i_3, i_5, i_6\}\)</span>.</p>
<p>The main goal of a RecSys is to propose a item to a user that 1) It has not been consumed by him/her but 2) the user would like the new item with high chance. Different definitions of what it is a item with ‘high chance’ yield diferent RecSys.</p>
<div id="groceries-data-set" class="section level3">
<h3>Groceries data set</h3>
<p>This data set gathers a collection of receipts with each line representing 1 receipt and the items purchased. The data set is available from R but it can be downloaded <a href="recsys/groceries.csv">groceries.csv</a>, however it comes by default with an special format. If the file is open by a plain text editor, one could observe that each row represents a enumeration of products corresponding with the items of a single transaction.</p>
<p>In the following chunk of code, we convert this format to a binary matrix as explained before. Each line is called a transaction and each column in a row represents an item.</p>
<pre class="r"><code>data(Groceries)
Shopping_Cart <- read.transactions("recsys/groceries.csv", sep=",")
dataMatrixGrocery<-as(Shopping_Cart, "matrix")*1; rownames(dataMatrixGrocery)<-c(1:nrow(dataMatrixGrocery))
kable(dataMatrixGrocery[10:15,160:169])</code></pre>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">UHT-milk</th>
<th align="right">vinegar</th>
<th align="right">waffles</th>
<th align="right">whipped/sour cream</th>
<th align="right">whisky</th>
<th align="right">white bread</th>
<th align="right">white wine</th>
<th align="right">whole milk</th>
<th align="right">yogurt</th>
<th align="right">zwieback</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>10</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>11</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="odd">
<td>12</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">1</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>13</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="odd">
<td>14</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>15</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
</tbody>
</table>
<p>We have in total 9835 transactions and 169 items. For example, in the transaction number <span class="math inline">\(10\)</span> was bought whole milk and in the number <span class="math inline">\(12\)</span> the client bought whole milk and yogurt among others.</p>
</div>
<div id="last.fm-data-set" class="section level3">
<h3>Last.FM data set</h3>
<p>The data set contains contains information about radio listener in Germany. The original data set contains information about users, their gender, their age, and which artists they have listened. However we will just used the artics that a given users have listened. data about a matrix where each row represents a user, and each column represents and band. The data set we use here can be download <a href="recsys/lastfmmatrix.csv">here</a>.</p>
<pre class="r"><code>dataMatrixMusicUsers <- read.csv(file="recsys/lastfmmatrix.csv"); rownames(dataMatrixMusicUsers)<-dataMatrixMusicUsers[,1]
dataMatrixMusic <- (dataMatrixMusicUsers[,!(names(dataMatrixMusicUsers) %in% c("user"))])</code></pre>
<p>Lets look at a sample of our data. We have in total 1257 users and 285 different bands. The output looks something like this:</p>
<pre class="r"><code>kable(dataMatrixMusic[20:25,c(1,2:8)])</code></pre>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">a.perfect.circle</th>
<th align="right">abba</th>
<th align="right">ac.dc</th>
<th align="right">adam.green</th>
<th align="right">aerosmith</th>
<th align="right">afi</th>
<th align="right">air</th>
<th align="right">alanis.morissette</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>383</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>422</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="odd">
<td>428</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">1</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>438</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="odd">
<td>447</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
<tr class="even">
<td>458</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
<td align="right">0</td>
</tr>
</tbody>
</table>
<p>For example, the user <span class="math inline">\(428\)</span> has listened ACDC.</p>
<p>##Taxonomy of RecSys</p>
<p>Mainly, the literature makes a different between:</p>
<ol style="list-style-type: decimal">
<li>Non-personalized and stereotype-based. Best-seller, most popular, trending hot…</li>
<li>Content Based. Uses the article data/information. At its core, content-based recommendation is based on the availability of (manually created or automatically extracted) item descriptions and a profile that assigns importance to these characteristics.</li>
<li>Colaborative Filtering. Use the users interactions with the items(like, viewed, fav). i) User based. Similarity between users. ii) Item based. Similarity between items. iii) Model based. Parametrized models.</li>
<li>Hybrid systems. Uses both 1 and 2.</li>
</ol>
<p>The following schema was taken from the arcicle “Recommendation systems: Principles, methods and evaluation” by Isinkaye et al (2015). The only difference is that the authors do not consider the Non-personalized and stereotype-based methods as a RecSys since they are mainly based on descriptive statistics.</p>
<p><img src="recsys/esquema.PNG" /></p>
</div>
</div>
<div id="contend-based-recsys" class="section level2">
<h2>Contend based RecSys</h2>
<p>Contend based methods take advantage of the information of the product. For example, if an user listens Metallica, a band of metal from the 90s, a possible recommendations would be 1) other bands of metal such as Audioslave, 2) a contemporaneous group such that ACDC, 3) other enemy group (literally) such as Megadeth or 4) a band as Exodus original group of one of the guitar players of Metallica.</p>
</div>
<div id="non-personalized-recsys" class="section level2">
<h2>Non-personalized RecSys</h2>
<p>Method based on descriptive statistics such us mean, mode, maximum, minimum… Below we have two examples, one from Amazon and another from Netflix. On one hand, the first one just recommends the iron machines that have been bought more times. On other hand, Netflix recommend the most times watched films/series.</p>
<center>
<img src="recsys/16.png" />
</center>
<p>For the Grocery data set one could conclude that milk should be located in a very visible place of the store since is the most common sell as we can see in the following frequency plot,</p>
<pre class="r"><code># Create an item frequency plot for the top 20 items
itemFrequencyPlot(Groceries,topN=20,type="absolute")</code></pre>
<p><img src="recsys_files/figure-html/unnamed-chunk-5-1.png" width="672" style="display: block; margin: auto;" /></p>
<p>About the bands data set, one could recommend to an user the group top ten of the most played, that is</p>
<pre class="r"><code>names(sort(colSums(dataMatrixMusic), decreasing=TRUE)[1:10])
## [1] "linkin.park" "coldplay" "red.hot.chili.peppers"
## [4] "rammstein" "system.of.a.down" "metallica"
## [7] "die.toten.hosen" "billy.talent" "the.killers"
## [10] "the.beatles"</code></pre>
</div>
<div id="colaborative-filtering-recsys" class="section level2">
<h2>Colaborative Filtering RecSys</h2>
<p>The basic idea of these systems is that if users have revealed the same interests in the past – if they listened or bought the same band or product, for instance – they will also have similar tastes in the future. So, if, for example, user <span class="math inline">\(u_{i_1}\)</span> and user <span class="math inline">\(u_{i_2}\)</span> have a history that is strongly similar each other and user <span class="math inline">\(u_{i_1}\)</span> has recently listened a group that <span class="math inline">\(u_{i_2}\)</span> has not, the basic rationale is to propose this group also to <span class="math inline">\(u_{i_2}\)</span>. In this way, the user <span class="math inline">\(u_{i_1}\)</span> <em>collaborates</em> to filter the most promising bands from a large set.</p>
<p>Following this logic one could predict and recommend items to users based on preference similarities. There are three types of collaborative filtering:</p>
<ul>
<li>Association rules.</li>
<li>Item Based Collaborative Filtering takes the <em>similarities</em> between items.</li>
<li>User Based Collaborative Filtering considers <em>similarities</em> between users.</li>
</ul>
<p>Association rules are a data mining technique that by product of an algorithm call ‘appriori’ ends up with a set of relations among items that can be studied with a probability approach. In contrast, the key issue of item based and user based collaborative filterin is how to define similarity. One could think about taking the distance such as <span class="math inline">\(L^P\)</span> or Hausdorff distance,. For example, consider that we want to measure the similarity between items <span class="math inline">\(i_1\)</span> and <span class="math inline">\(i_2\)</span> so its respective vectors are <span class="math inline">\(A=R(,i_1)\)</span> and <span class="math inline">\(B=R(,i_2)\)</span>. We could define the similarity of <span class="math inline">\(i_1\)</span> and <span class="math inline">\(i_2\)</span> as the distance <span class="math inline">\(d(i_1, i_2)=(\sum_{j=1}^{|U|}(R(,i_1)-R(,i_2))^p)^{1/p}\)</span> being very similar for values close to 0. However, the most employed measure is the so call Cosine Similarity defined as follows <span class="math display">\[ Similarity(A,B)=\frac{A B}{||A||_2 ||B||_2}=\frac{\sum_{j=1}^{|U|} A_j B_j}{\sqrt(\sum_{j=1}^{|U|}A_j^2)\sqrt(\sum_{j=1}^{|U|}B_j^2)}.\]</span></p>
<p>The important thing to know is that the resulting number represents how “similar” the vector <span class="math inline">\(A\)</span> is with respect the vector <span class="math inline">\(B\)</span>. The following chunk code is a function for computing the similarity between two vectors.</p>
<pre class="r"><code>getCosine <- function(x,y){
similarity <- sum(x*y) / (sqrt(sum(x*x)) * sqrt(sum(y*y)))
return(similarity)
}</code></pre>
<div id="association-rules" class="section level3">
<h3>Association Rules</h3>
<p>The outcome of this type of technique, in simple terms, is a set of rules that can be understood as “if this, then that”.</p>
<p>This gives us our rules which are represented as follows: <span class="math display">\[ \{ i_1,i_2 \} \rightarrow \{ i_k \}\]</span> Which can be read as “if a user buys an item in the item set on the left hand side, then the user will likely buy the item on the right hand side too”. A more human readable example is: <span class="math display">\[ \{coffee,sugar \} \rightarrow \{milk\}\]</span> If a customer buys coffee and sugar, then they are also likely to buy milk. With this we can understand three important ratios; the support, confidence and lift. We describe the significance of these in the following bullet points, but if you are interested in a formal mathematical definition you can find it on <a href="https://en.wikipedia.org/wiki/Association_rule_learning">wikipedia</a>.</p>
<p><strong>Support of item</strong> <span class="math inline">\(i_j\)</span>. The fraction of which our item set occurs in our dataset, in other words, the empirical probability of observing item <span class="math inline">\(i_j\)</span> if we select an item randomly.</p>
<p><strong>Confidence of</strong> <span class="math inline">\(i_{j_1} \rightarrow i_{j_2}\)</span>. Probability that a rule is correct for a new transaction with items on the left. Conditional probability of observing <span class="math inline">\(i_{j_2}\)</span> given that <span class="math inline">\(i_{j_1}\)</span> was observed.</p>
<p><span class="math display">\[P(i_{j_2} | i_{j_1}) = \frac{P(i_{j_2} \cap i_{j_1})}{P(i_{j_1})}\]</span></p>
<p><strong>Lift of</strong> <span class="math inline">\(i_{j_1} \rightarrow i_{j_2}\)</span>. The ratio by which the confidence of a rule exceeds the expected confidence. Probability of the itersecion divided by the product of the probabilities.</p>
<p><span class="math display">\[Lift(i_{j_1} \rightarrow i_{j_2})=\frac{P(i_{j_2} \cap i_{j_1})}{P(i_{j_2}) P( i_{j_1})},\]</span></p>
<p>If this number is <span class="math inline">\(1\)</span> it is because both items are independent.</p>
<p>We are now ready to mine some rules. It will be done by using the packages ‘aules’ and the function ‘apriori’ (name given by the algorithm that computes the rules). This function require a minimum support and confidence. We set the minimum support to 0.001. We set the minimum confidence of 0.8. We then show the top 5 rules,</p>
<pre class="r"><code># Get the rules
rules <- apriori(Groceries, parameter = list(supp = 0.001, conf = 0.8))
## Apriori
##
## Parameter specification:
## confidence minval smax arem aval originalSupport maxtime support minlen
## 0.8 0.1 1 none FALSE TRUE 5 0.001 1
## maxlen target ext
## 10 rules FALSE
##
## Algorithmic control:
## filter tree heap memopt load sort verbose
## 0.1 TRUE TRUE FALSE TRUE 2 TRUE
##
## Absolute minimum support count: 9
##
## set item appearances ...[0 item(s)] done [0.00s].
## set transactions ...[169 item(s), 9835 transaction(s)] done [0.02s].
## sorting and recoding items ... [157 item(s)] done [0.00s].
## creating transaction tree ... done [0.01s].
## checking subsets of size 1 2 3 4 5 6 done [0.07s].
## writing ... [410 rule(s)] done [0.01s].
## creating S4 object ... done [0.01s].
# Show the top 5 rules, but only 2 digits
options(digits=2)
inspect(rules[1:5])
## lhs rhs support confidence lift count
## [1] {liquor,red/blush wine} => {bottled beer} 0.0019 0.90 11.2 19
## [2] {curd,cereals} => {whole milk} 0.0010 0.91 3.6 10
## [3] {yogurt,cereals} => {whole milk} 0.0017 0.81 3.2 17
## [4] {butter,jam} => {whole milk} 0.0010 0.83 3.3 10
## [5] {soups,bottled beer} => {whole milk} 0.0011 0.92 3.6 11</code></pre>
<p>We can call the function summary for obtaining some more information about the result,</p>
<pre class="r"><code>summary(rules)
## set of 410 rules
##
## rule length distribution (lhs + rhs):sizes
## 3 4 5 6
## 29 229 140 12
##
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 3.0 4.0 4.0 4.3 5.0 6.0
##
## summary of quality measures:
## support confidence lift count
## Min. :0.00102 Min. :0.80 Min. : 3.1 Min. :10.0
## 1st Qu.:0.00102 1st Qu.:0.83 1st Qu.: 3.3 1st Qu.:10.0
## Median :0.00122 Median :0.85 Median : 3.6 Median :12.0
## Mean :0.00125 Mean :0.87 Mean : 4.0 Mean :12.3
## 3rd Qu.:0.00132 3rd Qu.:0.91 3rd Qu.: 4.3 3rd Qu.:13.0
## Max. :0.00315 Max. :1.00 Max. :11.2 Max. :31.0
##
## mining info:
## data ntransactions support confidence
## Groceries 9835 0.001 0.8</code></pre>
<p>Often we will want the most relevant rules first because, for example, one would want to have the most likely rules. We can easily sort by confidence by executing the following code.</p>
<pre class="r"><code>rules<-sort(rules, by="confidence", decreasing=TRUE)
inspect(rules[1:5])
## lhs rhs support confidence lift count
## [1] {rice,
## sugar} => {whole milk} 0.0012 1 3.9 12
## [2] {canned fish,
## hygiene articles} => {whole milk} 0.0011 1 3.9 11
## [3] {root vegetables,
## butter,
## rice} => {whole milk} 0.0010 1 3.9 10
## [4] {root vegetables,
## whipped/sour cream,
## flour} => {whole milk} 0.0017 1 3.9 17
## [5] {butter,
## soft cheese,
## domestic eggs} => {whole milk} 0.0010 1 3.9 10</code></pre>
<p>We can limit the number of items by including “maxlen” parameter to the apriori function,</p>
<pre class="r"><code>rules <- apriori(Groceries, parameter = list(supp = 0.001, conf = 0.8,maxlen=3))
## Apriori
##
## Parameter specification:
## confidence minval smax arem aval originalSupport maxtime support minlen
## 0.8 0.1 1 none FALSE TRUE 5 0.001 1
## maxlen target ext
## 3 rules FALSE
##
## Algorithmic control:
## filter tree heap memopt load sort verbose
## 0.1 TRUE TRUE FALSE TRUE 2 TRUE
##
## Absolute minimum support count: 9
##
## set item appearances ...[0 item(s)] done [0.00s].
## set transactions ...[169 item(s), 9835 transaction(s)] done [0.01s].
## sorting and recoding items ... [157 item(s)] done [0.00s].
## creating transaction tree ... done [0.00s].
## checking subsets of size 1 2 3 done [0.01s].
## writing ... [29 rule(s)] done [0.00s].
## creating S4 object ... done [0.00s].
inspect(rules[1:5])
## lhs rhs support confidence lift count
## [1] {liquor,red/blush wine} => {bottled beer} 0.0019 0.90 11.2 19
## [2] {curd,cereals} => {whole milk} 0.0010 0.91 3.6 10
## [3] {yogurt,cereals} => {whole milk} 0.0017 0.81 3.2 17
## [4] {butter,jam} => {whole milk} 0.0010 0.83 3.3 10
## [5] {soups,bottled beer} => {whole milk} 0.0011 0.92 3.6 11</code></pre>
<p>Now that we know how to generate rules, limit the output, lets say we wanted to target items to generate rules. There are two types of targets we might be interested in that are illustrated with an example of “whole milk”:</p>
<ul>
<li>What are customers likely to buy before buying whole milk</li>
<li>What are customers likely to buy if they purchase whole milk?</li>
</ul>
<p>This essentially means we want to set either the Left Hand Side and Right Hand Side. This is not difficult to do with R! Answering the first question we adjust our apriori() function as follows:</p>
<pre class="r"><code>rules<-apriori(data=Groceries, parameter=list(supp=0.001,conf = 0.08),
appearance = list(default="lhs",rhs="whole milk"),
control = list(verbose=F))
rules<-sort(rules, decreasing=TRUE,by="confidence")
inspect(rules[1:5])
## lhs rhs support confidence lift count
## [1] {rice,
## sugar} => {whole milk} 0.0012 1 3.9 12
## [2] {canned fish,
## hygiene articles} => {whole milk} 0.0011 1 3.9 11
## [3] {root vegetables,
## butter,
## rice} => {whole milk} 0.0010 1 3.9 10
## [4] {root vegetables,
## whipped/sour cream,
## flour} => {whole milk} 0.0017 1 3.9 17
## [5] {butter,
## soft cheese,
## domestic eggs} => {whole milk} 0.0010 1 3.9 10</code></pre>
<p>Likewise, we can set the left hand side to be “whole milk” and find its antecedents. Note the following:</p>
<ul>
<li>We set the confidence to 0.15 since we get no rules with 0.8</li>
<li>We set a minimum length of 2 to avoid empty left hand side items</li>
</ul>
<pre class="r"><code>rules<-apriori(data=Groceries, parameter=list(supp=0,conf =0.15,minlen=2),appearance=list(default="rhs",lhs="whole milk"),control = list(verbose=F))
rules<-sort(rules, decreasing=TRUE,by="confidence")
inspect(rules[1:5])
## lhs rhs support confidence lift count
## [1] {whole milk} => {other vegetables} 0.075 0.29 1.5 736
## [2] {whole milk} => {rolls/buns} 0.057 0.22 1.2 557
## [3] {whole milk} => {yogurt} 0.056 0.22 1.6 551
## [4] {whole milk} => {root vegetables} 0.049 0.19 1.8 481
## [5] {whole milk} => {tropical fruit} 0.042 0.17 1.6 416</code></pre>
</div>
<div id="item-based" class="section level3">
<h3>Item Based</h3>
<p>We first calculate the similarity of each song with the rest of the songs. This means that we want to compare each column in our “dataMatrixMusic” data set with every other column in the data set. Specifically, we will define similarity with the “Cosine Similarity”.</p>
<pre class="r"><code>dataMatrixMusic.similarity <- matrix(NA, nrow=ncol(dataMatrixMusic),ncol=ncol(dataMatrixMusic),dimnames=list(colnames(dataMatrixMusic),colnames(dataMatrixMusic)))
# Loop through the columns
for(i in 1:ncol(dataMatrixMusic)) {
# Loop through the columns for each column
for(j in 1:ncol(dataMatrixMusic)) {
# Fill in placeholder with cosine similarities
dataMatrixMusic.similarity[i,j]<-getCosine(as.matrix(dataMatrixMusic[i]),as.matrix(dataMatrixMusic[j]))
}
}
# Back to dataframe
dataMatrixMusic.similarity.Item <- as.data.frame(dataMatrixMusic.similarity)</code></pre>
<pre class="r"><code>#kable(dataMatrixMusic.similarity.Item[1:5,1:5])</code></pre>
<p>Note: For loops in R are infernally slow. We use as.matrix() to transform the columns into matrices since matrix operations run a lot faster. We transform the similarity matrix into a data.frame for later processes that we will use.</p>
<p>We are now in a position to make recommendations! We look at the top 10 neighbours of each song – those would be the recommendations we make to people listening to those songs. We start off by creating a placeholder and then we need to find the neighbours. This is another loop but runs much faster.</p>
<pre class="r"><code># Get the top 10 neighbours for each
top=10+1
dataMatrix.neighbours <- matrix(NA, nrow=ncol(dataMatrixMusic.similarity.Item),ncol=top,dimnames=list(colnames(dataMatrixMusic.similarity.Item)))
for(i in 1:ncol(dataMatrix.ibs)){
dataMatrix.neighbours[i,] <-(t(head(n=11,rownames(dataMatrixMusic.similarity.Item[order(dataMatrixMusic.similarity.Item[,i],decreasing=TRUE),][i]))))
}
colnames(dataMatrix.neighbours)<-c('band', paste('top', c(1:10), sep=''))
</code></pre>
<pre class="r"><code>#kable(dataMatrix.neighbours[1:5,2:top])</code></pre>
<p>This means for those listening to Abba we would recommend Madonna and Robbie Williams. Likewise for people listening to ACDC we would recommend the Red Hot Chilli Peppers and Metallica.</p>
</div>
<div id="user-based" class="section level3">
<h3>User Based</h3>
<p>We will need our similarity matrix for User Based recommendations.</p>
<pre class="r"><code>dataMatrixMusic.similarity <- matrix(NA, nrow=nrow(dataMatrixMusic),ncol=nrow(dataMatrixMusic),dimnames=list(rownames(dataMatrixMusic),rownames(dataMatrixMusic)))
# Loop through the columns
for(i in 1:ncol(dataMatrixMusic)) {
# Loop through the columns for each column
for(j in 1:ncol(dataMatrixMusic)) {
# Fill in placeholder with cosine similarities
dataMatrixMusic.similarity[i,j]<-getCosine(as.matrix(dataMatrixMusic[i]),as.matrix(dataMatrixMusic[j]))
}
}
# Back to dataframe
dataMatrixMusic.similarity.User <- as.data.frame(dataMatrixMusic.similarity)</code></pre>
<pre class="r"><code>#kable(dataMatrixMusic.similarity.User[1:5,1:5])</code></pre>
<p>The process behind creating a score matrix for the User Based recommendations is pretty straight forward:</p>
<ul>
<li>Choose an item and check if a user consumed that item</li>
<li>Get the similarities of that item’s top X neighbours</li>
<li>Get the consumption record of the user of the top X neighbours</li>
<li>Calculate the score with a formula: sumproduct(purchaseHistory, similarities)/sum(similarities)</li>
</ul>
<p>We can start by creating a helper function to calculate the score mentioned in the last step.</p>
<pre class="r"><code># Lets make a helper function to calculate the scores
getScore <- function(history, similarities)
{
x <- sum(history*similarities)/sum(similarities)
x
}</code></pre>
<pre class="r"><code>holder <- matrix(NA, nrow=nrow(dataMatrixMusicUsers),ncol=ncol(dataMatrixMusicUsers)-1,dimnames=list((dataMatrixMusicUsers$user),colnames(dataMatrixMusicUsers[-1])))
# Loop through the users (rows)
for(i in 1:nrow(holder))
{
# Loops through the products (columns)
for(j in 1:ncol(holder))
{
# Get the user's name and th product's name
user <- rownames(holder)[i]
product <- colnames(holder)[j]
# We do not want to recommend products you have already consumed
# If you have already consumed it, we store an empty string
if(as.integer(dataMatrixMusicUsers[dataMatrixMusicUsers$user==user,product]) == 1)
{
holder[i,j]<-""
} else {
# We first have to get a product's top 10 neighbours sorted by similarity
topN<-((head(n=11,(dataMatrixMusic.similarity.User[order(dataMatrixMusic.similarity.User[user,],decreasing=TRUE),][user]))))
topN.names <- as.character(rownames(topN))
topN.similarities <- as.numeric(topN[,1])
# Drop the first one because it will always be the same
topN.similarities<-topN.similarities[-1]
topN.names<-topN.names[-1]
# We then get the user's purchase history for those 10 items
topN.purchases<- dataMatrixMusicUsers[topN.names,]
topN.userPurchases<-topN.purchases[,product]
#topN.userPurchases <- as.numeric(topN.userPurchases[!(names(topN.userPurchases) %in% c("user"))])
# We then calculate the score for that product and that user
holder[i,j]<-getScore(similarities=topN.similarities,history=topN.userPurchases)
} # close else statement
} # end product for loop
} # end user for loop
dataMatrixMusic.user.scores <- holder
dataMatrixMusic.user.scores.holder <- matrix(NA, nrow=nrow(dataMatrixMusic.user.scores),ncol=100,dimnames=list(rownames(dataMatrixMusic.user.scores)))
for(i in 1:nrow(dataMatrixMusic.user.scores)){
dataMatrixMusic.user.scores.holder[i,] <- names(head(n=100,(dataMatrixMusic.user.scores[,order(dataMatrixMusic.user.scores[i,],decreasing=TRUE)])[i,]))
}</code></pre>
<p>The loop starts by taking each user (row) and then jumps into another loop that takes each column (artists). We then store the user’s name and artist name in variables to use them easily later. We then use an if statement to filter out artists that a user has already listened to – this is a business case decision.</p>
<p>The next bit gets the item based similarity scores for the artist under consideration.</p>
<p>It is important to note the number of artists you pick matters. We pick the top 10. We store the similarities score and song names. We also drop the first column because, as we saw, it always represents the same song. We’re almost there. We just need the user’s purchase history for the top 10 songs.</p>